import React, { useEffect, useState } from 'react';
import { message, Upload, UploadProps } from 'antd';
// import { UploadFile } from "antd/es/upload/interface";
import { CommonAPI } from '~/api';
import './index.scss';

interface PropsType {
  listType?: 'text' | 'picture' | 'picture-card'; // 上传列表的内建样式
  fileSize?: number; // 文件大小
  fileType?: string[]; // 上传文件类型
  fileUpload: boolean; // 是否上传到服务器(返回文件流还是返回上传后的地址)
  fileLength?: number; // 最大上传文件数量
  children: React.ReactNode; // 上传按钮
  onChange?: (
    fileList: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => void; // 上传文件改变时的状态
  defaultFileList?: any[]; // 默认文件列表
}
export const Uploader: React.FC<PropsType> = (props) => {
  Uploader.defaultProps = {
    listType: 'text',
    fileSize: 2,
    fileLength: 1,
    fileType: ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp'],
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onChange: () => {},
    defaultFileList: [],
  };
  const {
    fileType = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp'],
    children,
    listType,
    fileSize,
    fileUpload,
    fileLength,
    onChange,
    defaultFileList,
  } = props;
  const [fileList, setFileList] = useState<any[]>([]);
  // 上传文件配置
  const uploadProps: UploadProps = {
    listType,
    fileList,
    beforeUpload: (res) => {
      // console.log(fileType, res.type);
      const isType = fileType?.includes(res.type);
      const isSize = res.size / 1024 / 1024 < (fileSize || 2);
      if (!isType) {
        message.error('请上传正确的格式!').then();
        return isType;
      }
      if (!isSize) {
        message.error('文件最大2M，请压缩后上传！').then();
        return isSize;
      }
    },
    customRequest: (res) => {
      if (fileList.length >= (fileLength || 1)) {
        message.error(`最多上传${fileLength || 1}个文件`).then();
        return;
      }
      if (fileUpload) {
        // 上传到服务器
        const formData = new FormData();
        formData.append('uploadFile', res.file);
        CommonAPI.uploadOss(formData).then(
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          (val: { result: { filePath: string } }) => {
            setFileList([
              ...fileList,
              {
                id: new Date().getTime(),
                uid: new Date().getTime(),
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                name: res.file.name,
                url: val.result.filePath,
              },
            ]);
            onChange?.([
              ...fileList,
              {
                id: new Date().getTime(),
                uid: new Date().getTime(),
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                name: res.file.name,
                url: val.result.filePath,
              },
            ]);
          },
        );
      } else {
        setFileList([...fileList, res.file]);
        onChange?.([...fileList, res.file]);
      }
    },
    onRemove: (res) => {
      const newFileList = fileList.filter((item) => item.uid !== res.uid);
      setFileList(newFileList);
    },
    // onPreview: { onPreview },
  };
  useEffect(() => {
    // 如果有默认文件列表
    if (defaultFileList?.length) {
      setFileList(defaultFileList);
    }
  }, [defaultFileList]);
  return (
    <div className='uploader-view'>
      {listType === 'text' ? (
        <Upload {...uploadProps} style={{ width: '100%' }}>
          <>{fileList.length < (fileLength || 1) && children}</>
        </Upload>
      ) : (
        <Upload {...uploadProps} style={{ width: '100%' }}>
          {fileList.length < (fileLength || 1) && children}
        </Upload>
      )}
    </div>
  );
};
