import React, { useEffect, useState } from 'react';
import { message, Upload, UploadProps } from 'antd';
import uploadApi from './api';

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: 'picture-card',
    fileSize: 2,
    fileLength: 1,
    fileType: ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'],
    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('上传文件-->', res);
      const isType = fileType?.includes(res.type);
      const isSize = res.size / 1024 / 1024 < (fileSize || 2);
      const isLength = fileList.length < (fileLength || 1);
      if (!isType) {
        message.error('上传文件格式错误！').then();
      }
      if (!isSize) {
        message.error(`文件最大${props.fileSize}M，请压缩后上传！`).then();
      }
      if (!isLength) {
        message.error(`最多上传${fileLength || 1}个文件`).then();
      }
      return isType && isSize && isLength;
    },
    customRequest: (res) => {
      if (fileUpload) {
        setFileList([
          ...fileList,
          {
            id: new Date().getTime(),
            uid: new Date().getTime(),
            name: (res.file as any).name,
            type: (res.file as any).type,
            url: (res.file as any).url,
            status: 'uploading',
          },
        ]);
        // 上传到服务器
        const formData = new FormData();
        formData.append('uploadFile', res.file);
        uploadApi.uploadFile(formData).then(({ result, code }) => {
          if (code === '200') {
            setFileList([
              ...fileList,
              {
                id: new Date().getTime(),
                uid: new Date().getTime(),
                name: (res.file as any).name || '',
                url: result,
                type: (res.file as any).type,
                status: 'done',
              },
            ]);
            onChange?.([
              ...fileList,
              {
                id: new Date().getTime(),
                uid: new Date().getTime(),
                name: (res.file as any).name || '',
                url: result,
                type: (res.file as any).type,
                status: 'done',
              },
            ]);
          }
        });
      } else {
        setFileList([...fileList, res.file]);
        onChange?.([...fileList, res.file]);
      }
    },
    onRemove: (res) => {
      const newFileList = fileList.filter((item) => item.uid !== res.uid);
      setFileList(newFileList);
      onChange?.(newFileList);
    },
    // onPreview: { onPreview },
  };
  useEffect(() => {
    // 如果有默认文件列表
    if (defaultFileList?.length) {
      setFileList(defaultFileList);
    } else {
      setFileList([]);
    }
  }, [defaultFileList]);
  return (
    <div className='uploader-view'>
      <Upload {...uploadProps} style={{ width: '100%' }}>
        {children}
      </Upload>
    </div>
  );
};
