import React, { useEffect } from 'react';
import { Modal, Form, Input, notification, message } from 'antd';
import { addOrg } from '@/services/userCenter/userManage/api';

const AddUserModal = props => {
  const { title, visible, orgID, onCancel, updateTrees, onSelect } = 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,
            });
            // 重新获取机构树与用户表
            updateTrees();
            onSelect([`${res.OUID}`]);
          } 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,
            });
            // 重新获取机构树与用户表
            updateTrees();
            onSelect([`${res.OUID}`]);
          } else {
            notification.error({
              message: '提交失败',
              description: res.msg,
            });
          }
        })
        .catch(err => {
          message.error(err);
        });
    }
  };
  return (
    <Modal
      title={title}
      visible={visible}
      onCancel={onCancel}
      onOk={submitAddOrg}
      okText="确认"
      cancelText="取消"
    >
      <Form form={addOrgForm} labelCol={{ span: 4 }}>
        <Form.Item
          name="OUName"
          label="机构名称"
          rules={[{ required: true, message: '不能为空' }]}
        >
          <Input placeholder="请输入机构名称" />
        </Form.Item>
        <Form.Item name="description" label="描述">
          <Input placeholder="请输入相关描述" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddUserModal;
