import * as React from 'react';
import { message, Upload } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { UploadChangeParam, RcFile, UploadProps } from 'antd/lib/upload';
interface Iprops extends UploadProps {
  limit?: number;
  onChange?: (values: any) => void;
}
const customeUpload: React.FC<Iprops> = (props) => {
  const { limit } = props;
  const [state, setState] = React.useState<{ fileList: any[] }>({
    fileList: [],
  });
  const handleChange = (info: UploadChangeParam) => {
    setState((preState) => ({
      ...preState,
      fileList: info.fileList,
    }));
    if (props.onChange) {
      props.onChange(
        info.fileList.map((element) => {
          return element.response ? element.response.data : undefined;
        })
      );
    }
  };
  const onBeforeUpload = (file: RcFile, FileList: RcFile[]) => {
    const hasFile = state.fileList.find(
      (tempFile) => tempFile.name === file.name && file.type === tempFile.type
    );
    if (hasFile) {
      message.error('您已上传这个文件');
      return Promise.reject();
    }
    return Promise.resolve();
  };
  return (
    <Upload
      action='/api/v1/upload'
      listType='picture-card'
      accept='image/*'
      onChange={handleChange}
      onPreview={(file) => {
        window.open(file.response.data);
      }}
      beforeUpload={onBeforeUpload}>
      {limit && state.fileList.length >= limit ? null : (
        <div>
          <PlusOutlined />
          <div style={{ marginTop: 8 }}>点击上传</div>
        </div>
      )}
    </Upload>
  );
};
export default customeUpload;
