/* eslint-disable import/no-unresolved */
import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, notification, message } from 'antd';
import voca from 'voca';
import classNames from 'classnames';
import { editUser } from '@/services/userManage/api';
import styles from './AddUserModal.less';

const EditUserModal = props => {
  const { visible, currentUser, currentSelectOrg, onCancel, onSelect, submitSearchUser } = props;
  const [editUserForm] = 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(() => {
    if (visible) {
      editUserForm.setFieldsValue({
        loginName: voca.stripTags(currentUser.loginName),
        userName: voca.stripTags(currentUser.userName),
        phone: voca.stripTags(currentUser.phone) || '',
        email: currentUser.email || '',
      });
    }
  }, [visible]);

  // 提交-编辑用户
  const submitEditUser = () => {
    const loginName = voca.stripTags(editUserForm.getFieldValue('loginName'));
    const userName = voca.stripTags(editUserForm.getFieldValue('userName'));
    const phone = voca.stripTags(editUserForm.getFieldValue('phone')) || '';
    const email = editUserForm.getFieldValue('email') || '';
    editUserForm.validateFields().then(validate => {
      // 正则验证
      if (loginName === '') {
        notification.error({
          message: '提交失败',
          description: '登录名称不能为空!',
        });
        return;
      }
      if (!noChinese.test(loginName)) {
        notification.error({
          message: '提交失败',
          description: '登录名不支持中文!',
        });
        return;
      }
      if (userName === '') {
        notification.error({
          message: '提交失败',
          description: '用户姓名不能为空!',
        });
        return;
      }
      if (phone !== '' && !isPhone.test(phone)) {
        notification.error({
          message: '提交失败',
          description: '请输入11位手机号!',
        });
        return;
      }
      if (email !== '' && !isEmail.test(email)) {
        notification.error({
          message: '提交失败',
          description: '邮箱格式不正确!',
        });
        return;
      }
      // 所有验证通过才可以提交,phone/email为空时不验证
      if (
        loginName &&
        noChinese.test(loginName) &&
        userName &&
        (phone === '' || isPhone.test(phone)) &&
        (email === '' || isEmail.test(email))
      ) {
        editUser(currentUser.userId, loginName, userName, phone, email)
          .then(res => {
            if (res.code === 0) {
              onCancel();
              // 重新获取用户表

              // eslint-disable-next-line no-unused-expressions
              currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);

              notification.success({
                message: '提交成功',
                duration: 2,
              });
            } else {
              notification.error({
                message: '提交失败',
                description: res.msg,
              });
            }
            editUserForm.setFieldsValue({
              loginName: voca.stripTags(currentUser.loginName),
              userName: voca.stripTags(currentUser.userName),
              phone: voca.stripTags(currentUser.phone) || '',
              email: currentUser.email || '',
            });
          })
          .catch(err => {
            message.error(err);
          });
      }
    });
  };
  const title = (
    <span>
      编辑用户
      <span style={{ fontWeight: 'bold', color: 'rgb(24, 144, 255)' }}>
        【{currentUser.userName}】
      </span>
      的信息
    </span>
  );

  return (
    <Modal
      title={title}
      visible={visible}
      maskClosable={false}
      destroyOnClose
      // afterClose={() => {
      //   editUserForm.resetFields();
      // }}
      onOk={submitEditUser}
      onCancel={() => {
        onCancel();
        editUserForm.setFieldsValue({
          loginName: voca.stripTags(currentUser.loginName),
          userName: voca.stripTags(currentUser.userName),
          phone: voca.stripTags(currentUser.phone) || '',
          email: currentUser.email || '',
        });
      }}
      okText="确认"
      cancelText="取消"
    >
      <Form form={editUserForm} labelCol={{ span: 4 }}>
        <Form.Item
          hasFeedback
          name="loginName"
          label="登录名称"
          rules={[
            {
              pattern: /^[a-zA-Z0-9_]{0,}$/,
              message: '长度小于16位，支持字母与数字，允许下划线',
            },
            { required: true },
          ]}
        >
          <Input placeholder="请输入登录名称（小于16位）" maxLength="16" />
        </Form.Item>
        <Form.Item
          hasFeedback
          name="userName"
          label="用户姓名"
          rules={[
            { required: true },
            {
              pattern: /^[A-Za-z0-9_\u4e00-\u9fa5]+$/,
              message: '长度小于16位，支持字母、中文与数字，允许下划线',
            },
          ]}
        >
          <Input placeholder="请输入用户姓名（小于16位）" maxLength="16" />
        </Form.Item>
        <Form.Item
          hasFeedback
          name="phone"
          label="手机号码"
          rules={[
            { required: true },
            {
              pattern: new RegExp(/^1[0-9]{10}$/),
              message: '请输入正确的手机号码！',
            },
          ]}
        >
          <Input placeholder="请输入手机号码" autoComplete="off" maxlength="11" />
        </Form.Item>
        <Form.Item
          hasFeedback
          name="email"
          label="电子邮箱"
          rules={[
            {
              type: 'email',
              message: '请输入正确的电子邮箱！',
            },
          ]}
        >
          <Input placeholder="请输入电子邮箱" autoComplete="off" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EditUserModal;
