import { Button, Form, Modal } from "antd";
import { getFileUrl } from "../../utils";
import Upload from "../Upload";

/**
 * 导入文件组件
 */
const ImportFile = (props) => {
  const {
    visible,
    onCancel,
    onConfirm,
    title = "导入",
    templateUrl,
    labelCol = { span: 4 },
    children,
    exportTemplateButtonText = "导出模板",
    extraButtons,
    ...restProps
  } = props;

  const [form] = Form.useForm();

  // 关闭弹窗
  const handleClose = () => {
    form.resetFields();
    onCancel();
  };

  // 提交表单
  const handleSubmit = (values) => {
    onConfirm(values);
    handleClose();
  };

  // 导出模板
  const handleExportTemplate = () => {
    Modal.confirm({
      title: "提示",
      content: "确定要下载excel模板吗？",
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        const fileUrl = getFileUrl();
        window.open(fileUrl + templateUrl);
      },
    });
  };

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={handleClose}
      width={600}
      maskClosable={false}
      footer={[
        templateUrl && (
          <Button key="export" onClick={handleExportTemplate}>
            {exportTemplateButtonText}
          </Button>
        ),
        ...(extraButtons || []),
        <Button key="cancel" onClick={handleClose}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={form.submit}>
          确定
        </Button>,
      ]}
    >
      <Form
        form={form}
        labelCol={labelCol}
        wrapperCol={{ span: 24 - labelCol.span }}
        scrollToFirstError
        onFinish={handleSubmit}
        {...restProps}
      >
        {children && typeof children === "function" ? children({ form }) : children}
        <Form.Item label="附件" name="file" rules={[{ required: true, message: "附件不能为空" }]}>
          <Upload accept=".xls,.xlsx" listType="text" maxCount={1} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

ImportFile.displayName = "ImportFile";

export default ImportFile;
