import React, { useState } from 'react';
import { Modal, Form, Radio, Input, Button, Upload, message, Select } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { apiDepartmentSave, apiDepartmentExcel } from '../service';
import styles from '../index.less';

const { Dragger } = Upload;
const { Item } = Form;
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const DepartmentModal = ({ visible, onClose, enterpriseList }) => {
  const [form] = Form.useForm();
  const [importMode, setImportMode] = useState(false);

  const handleCancel = val => {
    form.resetFields();
    setImportMode(false);
    onClose(val, 'department');
  };

  const handleImportChange = info => {
    if (info.file.status === 'done') {
      message.success('文件上传成功');
    } else if (info.file.status === 'error') {
      message.error('文件上传失败');
    }
  };

  const getDepartmentSave = async values => {
    const params = {
      name: values.name,
      enterpriseId: values.enterpriseId,
    };
    const res = await apiDepartmentSave(params);
    if (res.businessCode === '0000') {
      message.success('保存成功');
      handleCancel(true);
    }
  };

  const getDepartmentExcel = async values => {
    const params = {
      enterpriseId: values.enterpriseId,
      file: values.file,
    };
    const res = await apiDepartmentExcel(params);
    if (res?.businessCode === '0000') {
      message.success('保存成功');
      handleCancel(true);
    }
  };

  const handleSave = async () => {
    const values = await form.validateFields();
    if (importMode) {
      getDepartmentExcel(values);
      return;
    }
    getDepartmentSave(values);
  };

  return (
    <Modal
      title="创建部门"
      visible={visible}
      onCancel={() => handleCancel(false)}
      footer={[
        <Button key="cancel" onClick={() => handleCancel(false)}>
          取消
        </Button>,
        <Button key="save" type="primary" onClick={() => handleSave()}>
          保存
        </Button>,
      ]}
      initialValue={{ configMode: 0 }}
    >
      <Form form={form} {...layout}>
        <Item
          label="选择企业"
          name="enterpriseId"
          rules={[{ required: true, message: '请选择企业' }]}
        >
          <Select
            placeholder="请选择企业"
            allowClear
            showSearch
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={enterpriseList}
          />
        </Item>

        <Item
          label="配置方式"
          name="configMode"
          rules={[{ required: true, message: '请选择配置方式' }]}
          initialValue={0}
        >
          <Radio.Group>
            <Radio value={0} onChange={() => setImportMode(false)}>
              单个添加
            </Radio>
            <Radio value={1} onChange={() => setImportMode(true)}>
              批量导入
            </Radio>
          </Radio.Group>
        </Item>

        {importMode ? (
          <>
            <Item
              label="上传文件"
              name="file"
              rules={[
                {
                  // eslint-disable-next-line no-confusing-arrow
                  validator: (_, value) =>
                    value && value.fileList.length > 0
                      ? Promise.resolve()
                      : // eslint-disable-next-line prefer-promise-reject-errors
                        Promise.reject('请上传文件'),
                },
              ]}
            >
              <Dragger
                beforeUpload={() => false}
                maxCount={1}
                accept=".xls,.xlsx"
                onChange={handleImportChange}
              >
                <UploadOutlined />
                <p>
                  将文件拖到此处，或<a href="#">点击上传</a>
                </p>
              </Dragger>
            </Item>
            <div className={styles.employees}>
              <a href="https://kdspstatic.q-gp.com/%E6%96%B0%E5%A2%9E%E9%83%A8%E9%97%A8.xlsx">
                部门导入模版.xlsx
              </a>
            </div>
          </>
        ) : (
          <Item
            label="部门名称"
            name="name"
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input maxLength={20} />
          </Item>
        )}
      </Form>
    </Modal>
  );
};

export default DepartmentModal;
