import BaseFormSelect from '../../../../components/BaseFormSelect';
import { ModalForm, ProFormUploadButton } from '@ant-design/pro-components';
import { Button, Col, Form, Row, message } from 'antd';
import React, { useRef } from 'react';
import { CommonController, DeptController } from '../../../../services';

interface ImportFormProps {
  title: string;
  trigger: JSX.Element;
  onSubmit?: () => void;
}
const ImportForm: React.FC<ImportFormProps> = (props) => {
  const { trigger, title, onSubmit } = props;
  const [form] = Form.useForm();
  const ref = useRef<Record<string, boolean>>({});
  return (
    <ModalForm
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      width={800}
      title={title}
      trigger={trigger}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
      }}
      onOpenChange={() => {
        Object.keys(ref.current).forEach((key) => {
          ref.current[key] = false;
        });
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        const { orgCode, files } = values || {};
        const [file] = files || [];
        const forms = new FormData();
        forms.append('orgCode', orgCode);
        forms.append('file', file.originFileObj);
        await DeptController.importDeptApi(forms);
        message.success('导入成功');
        onSubmit?.();
        return true;
      }}
    >
      <BaseFormSelect
        label="机构名称"
        name="orgCode"
        fieldProps={{ fetchDataOnSearch: false }}
        request={async () => CommonController.getOrgOptionsApi()}
        rules={[
          {
            required: true,
          },
        ]}
      />
      <ProFormUploadButton
        label="excel导入"
        name="files"
        max={1}
        rules={[
          {
            required: true,
            message: '请上传excel文件',
          },
        ]}
        fieldProps={{
          beforeUpload: () => false,
        }}
      />
      <Row>
        <Col offset={4}>
          <Button
            type="link"
            style={{ padding: 0 }}
            onClick={() => DeptController.exportDeptApi()}
          >
            下载科室导入模板
          </Button>
        </Col>
      </Row>
      <Row>
        <Col offset={4}>
          <span style={{ color: 'red' }}>
            注：模板文件中内容标题的名称与顺序不可更改
          </span>
        </Col>
      </Row>
    </ModalForm>
  );
};

export default ImportForm;
