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($t('file.upload.success'));
    } else if (info.file.status === 'error') {
      message.error($t('file.upload.failed'));
    }
  };

  const getDepartmentSave = async values => {
    const params = {
      name: values.name,
      enterpriseId: values.enterpriseId,
    };
    const res = await apiDepartmentSave(params);
    if (res.businessCode === '0000') {
      message.success($t('saved.successfully'));
      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($t('saved.successfully'));
      handleCancel(true);
    }
  };

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

  return (
    <Modal
      title={$t('create.department')}
      visible={visible}
      onCancel={() => handleCancel(false)}
      footer={[
        <Button key="cancel" onClick={() => handleCancel(false)}>{$t('cancel')}</Button>,
        <Button key="save" type="primary" onClick={() => handleSave()}>{$t('save')}</Button>,
      ]}
      initialValue={{ configMode: 0 }}
    >
      <Form form={form} {...layout}>
        <Item
          label={$t('select.company')}
          name="enterpriseId"
          rules={[{ required: true, message: $t('select.company') }]}
        >
          <Select
            placeholder={$t('select.company')}
            allowClear
            showSearch
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={enterpriseList}
          />
        </Item>

        <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>
        </Item>

        {importMode ? (
          <>
            <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"
                onChange={handleImportChange}
              >
                <UploadOutlined />
                <p>{$t('drag.file.here.or')}<a href="#">{$t('click.to.upload')}</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">{$t('department.import.templatexlsx')}</a>
            </div>
          </>
        ) : (
          <Item
            label={$t('department.name')}
            name="name"
            rules={[{ required: true, message: $t('enter.department.name') }]}
          >
            <Input maxLength={20} />
          </Item>
        )}
      </Form>
    </Modal>
  );
};

export default DepartmentModal;
