import React from 'react';
import { arrayMove, SortEnd } from 'react-sortable-hoc';
import { UploadContainer } from './container';
import { YUploadProps, ChangeType } from './upload.interface';
import { useModel } from './upload.useModel';

const DragUploadContainer: React.FC<YUploadProps> = (props) => {
  const { isOss, projectId, featureName, ossDir, isVertical, isDrag } = props;
  const {
    uploadType: baseUploadType,
    securityType: baseSecurityType,
    maxShow: baseMaxShow,
    column: baseColumn, 
    ...ohterProps
  }  = props;
  // 一些选填参数的默认处理
  const uploadType = baseUploadType || "uploadPicture";
  const securityType = isOss && projectId && (featureName || ossDir) ? (baseSecurityType || 'private') : 'public';
  const maxShow = uploadType === 'uploadPicture' ? baseMaxShow : undefined;
  const column = maxShow && !isDrag ? undefined : baseColumn;
  const dealCol = isVertical ? 1 : column;
  
  const { fileListRef, refreshValue, fileList, setFileList } = useModel({ ...props, securityType });

  return (
    <UploadContainer
      {...ohterProps}
      securityType={securityType}
      uploadType={uploadType}
      maxShow={maxShow}
      column={dealCol}
      refreshValue={refreshValue}
      fileListRef={fileListRef}
      distance={1}
      axis="xy"
      helperClass="SortableHelper"
      setFileList={setFileList}
      items={fileList}
      onSortEnd={({ oldIndex, newIndex }: SortEnd) => {
        if (oldIndex !== newIndex) {
          setFileList(arrayMove(fileList, oldIndex, newIndex), [], ChangeType.DRAG);
        }
      }}
    />
  )
}

export class YUpload extends React.Component<YUploadProps> {
  // 缩略图模式
  static Thumbnail (props: YUploadProps) {
    return <DragUploadContainer {...props} uploadType="thumbnail" />
  }
  // 列表模式
  static File (props: YUploadProps) {
    return <DragUploadContainer {...props} uploadType="uploadFile" />
  }
  // 默认大图模式
  render () {
    return (
      <DragUploadContainer {...this.props} />
    );
  }
}
