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

const { Dragger } = Upload;
const { Option } = Select;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const NewEmployeeModal = props => {
  const { visible, onClose, enterpriseList } = props;
  const [form] = Form.useForm();
  const [importMode, setImportMode] = useState(false);
  const [departmentList, setDepartmentList] = useState([]);
  const handleCancel = val => {
    form.resetFields();
    setImportMode(false);
    onClose(val, 'newEmployee');
  };
  const handleSave = () => {
    form.validateFields().then(async values => {
      if (importMode) {
        const res = await apiStaffExcel(values);
        if (res.businessCode === '0000') {
          message.success('上传成功');
          handleCancel(true);
        }
        return;
      }
      const res = await apiStaffSave(values);
      if (res.businessCode === '0000') {
        message.success('保存成功');
        handleCancel(true);
      }
    });
  };

  const validatePhone = (_, value) => {
    const phoneRegex = /^1[3456789]\d{9}$/;
    if (!value || phoneRegex.test(value)) {
      return Promise.resolve();
    }
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject('请输入有效的手机号码');
  };

  // 部门查询
  const getDepartmentList = async id => {
    const res = await apiDepartmentList({ data: { enterpriseId: id }, page: 1, size: 10000 });
    if (res.businessCode === '0000' && res.data?.records?.length) {
      const list = res.data.records;
      const optionData = list.map(item => ({
        value: item.id,
        label: item.name,
      }));
      setDepartmentList(optionData);
      return;
    }
    setDepartmentList([]);
  };
  const onChange = value => {
    form.setFieldsValue({ departmentId: undefined });
    getDepartmentList(value);
  };
  return (
    <Modal
      visible={visible}
      title="添加新员工"
      onCancel={() => handleCancel(false)}
      footer={[
        <Button key="cancel" onClick={() => handleCancel(false)}>
          取消
        </Button>,
        <Button key="save" type="primary" onClick={handleSave}>
          保存
        </Button>,
      ]}
    >
      <Form form={form} {...layout}>
        <Form.Item
          name="enterpriseId"
          label="企业"
          rules={[
            {
              required: true,
              message: '请选择企业',
            },
          ]}
        >
          <Select
            onChange={onChange}
            placeholder="请选择企业"
            allowClear
            showSearch
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={enterpriseList}
          />
        </Form.Item>
        <Form.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>
        </Form.Item>
        {importMode ? (
          <>
            <Form.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">
                <UploadOutlined />
                <p>
                  将文件拖到此处，或<a href="#">点击上传</a>
                </p>
              </Dragger>
            </Form.Item>
            <div className={styles.employees}>
              <a href="https://kdspstatic.q-gp.com/%E6%96%B0%E5%A2%9E%E5%91%98%E5%B7%A5.xlsx">
                员工导入模版.xlsx
              </a>
            </div>
          </>
        ) : (
          <>
            <Form.Item
              name="departmentId"
              label="部门"
              rules={[
                {
                  required: true,
                  message: '请选择部门',
                },
              ]}
            >
              <Select
                placeholder="请选择部门"
                allowClear
                showSearch
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
                options={departmentList}
              />
            </Form.Item>
            <Form.Item
              name="staffNo"
              label="员工ID"
              rules={[
                {
                  required: true,
                  message: '请输入员工ID',
                },
                {
                  pattern: /^[a-zA-Z0-9]+$/,
                  message: '员工ID由数字与英文大小写字母组成',
                },
              ]}
            >
              <Input maxLength={15} />
            </Form.Item>
            <Form.Item
              name="staffName"
              label="员工姓名"
              rules={[
                {
                  required: true,
                  message: '请输入员工姓名',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="mobile"
              label="员工手机号"
              rules={[
                {
                  required: true,
                  message: '请输入员工手机号',
                },
                {
                  validator: validatePhone,
                },
              ]}
            >
              <Input maxLength={11} />
            </Form.Item>
          </>
        )}
      </Form>
    </Modal>
  );
};

export default NewEmployeeModal;
