AddUserModal.jsx 11.9 KB
Newer Older
皮倩雯's avatar
皮倩雯 committed
1
/* eslint-disable no-unneeded-ternary */
2
import React, { useEffect, useState } from 'react';
3
import { Modal, Form, Input, notification, message, TreeSelect, Select } from 'antd';
4 5 6 7
import {
  addUser,
  GetUserRelationListNew,
  GetPasswordRegularization,
皮倩雯's avatar
皮倩雯 committed
8
  SysConfiguration,
9
} from '@/services/userManage/api';
皮倩雯's avatar
皮倩雯 committed
10
import { encipher } from '@wisdom-utils/utils/lib/helpers';
11
import classNames from 'classnames';
皮倩雯's avatar
皮倩雯 committed
12

皮倩雯's avatar
皮倩雯 committed
13
import { ok } from '../../../assets/images/icons/ok.svg';
14
import styles from './AddUserModal.less';
15
const { SHOW_CHILD } = TreeSelect;
陈前坚's avatar
陈前坚 committed
16

17
const AddUserModal = props => {
18
  const { visible, orgID, onCancel, updateTrees1, orgTitle1, onSelect, siteList } = props;
陈前坚's avatar
陈前坚 committed
19 20 21 22 23 24 25
  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,}$/,
  ); // 邮箱
26 27
  const [value, setValue] = useState(['0-1-1']);
  const [treeData, setTreeData] = useState([]);
28
  const [passwordLevel, setPasswordLevel] = useState(''); // 密码等级
29
  const [rules, setRules] = useState();
皮倩雯's avatar
皮倩雯 committed
30
  const [pasType, setPasType] = useState('');
31 32 33 34
  const onChange = newValue => {
    console.log('onChange ', value);
    setValue(newValue);
  };
陈前坚's avatar
陈前坚 committed
35

皮倩雯's avatar
皮倩雯 committed
36 37 38 39 40 41 42 43
  const passwordType = () => {
    SysConfiguration().then(res => {
      if (res.code === 0) {
        setPasType(res.data);
      }
    });
  };

陈前坚's avatar
陈前坚 committed
44
  useEffect(() => {
45
    if (visible) {
皮倩雯's avatar
皮倩雯 committed
46
      passwordType();
47
      getPasswordRule();
48 49
      addUserForm.resetFields();
      getEmptyRoleList();
50 51
    } else {
      setPasswordLevel('');
52 53 54
    }
  }, [orgID, visible]);

55 56 57 58 59 60 61 62
  const getPasswordRule = () => {
    GetPasswordRegularization().then(res => {
      if (res.code === 0) {
        setRules(res.data);
      }
    });
  };

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  // 获取全部未勾选站点列表
  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
98 99 100

  // 提交-添加用户
  const submitAddUser = () => {
101 102 103 104
    if (passwordLevel === '弱') {
      message.warning('请提高密码强度!');
      return;
    }
陈前坚's avatar
陈前坚 committed
105 106 107 108 109
    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') || '';
110 111 112 113 114 115
    addUserForm.validateFields().then(validate => {
      // 正则验证
      if (loginName === '') {
        notification.error({
          message: '提交失败',
          description: '登录名不能为空!',
陈前坚's avatar
陈前坚 committed
116
        });
117 118 119 120 121 122 123 124 125 126
      } else if (password === '') {
        notification.error({
          message: '提交失败',
          description: '密码不能为空!',
        });
      } else if (password.length < 6) {
        notification.error({
          message: '提交失败',
          description: '密码至少为6位,且包含数字和字母!',
        });
邓超's avatar
邓超 committed
127 128 129 130 131
      } else if (passwordLevel === '弱') {
        notification.error({
          message: '提交失败',
          description: '密码强度太弱,加强密码强度',
        });
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
      } 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: '邮箱格式不正确!',
        });
      }
148 149 150 151 152 153
      //  else if (!noChinese.test(loginName)) {
      //   notification.error({
      //     message: '提交失败',
      //     description: '登录名不支持中文!',
      //   });
      // }
154 155
      // 所有验证通过才可以提交,phone/email为空时不验证
      else if (
156
        // noChinese.test(loginName) &&
157 158 159 160 161 162 163 164 165 166 167 168
        password.length >= 6 &&
        userName &&
        (phone === '' || isPhone.test(phone)) &&
        (email === '' || isEmail.test(email))
      ) {
        console.log(addUserForm.getFieldValue('GroupId'), 'afasdf');
        console.log(orgID);
        addUser({
          GroupId: addUserForm.getFieldValue('GroupId') || '',
          OUID: orgID.id,
          loginName,
          userName,
皮倩雯's avatar
皮倩雯 committed
169
          password: encipher(password, pasType ? pasType : '').toUpperCase(),
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
          phone,
          email,
        })
          .then(res => {
            console.log('fasdkljgiodsaujgioasdgi');
            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);
          });
      }
    });
陈前坚's avatar
陈前坚 committed
197
  };
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  // 密码强度验证
  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;
228 229
      case 3:
        if (sValue.length > 8) {
230
          setPasswordLevel('强');
231 232
        } else {
          setPasswordLevel('中');
233
        }
234 235 236
        break;
      case 4:
        setPasswordLevel('强');
237 238 239
        break;
    }
  };
240 241
  const title = (
    <span>
242 243
<span style={{ fontWeight: 'bold', color: 'rgb(24, 144, 255)' }}>{orgTitle1}</span>
      下添加用户
244 245 246
    </span>
  );

247 248 249 250 251 252 253 254 255 256 257 258
  const tProps = {
    treeData,
    value,
    onChange,
    treeCheckable: true,
    showCheckedStrategy: SHOW_CHILD,
    placeholder: '请选择关联站点',
    style: {
      width: '100%',
    },
  };

259 260 261 262 263
  return (
    <Modal
      title={title}
      visible={visible}
      onCancel={onCancel}
264 265 266 267
      maskClosable={false}
      destroyOnClose
      afterClose={() => {
        addUserForm.resetFields();
268
        setPasswordLevel('');
269
      }}
270 271 272
      onOk={submitAddUser}
      okText="确认"
      cancelText="取消"
陈前坚's avatar
陈前坚 committed
273
    >
274 275 276 277 278 279 280 281
      <div className={styles.modalContent}>
        <Form form={addUserForm} labelCol={{ span: 4 }} onFieldsChange={changeValue}>
          <Form.Item
            hasFeedback
            name="loginName"
            label="登录名称"
            rules={[
              {
282
                pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]{0,}$/,
涂伟's avatar
涂伟 committed
283
                message: '长度小于16位,支持字母与数字,允许下划线',
284 285 286 287 288 289
              },
              { required: true },
            ]}
          >
            <Input placeholder="请输入登录名称(小于16位)" maxLength="16" />
          </Form.Item>
290 291 292 293 294 295 296
          <div className={styles.formBox}>
            <Form.Item
              hasFeedback
              name="password"
              label="账号密码"
              rules={[
                {
297 298
                  pattern: rules ? rules.regex : `/^(?=.*[a-zA-Z])(?=.*d)[wS]{6,16}$/`,
                  message: rules ? rules.tip : '长度6-16位,必须包含数字与字母',
邓超's avatar
邓超 committed
299 300 301 302
                },
                {
                  pattern: /^(?!.*(?:SELECT|UPDATE|INSERT|AND|OR|'|"|;|--|\\)).*$/,
                  message: '当前密码存在sql注入风险,请重新输入', // 防止sql注入
303 304 305 306
                },
                { required: true },
              ]}
            >
307
              <Input.Password
皮倩雯's avatar
皮倩雯 committed
308
                placeholder={rules ? rules.tip : '请输入账号密码长度6~16位,必须包含数字与字母'}
309 310 311 312 313 314 315 316 317
                maxLength="16"
                onCopy={e => {
                  e.preventDefault();
                }}
                onPaste={e => {
                  // 禁止粘贴
                  e.preventDefault();
                }}
              />
318 319
            </Form.Item>
            <div
320
              style={{ right: '70px' }}
321 322 323 324 325 326 327 328 329 330
              className={classNames(styles.tipsText, {
                [styles.tipsRed]: passwordLevel === '弱',
                [styles.tipsOrange]: passwordLevel === '中',
                [styles.tipsGreen]: passwordLevel === '强',
              })}
            >
              {passwordLevel}
            </div>
          </div>

331 332 333 334 335 336 337
          <Form.Item
            hasFeedback
            name="userName"
            label="用户姓名"
            rules={[
              { required: true },
              {
338 339
                pattern: /^(?=.{1,15}$)[A-Za-z0-9_\u4e00-\u9fa5·]+$/,
                //pattern: /^[A-Za-z0-9_\u4e00-\u9fa5]+$/,
340
                message: '长度小于16位,支持字母、中文与数字,允许"·" 和"_"',
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
              },
            ]}
          >
            <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>
373 374 375 376 377 378
          <Form.Item name="GroupId" label="关联站点" rules={[{ required: true }]}>
            {/* <TreeSelect {...tProps} showSearch treeDefaultExpandAll /> */}
            <Select
              allowClear
              showSearch
              filterOption={(input, option) =>
379
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
380 381 382 383 384
              }
              placeholder="请选择关联站点"
              options={siteList}
            />
          </Form.Item>
385 386
        </Form>
      </div>
387 388 389
    </Modal>
  );
};
陈前坚's avatar
陈前坚 committed
390 391

export default AddUserModal;