import { MyResponseType } from '@/common';
import {
  ImportOutlined,
  InboxOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import { Button, Flex, Modal, Space, Upload, message } from 'antd';
import { useState } from 'react';

type MyImportModalType = {
  title?: string;
  type?: any;
  danger?: boolean;
  params?: Record<string, any>;
  size?: 'small' | 'middle' | 'large';
  templateApi?: () => Promise<MyResponseType>;
  importApi: (data: any) => Promise<MyResponseType>;
  reload?: () => void;
};

export function MyImportModal(props: MyImportModalType) {
  const [open, setOpen] = useState(false);
  const [uploading, setUploading] = useState(false);

  const {
    title = '批量导入',
    params = {},
    type = 'primary',
    size = 'middle',
    danger = false,
  } = props;

  // 处理文件上传
  const handleBeforeUpload = (file: File) => {
    // 文件类型验证
    const validTypes = [
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'text/csv',
      'application/vnd.oasis.opendocument.spreadsheet',
    ];

    const fileExtension = file.name.split('.').pop()?.toLowerCase();
    const isExcelFile =
      file.type.includes('excel') || file.type.includes('spreadsheet');
    const isCSVFile = file.type === 'text/csv' || fileExtension === 'csv';

    if (!isExcelFile && !isCSVFile) {
      message.error('请上传Excel或CSV文件');
      return Upload.LIST_IGNORE;
    }

    // 开始导入
    startImport(file);
    return false; // 阻止默认上传
  };

  // 执行导入
  const startImport = (file: File) => {
    setUploading(true);

    const formData = new FormData();
    formData.append('upload_file', file);
    Object.entries(params).forEach(([key, value]) => {
      formData.append(key, value);
    });

    props
      ?.importApi(formData)
      .then(() => {
        message.success('导入成功');
        setTimeout(() => {
          setUploading(false);
          setOpen(false);
          props.reload?.();
        }, 800); // 延迟一点时间关闭，让用户看到成功提示
      })
      .catch((error) => {
        message.error(error?.message || '导入失败');
        setUploading(false);
      });
  };

  return (
    <>
      <Button
        onClick={() => setOpen(true)}
        type={type}
        danger={danger}
        size={size}
      >
        <ImportOutlined />
        {title}
      </Button>

      <Modal
        title={title}
        open={open}
        onCancel={() => {
          if (!uploading) {
            setOpen(false);
          }
        }}
        footer={(_, { CancelBtn }) => (
          <Flex style={{ width: '100%' }} justify="space-between">
            <Button onClick={() => props?.templateApi?.()} disabled={uploading}>
              下载模板
            </Button>
            <Space>{!uploading && <CancelBtn />}</Space>
          </Flex>
        )}
        maskClosable={!uploading}
        closable={!uploading}
        destroyOnClose
      >
        {uploading ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <LoadingOutlined
              style={{ fontSize: 48, color: '#1890ff', marginBottom: 20 }}
            />
            <p style={{ fontSize: 16, color: '#666' }}>
              正在处理文件，请稍候...
            </p>
            <p style={{ fontSize: 14, color: '#999', marginTop: 8 }}>
              导入完成后窗口将自动关闭
            </p>
          </div>
        ) : (
          <Upload.Dragger
            accept=".xls,.xlsx,.csv,.ods"
            maxCount={1}
            showUploadList={false}
            beforeUpload={handleBeforeUpload}
          >
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
            <p className="ant-upload-hint">
              支持Excel(.xls, .xlsx)和CSV(.csv)格式文件
              <br />
              选择文件后将自动开始导入
            </p>
          </Upload.Dragger>
        )}
      </Modal>
    </>
  );
}
