import { message, Spin, Upload } from 'antd';
import type { UploadProps, UploadFile as FileType } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { useState } from 'react';
import FileCards from './FileCards';
import { useIntl } from 'umi';

const { Dragger } = Upload;

type UploadFileProps = {
  /**
   * @description 上传文件接口方法
   */
  uploadAttachment: (formData: any) => Promise<any>;
  tips?: string;
  uploadFileProps?: UploadProps;
  value?: any[];
  onChange?: (value?: any[]) => void;
  /**
   * @description 自定义文件列表渲染
   */
  fileListRender?: (value?: any, onChange?: (value?: any) => void) => React.ReactNode;
  showUploadList?: boolean;
};

const DEFAULT_WIDTH = '280px';

const UploadFile: React.FC<UploadFileProps> = (props) => {
  const {
    tips,
    uploadFileProps,
    fileListRender,
    uploadAttachment,
    onChange,
    value,
    showUploadList = true,
  } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [fileList, setFileList] = useState<FileType[]>();
  const { formatMessage } = useIntl();

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    fileList,
    onChange(info) {
      setFileList(info.fileList);
    },
    customRequest: async ({ file, onSuccess }) => {
      const formData = new FormData();
      formData.append('file', file);
      try {
        setLoading(true);
        const response = await uploadAttachment(formData);
        onSuccess?.(response);
        message.success(formatMessage({ id: 'component.uploadFile.success' }));
        onChange?.([...(value ?? []), response]);
      } catch (error) {
        console.error(error);
        message.error(formatMessage({ id: 'component.uploadFile.fail' }));
      } finally {
        setLoading(false);
      }
    },
    // onDrop(e) {
    //   console.log('Dropped files', e.dataTransfer.files);
    // },
    style: { width: DEFAULT_WIDTH },
    ...uploadFileProps,
  };

  return (
    <Spin spinning={loading}>
      <div style={{ display: 'flex', alignItems: 'stretch', flexWrap: 'wrap', gap: '12px' }}>
        {showUploadList && (
          <>
            {fileListRender ? (
              fileListRender(value, onChange)
            ) : (
              <FileCards value={value} onChange={onChange} />
            )}
          </>
        )}

        <Dragger {...uploadProps}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">
            {tips ? tips : formatMessage({ id: 'component.uploadFile.tips' })}
          </p>
        </Dragger>
      </div>
    </Spin>
  );
};

export default UploadFile;
