/* eslint-disable import/no-unresolved */
import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, notification, message, Divider } from 'antd';
import voca from 'voca';
import classNames from 'classnames';
import { editUser, updateUserPassword } from '@/services/userManage/api';
import sha1 from 'sha1';
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,}$/,
  ); // 邮箱
  const [passwordForm] = Form.useForm(); // 修改密码
  const [newPasswordLevel, setNewPasswordLevel] = useState('');
  const [passwordConfirmLevel, setPasswordConfirmLevel] = useState('');

  useEffect(() => {
    if (visible) {
      console.log(currentUser);
      editUserForm.setFieldsValue({
        loginName: voca.stripTags(currentUser.loginName),
        userName: voca.stripTags(currentUser.userName),
        phone: voca.stripTags(currentUser.phone) || '',
        email: currentUser.email || '',
      });
      console.log(currentUser.password);
      passwordForm.setFieldsValue({
        oldPassword: currentUser.password,
        newPassword: '',
        passwordConfirm: '',
      });
    } else {
      setNewPasswordLevel('');
      setPasswordConfirmLevel('');
    }
  }, [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') || '';
    const oldPassword = passwordForm.getFieldValue('oldPassword');
    const newPassword = passwordForm.getFieldValue('newPassword');
    const passwordConfirm = passwordForm.getFieldValue('passwordConfirm');
    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;
      }
      // if ((newPassword && passwordConfirm === '') || (passwordConfirm && newPassword === '')) {
      //   notification.error({
      //     message: '提交失败',
      //     description: '请填写密码',
      //   });
      //   return;
      // }
      if ((newPassword && newPassword.length < 6) || (passwordConfirm && passwordConfirm < 6)) {
        notification.error({
          message: '提交失败',
          description: '密码至少为6位!',
        });
        return;
      }
      if (newPassword !== passwordConfirm) {
        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.msg === '') {
              onCancel();
              // 重新获取用户表
              if (!newPassword) {
                // eslint-disable-next-line no-unused-expressions
                currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);
              }

              notification.success({
                message: '提交成功',
                duration: 2,
              });
              submitChangePassword();
            } else {
              notification.error({
                message: '提交失败',
                description: res.message,
              });
            }
            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>
  );

  // 提交-修改密码
  const submitChangePassword = () => {
    const oldPassword = passwordForm.getFieldValue('oldPassword');
    const newPassword = passwordForm.getFieldValue('newPassword');
    const passwordConfirm = passwordForm.getFieldValue('passwordConfirm');
    if (
      newPassword &&
      newPassword.length >= 6 &&
      passwordConfirm &&
      newPassword.length >= 6 &&
      newPassword === passwordConfirm
    ) {
      updateUserPassword({
        UserId: +currentUser.userId,
        OldPassWord: oldPassword,
        NewPassWord: sha1(newPassword).toUpperCase(),
      })
        .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.message,
            });
          }
          passwordForm.setFieldsValue({
            oldPassword: currentUser.password,
            newPassword: '',
            passwordConfirm: '',
          });
        })
        .catch(err => {
          message.error(err);
        });
    }
  };
  const changeValue = changedFields => {
    if (changedFields[0].name[0] === 'newPassword') {
      setNewPasswordLevel(checkStrong(changedFields[0].value));
    }
    if (changedFields[0].name[0] === 'passwordConfirm') {
      setPasswordConfirmLevel(checkStrong(changedFields[0].value));
    }
  };
  const checkStrong = sValue => {
    let modes = 0;
    // 正则表达式验证符合要求的
    if (sValue.length < 1) return modes;
    if (/\d/.test(sValue)) modes++; // 数字
    if (/[a-z]/.test(sValue)) modes++; // 小写
    if (/[A-Z]/.test(sValue)) modes++; // 大写
    if (/[_\W]/.test(sValue)) modes++; // 特殊字符
    console.log(modes, 'modes');
    // 逻辑处理
    // eslint-disable-next-line default-case
    switch (modes) {
      case 1:
        return '弱';
      case 2:
        if (sValue.length > 8) {
          return '中';
        }
        return '弱';
      case 3:
        if (sValue.length > 8) {
          return '强';
        }
        return '中';
      case 4:
        return '强';
    }
  };
  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>
      <Divider
        orientation="left"
        style={{
          borderTopColor: '#99bbe8',
          color: '#15428b',
          fontWeight: 700,
        }}
      >
        重置密码（选填）
      </Divider>
      <div className={styles.modalContent}>
        <Form form={passwordForm} labelCol={{ span: 4 }} onFieldsChange={changeValue}>
          <Form.Item name="oldPassword" label="原始密码">
            <Input disabled />
          </Form.Item>
          <div className={styles.formBox}>
            <Form.Item
              name="newPassword"
              label="新密码"
              rules={[
                {
                  pattern: /^[a-zA-Z0-9_]{6,16}$/,
                  message: '长度6-16位，支持字母与数字，允许下划线',
                },
                // { required: true },
              ]}
            >
              <Input.Password
                placeholder="请输入新密码"
                autoComplete="off"
                maxLength="16"
                onCopy={e => {
                  e.preventDefault();
                }}
                onPaste={e => {
                  // 禁止粘贴
                  e.preventDefault();
                }}
              />
            </Form.Item>
            <div
              className={classNames(styles.tipsText, {
                [styles.tipsRed]: newPasswordLevel === '弱',
                [styles.tipsOrange]: newPasswordLevel === '中',
                [styles.tipsGreen]: newPasswordLevel === '强',
              })}
            >
              {newPasswordLevel}
            </div>
          </div>
          <div className={styles.formBox}>
            <Form.Item
              name="passwordConfirm"
              label="确认密码"
              rules={[
                {
                  pattern: /^[a-zA-Z0-9_]{6,16}$/,
                  message: '长度6-16位，支持字母与数字，允许下划线',
                },
                // { required: true },
              ]}
            >
              <Input.Password
                placeholder="再次确认新密码"
                autoComplete="off"
                maxLength="16"
                onCopy={e => {
                  e.preventDefault();
                }}
                onPaste={e => {
                  // 禁止粘贴
                  e.preventDefault();
                }}
              />
            </Form.Item>
            <div
              className={classNames(styles.tipsText, {
                [styles.tipsRed]: passwordConfirmLevel === '弱',
                [styles.tipsOrange]: passwordConfirmLevel === '中',
                [styles.tipsGreen]: passwordConfirmLevel === '强',
              })}
            >
              {passwordConfirmLevel}
            </div>
          </div>
        </Form>
      </div>
    </Modal>
  );
};

export default EditUserModal;
