import React, { useEffect } from 'react';
import { Modal, Form, Input, notification, message } from 'antd';
import { addUser } from '@/services/userManage/api';
import { ok } from '../../../assets/images/icons/ok.svg';

const AddUserModal = props => {
  const { visible, orgID, onCancel, updateTrees1, orgTitle1, onSelect } = props;
  const [addUserForm] = Form.useForm(); // 添加用户
  /** ***正则验证**** */
  const noChinese = new RegExp(/^[^\u4e00-\u9fa5]+$/); // 不能包含中文
  const isPhone = new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/); // 手机号
  const isEmail = new RegExp(
    /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
  ); // 邮箱

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

  // 提交-添加用户
  const submitAddUser = () => {
    const loginName = addUserForm.getFieldValue('loginName') || '';
    const userName = addUserForm.getFieldValue('userName') || '';
    const password = addUserForm.getFieldValue('password') || '';
    const phone = addUserForm.getFieldValue('phone') || '';
    const email = addUserForm.getFieldValue('email') || '';
    // 正则验证
    if (loginName === '') {
      notification.error({
        message: '提交失败',
        description: '登录名不能为空!',
      });
    } else if (!noChinese.test(loginName)) {
      notification.error({
        message: '提交失败',
        description: '登录名不支持中文!',
      });
    } else if (password === '') {
      notification.error({
        message: '提交失败',
        description: '密码不能为空!',
      });
    } else if (password.length < 6) {
      notification.error({
        message: '提交失败',
        description: '密码至少为6位，且包含数字和字母!',
      });
    } else if (userName === '') {
      notification.error({
        message: '提交失败',
        description: '用户名称不能为空!',
      });
    } else if (phone !== '' && !isPhone.test(phone)) {
      notification.error({
        message: '提交失败',
        description: '请输入11位手机号!',
      });
    } else if (email !== '' && !isEmail.test(email)) {
      notification.error({
        message: '提交失败',
        description: '邮箱格式不正确!',
      });
    }
    // 所有验证通过才可以提交,phone/email为空时不验证
    else if (
      noChinese.test(loginName) &&
      password.length >= 6 &&
      userName &&
      (phone === '' || isPhone.test(phone)) &&
      (email === '' || isEmail.test(email))
    ) {
      addUser({ OUID: orgID.id, loginName, userName, password, phone, email })
        .then(res => {
          if (res.code === 0) {
            addUserForm.resetFields();
            onCancel(); // 设置Modal不可见
            notification.success({
              message: '提交成功',
              duration: 2,
            });
            updateTrees1(orgID.id);
            onSelect([`${orgID.id}`]);

            // 重新获取用户表
          } 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={title}
      visible={visible}
      onCancel={onCancel}
      maskClosable={false}
      destroyOnClose
      afterClose={() => {
        addUserForm.resetFields();
      }}
      onOk={submitAddUser}
      okText="确认"
      cancelText="取消"
    >
      <Form form={addUserForm} labelCol={{ span: 4 }}>
        <Form.Item
          hasFeedback
          name="loginName"
          label="登录名称"
          rules={[
            {
              pattern: /^[a-zA-Z0-9_]{0,}$/,
              message: '不支持中文和特殊字符',
            },
            { required: true },
          ]}
        >
          <Input placeholder="登录名称不支持中文与特殊字符" maxLength="20" />
        </Form.Item>
        <Form.Item
          hasFeedback
          name="password"
          label="账户密码"
          rules={[
            {
              pattern: /^(?=.*[a-zA-Z\d])(?=.*([a-zA-Z].*))(?=.*[0-9].*)[!-~]{6,16}$/,
              message: '密码长度6-16位，且必须包含数字和字母，不能存在空格',
            },
            { required: true },
          ]}
        >
          <Input placeholder="请输入账户密码，至少6位" maxlength="16" />
        </Form.Item>
        <Form.Item
          hasFeedback
          name="userName"
          label="用户姓名"
          rules={[
            { required: true },
            { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不支持特殊字符' },
          ]}
        >
          <Input placeholder="用户姓名不支持特殊字符" maxLength="20" />
        </Form.Item>
        <Form.Item
          hasFeedback
          name="phone"
          label="手机号码"
          rules={[
            {
              pattern: new RegExp(/^1[0-9]{10}$/),
              message: '手机号码以1开头11位',
            },
          ]}
        >
          <Input placeholder="请输入11位手机号码" maxlength="11" autoComplete="off" />
        </Form.Item>
        <Form.Item
          hasFeedback
          name="email"
          label="电子邮箱"
          rules={[
            {
              type: 'email',
              message: '请输入正确的电子邮箱!',
            },
          ]}
        >
          <Input placeholder="请输入电子邮箱" autoComplete="off" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddUserModal;
