king
2020-06-28 48a18736c461ad730bd264b0ac7b40b68a0e33a1
src/views/login/index.jsx
@@ -1,51 +1,44 @@
import React, {Component} from 'react'
import { Form, Icon, Input, Button, Checkbox, Dropdown, Menu, message, Modal } from 'antd'
import React, { Component } from 'react'
import { message, Modal } from 'antd'
import { connect } from 'react-redux'
import md5 from 'md5'
import moment from 'moment'
import Api from '@/api'
import Utils from '@/utils/utils.js'
import options from '@/store/options.js'
import zhCN from '@/locales/zh-CN/login.js'
import enUS from '@/locales/en-US/login.js'
import options from '@/store/options.js'
import Utils from '@/utils/utils.js'
import logourl from '../../assets/img/login-logo.png'
import asyncLoadComponent from '@/utils/asyncLoadComponent'
import { modifyMemberLevel } from '@/store/action'
import './index.scss'
const { warning } = Modal
const LoginForm = asyncLoadComponent(() => import('./loginform'))
const LoginCloudForm = asyncLoadComponent(() => import('./logincloudform'))
const iszhCN = localStorage.getItem('lang') !== 'en-US'
class Login extends Component {
  constructor (props) {
    super(props)
    const iszhCN = !localStorage.getItem('lang') || localStorage.getItem('lang') === 'zh-CN'
    this.state = {
      langs: [{
        name: '中文简体',
        value: 'zh-CN'
      }, {
        name: 'English',
        value: 'en-US'
      }],
      selectedlang: iszhCN ?
        {
          name: '中文简体',
          value: 'zh-CN'
        } :
        {
          name: 'English',
          value: 'en-US'
        },
      dict: iszhCN ? zhCN : enUS,
      isDisabled: false,
      auth: false
    }
  state = {
    selectedlang: iszhCN ? 'zh-CN' : 'en-US',
    dict: iszhCN ? zhCN : enUS,
    isDisabled: false,
    auth: false,
    loginlogo: window.GLOB.loginlogo || '',
    bgImage: window.GLOB.bgImage || '',
    platName: window.GLOB.platName || '',
    copyRight: window.GLOB.copyRight || '',
    ICP: window.GLOB.ICP || '',
    lineColor: window.GLOB.lineColor || '',
    webSite: window.GLOB.webSite || '',
    langList: [],
    syncApp: false,
    syncing: false
  }
  changelang (item) {
    // 切换语言
    this.setState({
      selectedlang: item,
      dict: item.value === 'zh-CN' ? zhCN : enUS
      dict: item === 'zh-CN' ? zhCN : enUS
    })
  }
  
@@ -55,93 +48,108 @@
    return md5(md5(pwd + salt))
  }
  handleSubmit = e => {
    // 登录参数检验
    e.preventDefault()
    if (!this.state.auth) {
      warning({
        title: this.state.dict['login.auth.tip'],
        okText: this.state.dict['login.auth.ok'],
        cancelText: this.state.dict['login.auth.cancel'],
        onOk() {},
        onCancel() {}
      })
      return
    }
    this.props.form.validateFields((err, values) => {
      if (err) return
  handleSubmit = () => {
    this.loginformRef.handleConfirm().then(res => {
      this.setState({
        isDisabled: true
      })
      this.loginsubmit(values)
      this.loginsubmit(res)
    })
  }
  async loginsubmit (param) {
    if (options.sysType === 'local' && !window.GLOB.mainSystemApi) { // 业务系统必须设置单点地址
      Modal.warning({
        title: '未设置单点服务器地址,请联系管理员!'
      })
      return
    }
    // 登录提交
    // let password = this.md5Password(param.password)
    let password = param.password
    let result = await Api.loginsystem(param.username, password)
    if (!result.IsError) {
      Api.getusermsg(param.username, password).then(res => {
        if (res.status) {
          sessionStorage.setItem('UserID', res.UserID)
          sessionStorage.setItem('SessionUid', Utils.getuuid())
          sessionStorage.setItem('LoginUID', res.LoginUID)
          localStorage.setItem('lang', this.state.selectedlang.value)
          if (param.remember) { // 记住密码时账号密码存入localStorage
            localStorage.setItem('username', param.username)
            localStorage.setItem('password', param.password)
          } else {
            localStorage.removeItem('username')
            localStorage.removeItem('password')
          }
          if (this.props.location.state && this.props.location.state.from.pathname) {
            // 查看是否为其他页面跳转,路径存在时,跳回原页面
            this.props.history.replace(this.props.location.state.from.pathname)
          } else {
            this.props.history.replace('/main')
          }
        } else {
          message.warning(res.message)
        }
    let res = await Api.getusermsg(param.username, param.password)
    if (res.status) {
      sessionStorage.setItem('UserID', res.UserID)
      sessionStorage.setItem('SessionUid', Utils.getuuid())
      sessionStorage.setItem('LoginUID', res.LoginUID)
      sessionStorage.setItem('User_Name', res.UserName)
      sessionStorage.setItem('Full_Name', res.FullName)
      sessionStorage.setItem('avatar', res.icon || '')
      localStorage.setItem('lang', param.lang || 'zh-CN')
      let _url = window.location.href.split('#')[0]
      if (param.remember) { // 记住密码时账号密码存入localStorage
        localStorage.setItem(_url, window.btoa(window.encodeURIComponent(JSON.stringify({username: param.username, password: param.password}))))
      } else {
        localStorage.removeItem(_url)
      }
      if (this.props.location.state && this.props.location.state.from.pathname) {
        // 查看是否为其他页面跳转,路径存在时,跳回原页面
        this.props.history.replace(this.props.location.state.from.pathname)
      } else {
        this.props.history.replace('/main')
      }
    } else if (res.ErrCode === 'Need_Get_Appkey' && options.sysType === 'SSO') {
      message.warning('应用尚未创建,请向云端同步应用!')
      this.setState({
        isDisabled: false,
        syncApp: true
      })
    } else {
      message.warning(result.Message)
      message.warning(res.message)
      this.setState({
        isDisabled: false
      })
    }
  }
  UNSAFE_componentWillMount () {
  componentDidMount () {
    let timeStamp = new Date().getTime()
    let str = md5('MK19' + options.AppId + timeStamp)
    Api.systemauth(options.AppId, timeStamp).then(res => {
      if (res.status && res.EPC === str) {
        let box = []
        for (let i = 0; i < 15; i++) {
          let s = 'mksoft' + moment().add(i, 'days').format('YYYYMMDD')
          box.push(md5(s))
        }
        box = box.join(',')
        localStorage.setItem('AuthCode', box)
    let _appId = window.GLOB.appId
        this.setState({
          auth: true
        })
      } else {
    if (options.sysType === 'cloud') { // 云端使用系统配置appid
      _appId = options.caId
    }
    let str = md5('MK19' + _appId + timeStamp)
    let param = {
      rduri: 'http://minkesoft.com/mksepc/webapi/dostar',
      func: 'sEmpowerCloud_Get_LinkUrl',
      AppID: _appId,
      TimeStamp: timeStamp
    }
    Api.dostarInterface(param).then(res => {
      if (res.status) {
        if (res.EPC === str) {
          let box = []
          for (let i = 0; i < 15; i++) {
            let s = 'mksoft' + moment().add(i, 'days').format('YYYYMMDD')
            box.push(md5(s))
          }
          box = box.join(',')
          localStorage.setItem('AuthCode', box)
          this.setState({
            auth: true
          })
        } else {
          localStorage.removeItem('AuthCode')
          this.setState({
            auth: false
          })
        }
      } else if (res.ErrCode === 'N') {
        localStorage.removeItem('AuthCode')
        this.setState({
          auth: false
        })
      }
    })
    // console.log(options)
    // localStorage.setItem('AuthCode', [md5('mksoft' + moment().format('YYYYMMDD'))])
    let authCode = localStorage.getItem('AuthCode')
    let _s = md5('mksoft' + moment().format('YYYYMMDD'))
@@ -150,91 +158,205 @@
        auth: true
      })
    }
    // 获取系统信息
    let _param = {
      func: 's_Get_style',
      Appkey: window.GLOB.appkey || '',
      TypeCharOne: 'PC',
      LText: `select '${window.GLOB.appkey}'`,
    }
    _param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    _param.secretkey = Utils.encrypt(_param.LText, _param.timestamp)
    if (window.GLOB.mainSystemApi) {
      _param.rduri = window.GLOB.mainSystemApi.replace('dostars', 'dostar')
    }
    Api.dostarInterface(_param).then(res => {
      if (res.status) {
        let _url = window.location.href.split('#')[0] + 'system'
        let systemMsg = {
          favicon: res.titlelogo || '',
          platTitle: res.titleName || '',
          platName: res.SysName || '',
          bgImage: res.Banner || '',
          loginlogo: res.loginlogo || '',
          copyRight: res.CopyRightYear && res.CopyRightOrg ? `Copyright©${res.CopyRightYear}    所有相关版权归    ${res.CopyRightOrg}` : '',
          ICP: res.ICP || '',
          mainlogo: res.indexlogo || '',
          doclogo: res.doclogo || '',
          style: res.CSS || '',
          webSite: res.WebSite || ''
        }
        // url标题
        document.title = systemMsg.platTitle
        try {
          localStorage.setItem(_url, window.btoa(window.encodeURIComponent(JSON.stringify(systemMsg))))
        } catch {
          localStorage.removeItem(_url)
        }
        this.setState({
          langList: res.lang_data || [],
          ...systemMsg
        })
        window.GLOB.mainlogo = systemMsg.mainlogo
        if (res.titlelogo && window.GLOB.favicon !== res.titlelogo) {
          let link = document.querySelector("link[rel*='icon']") || document.createElement('link')
          link.type = 'image/x-icon'
          link.rel = 'shortcut icon'
          link.href = res.titlelogo
          document.getElementsByTagName('head')[0].appendChild(link)
        }
        let memberLevel = res.member_level
        if (typeof(memberLevel) === 'number' && memberLevel > 10 && parseInt(memberLevel / 10) * 10 === memberLevel) {
          sessionStorage.setItem('Member_Level', md5('mksoft' + moment().format('YYYYMM') + memberLevel))
          this.props.modifyMemberLevel(memberLevel)
        }
      } else {
        message.warning(res.message)
      }
    })
  }
  componentDidMount () {
    const input = document.getElementById('username')
    if (input) {
      input.focus()
  syncSubmit = () => {
    this.setState({
      syncing: true
    })
    let param = {
      func: 's_get_app_from_cloud',
      UserName: '',
      Password: '',
      systemType: options.sysType,
      Type: 'X',
      debug: 'Y'
    }
    param.appkey = window.GLOB.appkey || ''
    if (options.cloudServiceApi) {
      param.rduri = options.cloudServiceApi.replace('dostars', 'dostar')
    }
    this.logincloudRef.handleConfirm().then(result => {
      param.UserName = result.cloudusername
      param.Password = result.cloudpassword
      param.Password = Utils.formatOptions(param.Password)
      Api.dostarInterface(param).then(res => {
        if (res.status) {
          let _param = {
            func: 's_sDataDictb_TBBack',
            LTextOut: res.LTextOut,
            lid: res.Lid,
            Appkey: window.GLOB.appkey || ''
          }
          _param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
          _param.secretkey = Utils.encrypt(_param.LTextOut, _param.timestamp)
          _param.open_key = Utils.encrypt(_param.secretkey, _param.timestamp, true)
          Api.dostarInterface(_param).then(response => {
            if (response.status) {
              message.success('应用创建成功。')
              this.setState({
                syncing: false,
                syncApp: false
              })
            } else {
              this.setState({
                syncing: false
              })
              message.warning(response.message)
            }
          })
        } else {
          this.setState({
            syncing: false
          })
          message.warning(res.message)
        }
      })
    })
  }
  /**
   * @description 组件销毁,清除state更新
   */
  componentWillUnmount () {
    this.setState = () => {
      return
    }
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const menu = (
      <Menu>
        {this.state.langs.map((item, index) => {
          return (
            <Menu.Item key={index} onClick={() => {this.changelang(item)}}>
              <span>{item.name}</span>
            </Menu.Item>
          )
        })}
      </Menu>
    )
    const { lineColor, bgImage, loginlogo, copyRight, webSite, ICP } = this.state
    return (
      <div className="login-container">
        <div className="logo">
          <img src={logourl} alt=""/>
      <div className="login-container" style={bgImage ? {backgroundImage: 'url(' + bgImage + ')'} : {}}>
        <div className="logo" style={lineColor ? {borderColor: lineColor} : {}}>
          {loginlogo ? <img src={loginlogo} alt=""/> : null}
        </div>
        <div className="login-middle">
          <Form onSubmit={this.handleSubmit} className="login-form">
            <h4>明科商业智能开放平台</h4>
            <Form.Item>
              {getFieldDecorator('username', {
                rules: [{ required: true, message: this.state.dict['login.username.empty'] }],
                initialValue: localStorage.getItem('username') || '',
              })(
                <Input
                  prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                  placeholder={this.state.dict['login.username']}
                />,
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: this.state.dict['login.password.empty'] }],
                initialValue: localStorage.getItem('password') || '',
              })(
                <Input
                  prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                  type="password"
                  placeholder={this.state.dict['login.password']}
                />,
              )}
            </Form.Item>
            <Form.Item className="minline">
              {getFieldDecorator('remember', {
                valuePropName: 'checked',
                initialValue: true,
              })(<Checkbox>{this.state.dict['login.remember']}</Checkbox>)}
              <Dropdown overlay={menu} trigger={['click']} placement="bottomRight">
                <span className="ant-dropdown-link">
                  {this.state.selectedlang.name} <Icon type="down" />
                </span>
              </Dropdown>
            </Form.Item>
            <Form.Item className="btn-login">
              <Button type="primary" htmlType="submit" className="login-form-button" disabled={this.state.isDisabled} loading={this.state.isDisabled}>
                {this.state.dict['login.submit']}
              </Button>
            </Form.Item>
          </Form>
        <div className="login-middle" style={lineColor ? {borderColor: lineColor} : {}}>
          <LoginForm
            platName={this.state.platName}
            dict={this.state.dict}
            auth={this.state.auth}
            lang={this.state.selectedlang}
            langList={this.state.langList}
            isDisabled={this.state.isDisabled}
            changelang={(value) => this.changelang(value)}
            handleSubmit={() => this.handleSubmit()}
            wrappedComponentRef={(inst) => this.loginformRef = inst}
          />
        </div>
        <div className="login-bottom">
          <p>
            <span className="split">Copyright©2017</span>
            <span className="split">{this.state.dict['login.copyright']}</span>
            <span>北京明科普华信息技术有限公司</span>
          </p>
          <p>
            <span>ICP备案:</span>
            <span>京ICP备12007830号</span>
          </p>
          {webSite && copyRight ?
            <a target="blank" href={webSite} dangerouslySetInnerHTML={{ __html: copyRight.replace(/\s/ig, '&nbsp;') }}></a> :
            <p dangerouslySetInnerHTML={{ __html: copyRight ? copyRight.replace(/\s/ig, '&nbsp;') : '' }}></p>
          }
          {ICP ? <p dangerouslySetInnerHTML={{ __html: ICP.replace(/\s/ig, '&nbsp;') }}></p> : null}
        </div>
        {/* 编辑状态登录 */}
        <Modal
          title={this.state.dict['login.sync.cloud']}
          okText={this.state.dict['login.auth.ok']}
          cancelText={this.state.dict['login.auth.cancel']}
          visible={this.state.syncApp}
          onOk={this.syncSubmit}
          className="sync-cloud-application"
          width={'430px'}
          confirmLoading={this.state.syncing}
          onCancel={() => {this.setState({ syncApp: false, syncing: false })}}
          destroyOnClose
        >
          <LoginCloudForm handleSubmit={() => this.syncSubmit()} wrappedComponentRef={(inst) => this.logincloudRef = inst}/>
        </Modal>
      </div>
    )
  }
}
export default Form.create()(Login)
const mapStateToProps = () => {
  return {}
}
const mapDispatchToProps = (dispatch) => {
  return {
    modifyMemberLevel: (memberLevel) => dispatch(modifyMemberLevel(memberLevel))
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Login)