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

interface PropsType {
  listType?: 'text' | 'picture' | 'picture-card'; // 上传列表的内建样式
  fileSize?: number; // 文件大小
  fileType?: string[]; // 上传文件类型
  fileLength?: number; // 最大上传文件数量
  children: React.ReactNode; // 上传按钮
  onChange?: (fileList: any[]) => void; // 上传文件改变时的状态
  onRemove?: (fileList: any[]) => void;
}
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'],
    onChange: () => {},
    onRemove: () => {},
  };
  const { fileType, children, listType, fileSize, fileLength, onChange, onRemove } = props;
  const [fileList, setFileList] = useState<any[]>([]);
  // 上传文件配置
  const uploadProps: UploadProps = {
    listType,
    fileList,
    beforeUpload: (res) => {
      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;
      }
      setFileList([...fileList, res.file]);
      onChange?.([...fileList, res.file]);
    },
    onRemove: (res) => {
      const newFileList = fileList.filter((item) => item.uid !== res.uid);
      setFileList(newFileList);
      onRemove?.(newFileList);
    },
    // onPreview: { onPreview },
  };
  return (
    <div className='uploader-view'>
      <Upload {...uploadProps} style={{ width: '100%' }}>
        <>{fileList.length < (fileLength || 1) && children}</>
      </Upload>
    </div>
  );
};
