import {
  ProFormUploadButton,
  ProFormUploadButtonProps,
} from '@ant-design/pro-components';
import { message } from 'antd';
import { RcFile, UploadFile } from 'antd/es/upload/interface';
import React, { useState } from 'react';

const ProFormUploadOss: React.FC = (props: ProFormUploadButtonProps) => {
  const [fileList, setFileList] = useState<Array<UploadFile<any>>>([]);

  const getBase64 = (img: RcFile, callback: (imageUrl: any) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    // 读取文件
    reader.readAsDataURL(img);
  };

  return (
    <ProFormUploadButton
      label={'上传内容'}
      required={true}
      listType="picture-card"
      name={'file'}
      fileList={fileList}
      max={1}
      tooltip={
        '每次最多上传1张图片，支持.jpg, .jpeg,.gif, .png, .bmp格式，单张图片保持在2M内，建议尺寸：750x750px'
      }
      fieldProps={{
        onPreview: async (file) => {
          if (file.url === '') {
            await message.warning('文件还未上传无法预览');
          }
        },
        //@ts-ignore
        onRemove: (file: UploadFile) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          setFileList(newFileList);
        },
        beforeUpload: (file) => {
          getBase64(file, (imageUrl: any) => {
            setFileList([
              // @ts-ignore
              ...fileList,
              {
                uid: file.uid,
                name: file.name,
                // @ts-ignore
                status: 'success',
                thumbUrl: imageUrl,
                url: '',
              },
            ]);
          });

          return false;
        },
      }}
      {...props}
    />
  );
};

export default ProFormUploadOss;
