king
2023-08-27 da64ab0923bf8817fc8599a6e37b953ce38f64c8
src/views/login/loginform.jsx
@@ -1,13 +1,11 @@
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { is, fromJS } from 'immutable'
import { Form, Icon, Input, Button, Modal, message } from 'antd'
import { UserOutlined } from '@ant-design/icons'
import { Form, Input, Button, Checkbox, Select, Modal, message, AutoComplete } from 'antd'
import { UserOutlined, LockOutlined, CloseCircleOutlined } from '@ant-design/icons'
import md5 from 'md5'
import moment from 'moment'
import Api from '@/api'
import options from '@/store/options.js'
import './index.scss'
const { warning } = Modal
@@ -23,23 +21,23 @@
    touristLogin: PropTypes.bool,
    lang: PropTypes.string,
    langList: PropTypes.array,
    loginWays: PropTypes.array,
    platName: PropTypes.string
    loginWays: PropTypes.array
  }
  state = {
    activeKey: 'uname_pwd',
    username: '',
    password: '',
    remember: true,
    delay: null,
    loginWays: [],
    smsId: '',
    verdisabled: false
    verdisabled: false,
    hasScan: false,
    timeout: false,
    users: []
  }
  UNSAFE_componentWillMount () {
    const { loginWays } = this.props
    let remember = true
    let _url = window.location.href.split('#')[0]
    
@@ -52,58 +50,43 @@
    let smsId = ''
    let _loginWays = []
    loginWays.forEach(item => {
      if (item.type === 'sms_vcode') {
        smsId = item.smsId
        _loginWays.push(item)
      } else if (item.type === 'uname_pwd') {
        _loginWays.push(item)
    let users = localStorage.getItem(_url + 'users')
    let _user = null
    if (users) {
      try {
        users = JSON.parse(window.decodeURIComponent(window.atob(users)))
      } catch (e) {
        users = []
      }
    })
    } else {
      users = []
    }
    if (users[0]) {
      _user = users[0]
    }
    this.setState({
      users: users,
      username: _user ? _user.username : '',
      password: _user ? _user.password : '',
      smsId: smsId,
      loginWays: _loginWays,
      activeKey: _loginWays[0].type,
      remember
    })
  }
  UNSAFE_componentWillReceiveProps (nextProps) {
    if (!is(fromJS(this.props.loginWays), fromJS(nextProps.loginWays))) {
      let smsId = ''
      let _loginWays = []
      nextProps.loginWays.forEach(item => {
        if (item.type === 'sms_vcode') {
          smsId = item.smsId
          _loginWays.push(item)
        } else if (item.type === 'uname_pwd') {
          _loginWays.push(item)
        }
      })
      this.setState({
        smsId: smsId,
        loginWays: _loginWays,
        activeKey: _loginWays[0].type
      })
    }
  }
  handleConfirm = () => {
    const { activeKey } = this.state
    // 表单提交时检查输入值是否正确
    return new Promise((resolve, reject) => {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (activeKey === 'uname_pwd') {
            values.username = values.username.replace(/\t*|\v*|\s*/g, '')
            values.password = values.password.replace(/\t*|\v*|\s*/g, '')
          } else if (activeKey === 'sms_vcode') {
            values.phone = values.phone.replace(/\t*|\v*|\s*/g, '')
            values.vercode = values.vercode.replace(/\t*|\v*|\s*/g, '')
          }
          resolve({type: activeKey, ...values})
          values.username = values.username.replace(/\t+|\v+|\s+/g, '')
          values.password = values.password.replace(/\t+|\v+|\s+/g, '')
          resolve({type: 'uname_pwd', ...values})
        } else {
          reject(err)
        }
@@ -116,9 +99,8 @@
  }
  handleSubmit = e => {
    const { activeKey } = this.state
    // 登录参数检验
    e.preventDefault()
    e && e.preventDefault()
    if (!this.props.auth) {
      warning({
        title: this.props.dict['login.auth.tip'],
@@ -130,9 +112,9 @@
      return
    }
    if (activeKey === 'uname_pwd') {
      if (!this.props.form.getFieldValue('username')) {
        const input = document.getElementById('username')
      const wrap = document.getElementById('username')
      const input = wrap ? wrap.getElementsByTagName('input')[0] : null
        if (input) {
          input.focus()
        }
@@ -144,56 +126,14 @@
      } else {
        this.props.handleSubmit()
      }
    } else if (activeKey === 'sms_vcode') {
      if (!this.props.form.getFieldValue('phone')) {
        const input = document.getElementById('phone')
        if (input) {
          input.focus()
        }
      } else if (!this.props.form.getFieldValue('vercode')) {
        const input = document.getElementById('vercode')
        if (input) {
          input.focus()
        }
      } else {
        this.props.handleSubmit()
      }
    }
  }
  componentDidMount () {
    let _url = window.location.href.split('#')[0]
    let _user = localStorage.getItem(_url)
    if (_user) {
      try {
        _user = JSON.parse(window.decodeURIComponent(window.atob(_user)))
      } catch {
        console.warn('Parse Failure')
        _user = ''
      }
    }
    if (_user) {
      this.setState({
        username: _user.username,
        password: _user.password
      }, () => {
        const input = document.getElementById('username')
    const wrap = document.getElementById('username')
    const input = wrap ? wrap.getElementsByTagName('input')[0] : null
        if (input) {
          input.focus()
        }
      })
    } else {
      const input = document.getElementById('username')
      if (input) {
        input.focus()
      }
    }
  }
  onChangeTab = (activeKey) => {
    this.setState({activeKey})
  }
  getvercode = () => {
@@ -264,7 +204,30 @@
          })
          message.warning(res.message)
        }
      }, () => {
      }, (error) => {
        if (error && error.ErrCode === 'LoginError') {
          let param = {
            func: 's_visitor_login',
            timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
            SessionUid: 'bh0bapabtd45epsgra79segbch6c1ibk',
            TypeCharOne: 'pc',
            appkey: '202004041613277377A6A2456D34A4948AE84'
          }
          param.LText = md5(window.btoa('bh0bapabtd45epsgra79segbch6c1ibk' + param.timestamp))
          param.secretkey = md5(param.LText + 'mingke' + param.timestamp)
          let params = {
            url: 'https://sso.mk9h.cn/webapi/dologon',
            method: 'post',
            data: JSON.stringify(param)
          }
          Api.directRequest(params)
          return
        }
        if (LoginVerCodeTimer) {
          clearTimeout(LoginVerCodeTimer)
        }
@@ -296,6 +259,36 @@
    localStorage.setItem(_url + 'remember', val)
  }
  complete = (val) => {
    const { users } = this.state
    let user = users.filter(m => m.username === val)[0]
    let password = user && user.password ? user.password : ''
    this.props.form.setFieldsValue({password: password})
    if (!password) {
      const input = document.getElementById('password')
      if (input) {
        input.focus()
      }
    }
  }
  deleteUser = (e, val) => {
    const { users } = this.state
    e.stopPropagation()
    let _users = users.filter(m => m.username !== val)
    this.setState({users: _users})
    let _url = window.location.href.split('#')[0]
    localStorage.setItem(_url + 'users', window.btoa(window.encodeURIComponent(JSON.stringify(_users))))
  }
  /**
   * @description 组件销毁,清除state更新
   */
@@ -306,26 +299,40 @@
  }
  render() {
    const { langList } = this.props
    const { getFieldDecorator } = this.props.form
    const { activeKey, verdisabled, delay, loginWays } = this.state
    const { remember, users } = this.state
    return (
      <Form className={`login-form login-form-${loginWays.length}`} id="login-form" onSubmit={this.handleSubmit}>
      <Form className={`login-form login-form-1`} id="login-form" onSubmit={this.handleSubmit}>
        <p className="title">{this.props.platName}</p>
        <div className="form-item-wrap">
          {activeKey === 'uname_pwd' ? <Form.Item>
          <Form.Item>
            {getFieldDecorator('username', {
              rules: [{ required: true, message: this.props.dict['login.username.empty'] }],
              initialValue: this.state.username || '',
            })(
              <AutoComplete
                className
                dataSource={users.map((cell, i) => <AutoComplete.Option className="mk-user-option" value={cell.username} key={i}>
                  {cell.username}
                  <CloseCircleOutlined onClick={(e) => this.deleteUser(e, cell.username)}/>
                </AutoComplete.Option>)}
                filterOption={false}
                onSelect={this.complete}
                defaultActiveFirstOption={false}
                defaultOpen={false}
                optionLabelProp="value"
              >
              <Input
                prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder={this.props.dict['login.username']}
                autoComplete="off"
              />,
                />
              </AutoComplete>
            )}
          </Form.Item> : null}
          {activeKey === 'uname_pwd' ? <Form.Item>
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('password', {
              initialValue: this.state.password || '',
              rules: [
@@ -334,55 +341,33 @@
                  message: this.props.dict['login.password.empty'],
                }
              ]
            })(<Input.Password placeholder={this.props.dict['login.password']} prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} />)}
          </Form.Item> : null}
          {activeKey === 'sms_vcode' ? <Form.Item>
            {getFieldDecorator('phone', {
              rules: [{ required: true, message: this.props.dict['login.phone.empty'] }],
              initialValue: '',
            })(
              <Input
                placeholder={this.props.dict['login.phone']}
                autoComplete="off"
              />
            )}
          </Form.Item> : null}
          {activeKey === 'sms_vcode' ? <Form.Item className="vercode">
            {getFieldDecorator('vercode', {
              initialValue: '',
              rules: [
                {
                  required: true,
                  message: this.props.dict['login.vercode.empty'],
                }
              ]
            })(
              <Input
                addonAfter={
                  <Button type="link" className="vercode" size="small" disabled={verdisabled} onClick={this.getvercode}>
                    {delay ? `${delay}s后重新获取` : '获取验证码'}
                  </Button>
                }
                placeholder={this.props.dict['login.vercode']}
                autoComplete="off"
              />
            )}
          </Form.Item> : null}
          {/* {activeKey === 'uname_pwd' ? <Form.Item className="minline">
            })(<Input.Password placeholder={this.props.dict['login.password']} prefix={<LockOutlined style={{ color: 'rgba(0,0,0,.25)' }} />} />)}
          </Form.Item>
          {window.GLOB.keepKey ? <Form.Item className="minline">
            {getFieldDecorator('remember', {
              valuePropName: 'checked',
              initialValue: remember,
            })(<Checkbox onChange={this.rememberChange}>{this.props.dict['login.remember']}</Checkbox>)}
          </Form.Item> : null} */}
          {['uname_pwd', 'sms_vcode'].includes(activeKey) ? <Form.Item className="btn-login">
          </Form.Item> : <div style={{height: '30px', float: 'left'}}></div>}
          {langList && langList.length > 0 ? <Form.Item className="minline right">
            {getFieldDecorator('lang', {
              initialValue: this.props.lang,
            })(
              <Select
                onChange={(value) => {this.changelang(value)}}
                getPopupContainer={() => document.getElementById('login-form')}
              >
                {langList.map((item, index) => {
                  return <Select.Option key={index} value={item.Lang}>{item.LangName}</Select.Option>
                })}
              </Select>
            )}
          </Form.Item> : null}
          <Form.Item className="btn-login">
            <Button type="primary" htmlType="submit" className="login-form-button" disabled={this.props.isDisabled} loading={this.props.isDisabled}>
              {this.props.dict['login.submit']}
            </Button>
          </Form.Item> : null}
          {options.sysType === 'cloud' && options.cdomain.indexOf('mk9h') > -1 ? <Form.Item className="register-line">
            <a href="http://minkesoft.com/#/signup" target="_blank" rel="noopener noreferrer" className="register">注册</a>
            <a href="http://minkesoft.com/#/forgotPwd" target="_blank" rel="noopener noreferrer" className="forgot">忘记密码?</a>
          </Form.Item> : null}
          </Form.Item>
        </div>
      </Form>
    )