king
2020-02-21 063b983daaf51a7f1e8677bde1e9c0e618866c91
src/components/header/index.jsx
@@ -3,17 +3,27 @@
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import {Dropdown, Menu, Icon, Modal, message, Form, notification, Switch } from 'antd'
import md5 from 'md5'
import moment from 'moment'
import {Dropdown, Menu, Icon, Modal, Form, notification, Switch } from 'antd'
import asyncComponent from '@/utils/asyncComponent'
import {toggleCollapse, modifyMainMenu, resetState, resetDebug, resetEditState, resetEditLevel} from '@/store/action'
import Resetpwd from '@/components/resetpwd'
import {
  toggleCollapse,
  modifyMainMenu,
  resetState,
  resetDebug,
  resetEditState,
  resetEditLevel,
  initPermission,
  logout
} from '@/store/action'
import Api from '@/api'
import zhCN from '@/locales/zh-CN/header.js'
import enUS from '@/locales/en-US/header.js'
import Utils from '@/utils/utils.js'
import logourl from '@/assets/img/mlogo.png'
import logourl from '@/assets/img/main-logo.png'
import avatar from '@/assets/img/avatar.jpg'
import Resetpwd from './resetpwd'
import LoginForm from './loginform'
import './index.scss'
const EditMenu = asyncComponent(() => import('./editmenu'))
@@ -32,7 +42,12 @@
    visible: false, // 修改密码模态框
    dict: (!localStorage.getItem('lang') || localStorage.getItem('lang') === 'zh-CN') ? zhCN : enUS,
    confirmLoading: false,
    userName: localStorage.getItem('username')
    userName: sessionStorage.getItem('User_Name'),
    logourl: window.GLOB.mainlogo || logourl,
    loginVisible: false,
    loginLoading: false,
    avatar: avatar,
    systems: []
  }
  handleCollapse = () => {
@@ -49,12 +64,6 @@
    })
  }
  md5Password (pwd) {
    // md5密码加密
    const salt = 'minkesoft'
    return md5(md5(pwd + salt))
  }
  resetPwdSubmit = () => {
    this.formRef.handleConfirm().then(res => {
      this.setState({
@@ -65,21 +74,36 @@
  }
  async resetPwdSubmitexec (param) {
    // 重置密码提交,关闭模态框,清空表单数据
    let password = this.md5Password(param.originpwd)
    let newpassword = this.md5Password(param.password)
    let result = await Api.resetpassword(password, newpassword)
    if (result.status) {
    let _param = {
      func: 's_PwdUpt',
      LText: `select '${param.originpwd}','${param.password}'`
    }
    _param.LText = Utils.formatOptions(_param.LText)                   // 关键字符替换,base64加密
    _param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000' // 时间戳
    _param.secretkey = Utils.encrypt(_param.LText, _param.timestamp)   // md5密钥
    let localResult = await Api.getLocalConfig(_param)
    let result = {status: true}
    if (window.GLOB.mainSystemApi && window.GLOB.subSystemApi !== window.GLOB.mainSystemApi) {
      result = await Api.getSystemConfig(_param)
    }
    if (result.status && localResult.status) {
      this.setState({
        visible: false,
        confirmLoading: false
      })
      this.formRef.resetfrom()
      message.success(this.state.dict['header.password.resetsuccess'])
      notification.success({
        top: 92,
        message: this.state.dict['header.password.resetsuccess'],
        duration: 2
      })
    } else {
      notification.warning({
        top: 92,
        message: result.message,
        message: result.message || localResult.message,
        duration: 10
      })
      this.setState({
@@ -93,7 +117,6 @@
    this.setState({
      visible: false
    })
    this.formRef.resetfrom()
  }
  logout = () => {
@@ -105,16 +128,9 @@
      okText: this.state.dict['header.confirm'],
      cancelText: this.state.dict['header.cancel'],
      onOk() {
        sessionStorage.clear()
        _this.props.logout()
        _this.props.history.replace('/login')
        // return Api.logoutsystem().then(res => {
        //   if (res.status) {
        //     sessionStorage.removeItem('UserID')
        //     _this.props.resetState()
        //     _this.props.history.replace('/login')
        //   } else {
        //     message.warning(res.message)
        //   }
        // })
      },
      onCancel() {}
    })
@@ -135,25 +151,26 @@
  async loadmenu () {
    // 获取主菜单
    let result = await Api.getSystemConfig({func: 'sPC_Get_MainMenu'})
    if (result.status) {
      let _avatar = Utils.getrealurl(result.HeadIcon) // 头像
      if (_avatar) {
        avatar = _avatar
      }
    let _param = {func: 'sPC_Get_MainMenu'}
    if (sessionStorage.getItem('isEditState') === 'true') { // 编辑状态时,获取一级菜单,增加参数debug
      _param.debug = 'Y'
    }
    let result = await Api.getSystemConfig(_param)
    // 登录超时
    if (!result) return
    if (result.status) {
      if (result.debug === 'true') { // 是否为debug模式,即可复制菜单参数
        this.props.resetDebug()
      }
      let param = sessionStorage.getItem('view_param') // 是否为打开新页面
      if (param) {
      let MainMenuId = sessionStorage.getItem('MainMenu') // 是否为打开新页面
      if (MainMenuId) {
        // 通过url中menuid筛选出选中的主菜单
        let menuId = param.split('&')[0]
        let _menu = result.data.filter(item => item.MenuID === menuId)[0]
        if (!_menu) {
          sessionStorage.removeItem('view_param')
        }
        let _menu = result.data.filter(item => item.MenuID === MainMenuId)[0]
        sessionStorage.removeItem('MainMenu')
        this.props.modifyMainMenu(_menu || result.data[0])
      } else {
        this.props.modifyMainMenu(result.data[0])
@@ -173,8 +190,44 @@
            item.PageParam = {OpenType: 'menu', linkUrl: ''}
          }
          return item
        })
        }),
        systems: result.Systems.filter(sys => sys.LinkUrl1 && sys.AppKey !== window.GLOB.appkey)
      })
    } else {
      notification.error({
        top: 92,
        message: result.message,
        duration: 15
      })
    }
  }
  async getRolesMenu () {
    // 获取角色权限
    let result = await Api.getSystemConfig({func: 'sPC_Get_RolesMenu'})
    // 登录超时
    if (!result) return
    if (result.status) {
      let _permAction = {}
      let _permFuncField = []
      if (result.UserRoles && result.UserRoles[0] && result.UserRoles[0].RoleMenu) {
        result.UserRoles[0].RoleMenu.forEach(menu => {
          _permAction[menu.MenuID] = true
        })
      }
      if (result.sModular && result.sModular.length > 0) {
        result.sModular.forEach(field => {
          if (field.ModularNo) {
            _permFuncField.push(field.ModularNo)
          }
        })
        _permFuncField = _permFuncField.sort()
      }
      this.props.initPermission(_permAction, _permFuncField)
    }
  }
@@ -187,7 +240,80 @@
  changeEditState = (state) => {
    // 修改编辑状态
    this.props.resetEditState(state)
    let UserID = sessionStorage.getItem('CloudUserID')
    let LoginUID = sessionStorage.getItem('CloudLoginUID')
    if (state && (!UserID || !LoginUID)) {
      this.setState({
        loginVisible: true
      })
    } else {
      sessionStorage.setItem('isEditState', state)
      let _userName = sessionStorage.getItem('User_Name')
      let _avatar = this.state.avatar
      if (!state && sessionStorage.getItem('avatar')) {
        _avatar = Utils.getrealurl(sessionStorage.getItem('avatar')) // 头像
      } else if (state && sessionStorage.getItem('CloudAvatar')) {
        _avatar = Utils.getrealurl(sessionStorage.getItem('CloudAvatar')) // 头像
      }
      if (state) {
        _userName = sessionStorage.getItem('CloudUserName')
      }
      this.setState({
        menulist: null,
        userName: _userName,
        avatar: _avatar
      })
      this.loadmenu()
      this.props.modifyMainMenu('')
      this.props.resetEditState(state)
    }
  }
  loginSubmit = () => {
    this.setState({
      loginLoading: true
    })
    this.loginRef.handleConfirm().then(param => {
      Api.getusermsg(param.username, param.password, true).then(res => {
        if (res.status) {
          sessionStorage.setItem('CloudUserID', res.UserID)
          sessionStorage.setItem('CloudSessionUid', Utils.getuuid())
          sessionStorage.setItem('CloudLoginUID', res.LoginUID)
          sessionStorage.setItem('CloudUserName', res.UserName)
          sessionStorage.setItem('CloudAvatar', res.icon)
          sessionStorage.setItem('isEditState', 'true')
          let _avatar = this.state.avatar
          if (res.icon) {
            _avatar = Utils.getrealurl(res.icon) // 头像
          }
          this.setState({
            menulist: null,
            loginVisible: false,
            loginLoading: false,
            userName: res.UserName,
            avatar: _avatar
          })
          this.loadmenu()
          this.props.modifyMainMenu('')
          this.props.resetEditState(true)
        } else {
          this.setState({
            loginLoading: false
          })
          notification.error({
            top: 92,
            message: res.message,
            duration: 15
          })
        }
      })
    })
  }
  enterEdit = () => {
@@ -199,9 +325,19 @@
    // 退出编辑状态
    this.props.resetEditLevel(false)
  }
  changeSystem = (system) => {
    let _param = window.btoa('ud=' + sessionStorage.getItem('UserID') + '&sd=' + sessionStorage.getItem('SessionUid') + '&ld=' + sessionStorage.getItem('LoginUID') + '&un=' + sessionStorage.getItem('User_Name'))
    window.location.href = system.LinkUrl1 + '#/ssologin/' + _param
  }
  
  UNSAFE_componentWillMount () {
    // 组件加载时,获取菜单数据
    let _avatar = sessionStorage.getItem('avatar')
    if (_avatar) {
      _avatar = Utils.getrealurl(_avatar) // 头像
      this.setState({avatar: _avatar})
    }
    this.loadmenu()
  }
@@ -213,21 +349,30 @@
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
  componentDidMount () {
    this.getRolesMenu()
  }
  render () {
    const menu = (
      <Menu overlayclassname="header-dropdown">
        {this.props.debug && <Menu.Item key="0">
          {this.state.dict['header.edit']}
          <Switch size="small" className="edit-switch" disabled={!!this.props.editLevel} onChange={this.changeEditState} />
          <Switch size="small" className="edit-switch" disabled={!!this.props.editLevel} checked={this.props.editState} onChange={this.changeEditState} />
        </Menu.Item>}
        <Menu.Item key="1" onClick={this.changePassword}>{this.state.dict['header.password']}</Menu.Item>
        {!this.props.editState ? <Menu.Item key="1" onClick={this.changePassword}>{this.state.dict['header.password']}</Menu.Item> : null}
        {/* {this.state.systems.length > 0 ? <Menu.SubMenu title="切换系统">
          {this.state.systems.map((system, index) => (
            <Menu.Item className="header-subSystem" key={'sub' + index} onClick={() => {this.changeSystem(system)}}> {system.AppName} </Menu.Item>
          ))}
        </Menu.SubMenu> : null} */}
        <Menu.Item key="2" onClick={this.logout}>{this.state.dict['header.logout']}</Menu.Item>
      </Menu>
    )
    return (
      <header className="header-container ant-menu-dark">
        <div className={this.props.collapse ? "collapse header-logo" : "header-logo"}><img src={logourl} alt=""/></div>
        <div className={this.props.collapse ? "collapse header-logo" : "header-logo"}><img src={this.state.logourl} alt=""/></div>
        <div className={this.props.collapse ? "collapse header-collapse" : "header-collapse"} onClick={this.handleCollapse}>
          <Icon type={this.props.collapse ? 'menu-unfold' : 'menu-fold'} />
        </div>
@@ -237,7 +382,7 @@
          this.state.menulist.map(item => {
            return (
              <li key={item.MenuID} onClick={() => {this.changeMenu(item)}} className={this.props.selectmenu.MenuID === item.MenuID ? 'active' : ''}>
                {item.MenuName}
                <span>{item.MenuName}</span>
              </li>
            )
          })}
@@ -249,7 +394,7 @@
        {/* 头像、用户名 */}
        <Dropdown className="header-setting" overlay={menu}>
          <div>
            <img src={avatar} alt=""/>
            <img src={this.state.avatar} alt=""/>
            <span>
              <span className="username">{this.state.userName}</span> <Icon type="down" />
            </span>
@@ -264,8 +409,23 @@
          onOk={this.resetPwdSubmit}
          confirmLoading={this.state.confirmLoading}
          onCancel={this.handleCancel}
          destroyOnClose
        >
          <Resetpwd dict={this.state.dict} wrappedComponentRef={(inst) => this.formRef = inst} resetPwdSubmit={this.resetPwdSubmit}/>
        </Modal>
        {/* 编辑状态登录 */}
        <Modal
          title={this.state.dict['header.login.develop']}
          okText={this.state.dict['header.confirm']}
          cancelText={this.state.dict['header.cancel']}
          visible={this.state.loginVisible}
          onOk={this.loginSubmit}
          width={'430px'}
          confirmLoading={this.state.loginLoading}
          onCancel={() => {this.setState({ loginVisible: false, loginLoading: false })}}
          destroyOnClose
        >
          <LoginForm handleSubmit={() => this.loginSubmit()} wrappedComponentRef={(inst) => this.loginRef = inst}/>
        </Modal>
      </header>
    )
@@ -278,7 +438,9 @@
    selectmenu: state.selectedMainMenu,
    debug: state.debug,
    editState: state.editState,
    editLevel: state.editLevel
    editLevel: state.editLevel,
    permAction: state.permAction,
    permFuncField: state.permFuncField
  }
}
@@ -286,10 +448,12 @@
  return {
    toggleCollapse: (collapse) => dispatch(toggleCollapse(collapse)),
    modifyMainMenu: (selectmenu) => dispatch(modifyMainMenu(selectmenu)),
    resetEditState: (state) => dispatch(resetEditState(state)),
    resetEditLevel: (level) => dispatch(resetEditLevel(level)),
    initPermission: (permAction, permFuncField) => dispatch(initPermission(permAction, permFuncField)),
    resetState: () => dispatch(resetState()),
    resetDebug: () => dispatch(resetDebug()),
    resetEditState: (state) => dispatch(resetEditState(state)),
    resetEditLevel: (level) => dispatch(resetEditLevel(level))
    logout: () => dispatch(logout())
  }
}