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 = async () => {
    const values = await form.validateFields();
    if (importMode) {
      const res = await apiStaffExcel(values);
      if (res?.businessCode === '0000') {
        message.success($t('upload.successful'));
        handleCancel(true);
      }
      return;
    }
    const res = await apiStaffSave(values);
    if (res?.businessCode === '0000') {
      message.success($t('saved.successfully'));
      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($t('enter.valid.phone.number'));
  };

  // 部门查询
  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={$t('add.new.staff')}
      onCancel={() => handleCancel(false)}
      footer={[
        <Button key="cancel" onClick={() => handleCancel(false)}>{$t('cancel')}</Button>,
        <Button key="save" type="primary" onClick={handleSave}>{$t('save')}</Button>,
      ]}
    >
      <Form form={form} {...layout}>
        <Form.Item
          name="enterpriseId"
          label={$t('enterprise')}
          rules={[
            {
              required: true,
              message: $t('select.company'),
            },
          ]}
        >
          <Select
            onChange={onChange}
            placeholder={$t('select.company')}
            allowClear
            showSearch
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={enterpriseList}
          />
        </Form.Item>
        <Form.Item
          label={$t('config.method')}
          name="configMode"
          rules={[{ required: true, message: $t('select.config.method') }]}
          initialValue={0}
        >
          <Radio.Group>
            <Radio value={0} onChange={() => setImportMode(false)}>{$t('add.single')}</Radio>
            <Radio value={1} onChange={() => setImportMode(true)}>{$t('batch.import')}</Radio>
          </Radio.Group>
        </Form.Item>
        {importMode ? (
          <>
            <Form.Item
              label={$t('upload.file')}
              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($t('upload.file')),
                },
              ]}
            >
              <Dragger beforeUpload={() => false} maxCount={1} accept=".xls,.xlsx">
                <UploadOutlined />
                <p>{$t('drag.file.here.or')}<a href="#">{$t('click.to.upload')}</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">{$t('employee.templatexlsx')}</a>
            </div>
          </>
        ) : (
          <>
            <Form.Item
              name="departmentId"
              label={$t('department')}
              rules={[
                {
                  required: true,
                  message: $t('select.department'),
                },
              ]}
            >
              <Select
                placeholder={$t('select.department')}
                allowClear
                showSearch
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
                options={departmentList}
              />
            </Form.Item>
            <Form.Item
              name="staffNo"
              label={$t('employee.id')}
              rules={[
                {
                  required: true,
                  message: $t('enter.staff.id'),
                },
                {
                  pattern: /^[a-zA-Z0-9]+$/,
                  message: $t('employee.id.alphanumeric.only'),
                },
              ]}
            >
              <Input maxLength={15} />
            </Form.Item>
            <Form.Item
              name="staffName"
              label={$t('employee.name')}
              rules={[
                {
                  required: true,
                  message: $t('enter.staff.name'),
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="mobile"
              label={$t('employee.mobile')}
              rules={[
                {
                  required: true,
                  message: $t('enter.staff.phone'),
                },
                {
                  validator: validatePhone,
                },
              ]}
            >
              <Input maxLength={11} />
            </Form.Item>
          </>
        )}
      </Form>
    </Modal>
  );
};

export default NewEmployeeModal;
