AddUserModal.jsx 10.4 KB
Newer Older
1
import React, { useEffect, useState } from 'react';
2
import { Modal, Form, Input, notification, message, TreeSelect, Select } from 'antd';
3
import { addUser, GetUserRelationListNew } from '@/services/userManage/api';
4
import classNames from 'classnames';
5
import sha1 from 'sha1';
皮倩雯's avatar
皮倩雯 committed
6
import { ok } from '../../../assets/images/icons/ok.svg';
7
import styles from './AddUserModal.less';
8
const { SHOW_CHILD } = TreeSelect;
陈前坚's avatar
陈前坚 committed
9

10
const AddUserModal = props => {
11
  const { visible, orgID, onCancel, updateTrees1, orgTitle1, onSelect, siteList } = props;
陈前坚's avatar
陈前坚 committed
12 13 14 15 16 17 18
  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,}$/,
  ); // 邮箱
19 20
  const [value, setValue] = useState(['0-1-1']);
  const [treeData, setTreeData] = useState([]);
21
  const [passwordLevel, setPasswordLevel] = useState(''); // 密码等级
22 23 24 25
  const onChange = newValue => {
    console.log('onChange ', value);
    setValue(newValue);
  };
陈前坚's avatar
陈前坚 committed
26 27

  useEffect(() => {
28 29 30
    if (visible) {
      addUserForm.resetFields();
      getEmptyRoleList();
31 32
    } else {
      setPasswordLevel('');
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    }
  }, [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);
      });
  };
陈前坚's avatar
陈前坚 committed
71 72 73 74 75 76 77 78

  // 提交-添加用户
  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') || '';
79

陈前坚's avatar
陈前坚 committed
80 81 82 83 84 85 86 87 88 89 90
    // 正则验证
    if (loginName === '') {
      notification.error({
        message: '提交失败',
        description: '登录名不能为空!',
      });
    } else if (!noChinese.test(loginName)) {
      notification.error({
        message: '提交失败',
        description: '登录名不支持中文!',
      });
91
    } else if (password === '') {
陈前坚's avatar
陈前坚 committed
92 93
      notification.error({
        message: '提交失败',
94
        description: '密码不能为空!',
陈前坚's avatar
陈前坚 committed
95
      });
96
    } else if (password.length < 6) {
97 98
      notification.error({
        message: '提交失败',
99
        description: '密码至少为6位,且包含数字和字母!',
100
      });
101
    } else if (userName === '') {
陈前坚's avatar
陈前坚 committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
      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))
    ) {
125
      console.log(addUserForm.getFieldValue('GroupId'), 'afasdf');
126
      console.log(orgID);
127
      addUser({
128
        GroupId: addUserForm.getFieldValue('GroupId') || '',
129 130 131 132 133 134 135
        OUID: orgID.id,
        loginName,
        userName,
        password: sha1(password).toUpperCase(),
        phone,
        email,
      })
陈前坚's avatar
陈前坚 committed
136
        .then(res => {
137
          console.log('fasdkljgiodsaujgioasdgi');
138
          if (res.code === 0) {
陈前坚's avatar
陈前坚 committed
139
            addUserForm.resetFields();
140
            onCancel(); // 设置Modal不可见
陈前坚's avatar
陈前坚 committed
141 142 143 144
            notification.success({
              message: '提交成功',
              duration: 2,
            });
145 146
            updateTrees1(orgID.id);
            onSelect([`${orgID.id}`]);
陈前坚's avatar
陈前坚 committed
147 148 149 150
            // 重新获取用户表
          } else {
            notification.error({
              message: '提交失败',
151
              description: res.msg,
陈前坚's avatar
陈前坚 committed
152 153 154 155 156 157 158 159
            });
          }
        })
        .catch(err => {
          message.error(err);
        });
    }
  };
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
  // 密码强度验证
  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;
190 191
      case 3:
        if (sValue.length > 8) {
192
          setPasswordLevel('强');
193 194
        } else {
          setPasswordLevel('中');
195
        }
196 197 198
        break;
      case 4:
        setPasswordLevel('强');
199 200 201
        break;
    }
  };
202 203
  const title = (
    <span>
204 205
<span style={{ fontWeight: 'bold', color: 'rgb(24, 144, 255)' }}>{orgTitle1}</span>
      下添加用户
206 207 208
    </span>
  );

209 210 211 212 213 214 215 216 217 218 219 220
  const tProps = {
    treeData,
    value,
    onChange,
    treeCheckable: true,
    showCheckedStrategy: SHOW_CHILD,
    placeholder: '请选择关联站点',
    style: {
      width: '100%',
    },
  };

221 222 223 224 225
  return (
    <Modal
      title={title}
      visible={visible}
      onCancel={onCancel}
226 227 228 229
      maskClosable={false}
      destroyOnClose
      afterClose={() => {
        addUserForm.resetFields();
230
        setPasswordLevel('');
231
      }}
232 233 234
      onOk={submitAddUser}
      okText="确认"
      cancelText="取消"
陈前坚's avatar
陈前坚 committed
235
    >
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
      <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>
252 253 254 255 256 257 258 259 260 261 262 263 264
          <div className={styles.formBox}>
            <Form.Item
              hasFeedback
              name="password"
              label="账号密码"
              rules={[
                {
                  pattern: /^[a-zA-Z0-9_]{6,16}$/,
                  message: '长度6-16位,支持字母与数字,允许下划线',
                },
                { required: true },
              ]}
            >
265 266 267 268 269 270 271 272 273 274 275
              <Input.Password
                placeholder="请输入账号密码(6~16位)"
                maxLength="16"
                onCopy={e => {
                  e.preventDefault();
                }}
                onPaste={e => {
                  // 禁止粘贴
                  e.preventDefault();
                }}
              />
276 277
            </Form.Item>
            <div
278
              style={{ right: '70px' }}
279 280 281 282 283 284 285 286 287 288
              className={classNames(styles.tipsText, {
                [styles.tipsRed]: passwordLevel === '弱',
                [styles.tipsOrange]: passwordLevel === '中',
                [styles.tipsGreen]: passwordLevel === '强',
              })}
            >
              {passwordLevel}
            </div>
          </div>

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
          <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>
330 331 332 333 334 335
          <Form.Item name="GroupId" label="关联站点" rules={[{ required: true }]}>
            {/* <TreeSelect {...tProps} showSearch treeDefaultExpandAll /> */}
            <Select
              allowClear
              showSearch
              filterOption={(input, option) =>
336
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
337 338 339 340 341
              }
              placeholder="请选择关联站点"
              options={siteList}
            />
          </Form.Item>
342 343
        </Form>
      </div>
344 345 346
    </Modal>
  );
};
陈前坚's avatar
陈前坚 committed
347 348

export default AddUserModal;