import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, notification, message, TreeSelect } from 'antd';
import { addUser, GetUserRelationListNew } from '@/services/userManage/api';
import classNames from 'classnames';
import sha1 from 'sha1';
import { ok } from '../../../assets/images/icons/ok.svg';
import styles from './AddUserModal.less';
const { SHOW_CHILD } = TreeSelect;

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,}$/,
  ); // 邮箱
  const [value, setValue] = useState(['0-1-1']);
  const [treeData, setTreeData] = useState([]);
  const [passwordLevel, setPasswordLevel] = useState(''); // 密码等级
  const onChange = newValue => {
    console.log('onChange ', value);
    setValue(newValue);
  };

  useEffect(() => {
    if (visible) {
      addUserForm.resetFields();
      getEmptyRoleList();
    } else {
      setPasswordLevel('');
    }
  }, [orgID, visible]);

  // 获取全部未勾选站点列表
  const getEmptyRoleList = () => {
    GetUserRelationListNew({ userID: 0 })
      .then(res => {
        if (res.code === 0) {
          let aa = {};
          console.log(res.data.stationList);
          res.data.stationList.map(i => {
            aa.title = i.visibleTitle;
            aa.value = i.visibleValue;
            aa.key = i.visibleValue;
            aa.children = [];
            i.stationList.map(j => {
              let bb = {};
              bb.title = j.stationName;
              bb.value = j.stationID;
              bb.key = j.stationID;
              aa.children.push(bb);
            });
          });
          console.log(aa);
          let data = [];
          data.push(aa);
          setTreeData(data);
        } else {
          notification.error({
            message: '获取失败',
            description: res.msg,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };

  // 提交-添加用户
  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: sha1(password).toUpperCase(),
        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 changeValue = changedFields => {
    if (changedFields[0].name[0] === 'password') {
      // console.log(changedFields[0].value);
      checkStrong(changedFields[0].value);
      // console.log(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:
        setPasswordLevel('弱');
        break;
      case 2:
        if (sValue.length > 8) {
          setPasswordLevel('中');
        } else {
          setPasswordLevel('弱');
        }
        break;
      case 3:
        if (sValue.length > 8) {
          setPasswordLevel('强');
        } else {
          setPasswordLevel('中');
        }
        break;
      case 4:
        setPasswordLevel('强');
        break;
    }
  };
  const title = (
    <span>
      在<span style={{ fontWeight: 'bold', color: 'rgb(24, 144, 255)' }}>【{orgTitle1}】</span>
      下添加用户
    </span>
  );

  const tProps = {
    treeData,
    value,
    onChange,
    treeCheckable: true,
    showCheckedStrategy: SHOW_CHILD,
    placeholder: '请选择关联站点',
    style: {
      width: '100%',
    },
  };

  return (
    <Modal
      title={title}
      visible={visible}
      onCancel={onCancel}
      maskClosable={false}
      destroyOnClose
      afterClose={() => {
        addUserForm.resetFields();
        setPasswordLevel('');
      }}
      onOk={submitAddUser}
      okText="确认"
      cancelText="取消"
    >
      <div className={styles.modalContent}>
        <Form form={addUserForm} labelCol={{ span: 4 }} onFieldsChange={changeValue}>
          <Form.Item
            hasFeedback
            name="loginName"
            label="登录名称"
            rules={[
              {
                pattern: /^[a-zA-Z0-9_]{0,}$/,
                message: '长度小于16位，支持字母与数字，允许下划线',
              },
              { required: true },
            ]}
          >
            <Input placeholder="请输入登录名称（小于16位）" maxLength="16" />
          </Form.Item>
          <div className={styles.formBox}>
            <Form.Item
              hasFeedback
              name="password"
              label="账号密码"
              rules={[
                {
                  pattern: /^[a-zA-Z0-9_]{6,16}$/,
                  message: '长度6-16位，支持字母与数字，允许下划线',
                },
                { required: true },
              ]}
            >
              <Input.Password
                placeholder="请输入账号密码（6~16位）"
                maxLength="16"
                onCopy={e => {
                  e.preventDefault();
                }}
                onPaste={e => {
                  // 禁止粘贴
                  e.preventDefault();
                }}
              />
            </Form.Item>
            <div
              style={{ right: '70px' }}
              className={classNames(styles.tipsText, {
                [styles.tipsRed]: passwordLevel === '弱',
                [styles.tipsOrange]: passwordLevel === '中',
                [styles.tipsGreen]: passwordLevel === '强',
              })}
            >
              {passwordLevel}
            </div>
          </div>

          <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="请输入手机号码" maxlength="11" autoComplete="off" />
          </Form.Item>
          <Form.Item
            hasFeedback
            name="email"
            label="电子邮箱"
            rules={[
              {
                type: 'email',
                message: '请输入正确的电子邮箱！',
              },
            ]}
          >
            <Input placeholder="请输入电子邮箱" autoComplete="off" />
          </Form.Item>
          {/* <Form.Item name="stationList" label="关联站点" rules={[{ required: true }]}>
          <TreeSelect {...tProps} showSearch treeDefaultExpandAll />
        </Form.Item> */}
        </Form>
      </div>
    </Modal>
  );
};

export default AddUserModal;
