/* eslint-disable import/no-unresolved */
import React, { useEffect } from 'react';
import { Modal, Form, Input, notification, message } from 'antd';
import { addOrg } from '@/services/userManage/api';

const AddUserModal = props => {
  const { visible, orgID, onCancel, updateTrees1, onSelect, orgTitle1 } = props;
  const [addOrgForm] = Form.useForm(); // 添加用户

  useEffect(() => {
    console.log(orgID);
    addOrgForm.resetFields();
  }, [orgID]);

  // 提交-添加下级机构
  const submitAddOrg = () => {
    // 顶级机构
    if (orgID == -1) {
      addOrg(
        orgID,
        addOrgForm.getFieldValue('OUName'),
        addOrgForm.getFieldValue('desrciption') || '',
        '',
      )
        .then(res => {
          if (res.msg === 'Ok') {
            onCancel();
            notification.success({
              message: '提交成功',
              duration: 2,
            });
            // 重新获取机构树与用户表
            console.log(res.data);
            updateTrees1(res.data);
            onSelect([`${res.data}`]);
          } else {
            notification.error({
              message: '提交失败',
              description: res.msg,
            });
          }
        })
        .catch(err => {
          message.error(err);
        });
    } else {
      addOrg(
        orgID.id,
        addOrgForm.getFieldValue('OUName'),
        addOrgForm.getFieldValue('desrciption') || '',
        '',
      )
        .then(res => {
          if (res.msg === 'Ok') {
            onCancel();
            notification.success({
              message: '提交成功',
              duration: 2,
            });
            // 重新获取机构树与用户表
            console.log(res.data);
            updateTrees1(res.data);
            onSelect([`${res.data}`]);
          } else {
            notification.error({
              message: '提交失败',
              description: res.msg,
            });
          }
        })
        .catch(err => {
          message.error(err);
        });
    }
  };
  const title = (
    <span>
      在<span style={{ fontWeight: 'bold', color: 'rgb(24, 144, 255)' }}>【{orgTitle1}】</span>
      下添加机构
    </span>
  );
  return (
    <Modal
      title={orgID === '-1' ? '添加顶级机构' : title}
      visible={visible}
      onCancel={onCancel}
      onOk={submitAddOrg}
      destroyOnClose
      afterClose={() => {
        addOrgForm.resetFields();
      }}
      maskClosable={false}
      okText="确认"
      cancelText="取消"
    >
      <Form form={addOrgForm} labelCol={{ span: 4 }}>
        <Form.Item name="OUName" label="机构名称" rules={[{ required: true, message: '不能为空' }]}>
          <Input placeholder="请输入机构名称" maxLength="20" />
        </Form.Item>
        <Form.Item name="description" label="描述">
          <Input placeholder="请输入相关描述" maxLength="100" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddUserModal;
