king
2022-08-06 cbeffcc0902631909c0373f274752a97ddaf2d4e
src/components/header/index.jsx
@@ -4,17 +4,17 @@
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import moment from 'moment'
import { Dropdown, Menu, Icon, Modal, Form, notification, Switch, Input, Badge } from 'antd'
import { Dropdown, Menu, Modal, Form, notification, Switch, Input } from 'antd'
import { SearchOutlined, DownOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons'
import {
  toggleCollapse,
  modifyMenuTree,
  modifyMainMenu,
  modifyTabview,
  initActionPermission,
  initMenuPermission,
  logout
} from '@/store/action'
import asyncComponent from '@/utils/asyncSpinComponent'
import Api from '@/api'
import MKEmitter from '@/utils/events.js'
import options from '@/store/options.js'
@@ -22,12 +22,12 @@
import enUS from '@/locales/en-US/main.js'
import Utils from '@/utils/utils.js'
import avatar from '@/assets/img/avatar.jpg'
import Resetpwd from './resetpwd'
import LoginForm from './loginform'
import './index.scss'
const { confirm } = Modal
const { Search } = Input
const Resetpwd = asyncComponent(() => import('./resetpwd'))
const LoginForm = asyncComponent(() => import('./loginform'))
class Header extends Component {
  static propTpyes = {
@@ -38,16 +38,16 @@
    visible: false, // 修改密码模态框
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    confirmLoading: false,
    userName: sessionStorage.getItem('User_Name'),
    userName: '',
    fullName: '',
    logourl: window.GLOB.mainlogo,
    appVersion: window.GLOB.appVersion,
    loginVisible: false,
    loginLoading: false,
    avatar: Utils.getrealurl(sessionStorage.getItem('avatar')),
    systems: [],
    searchkey: '',
    thdMenuList: [],
    oriVersion: '',
    newVersion: '',
    debug: sessionStorage.getItem('debug') === 'true',
    navBar: ['linkage_navigation', 'linkage', 'menu_board', 'menu_board_navigation'].includes(window.GLOB.navBar) ? 'topmenu' : '',
    menuType: window.GLOB.navBar
@@ -67,6 +67,8 @@
  }
  resetPwdSubmit = () => {
    if (!this.formRef) return
    this.formRef.handleConfirm().then(res => {
      this.setState({
        confirmLoading: true
@@ -90,9 +92,14 @@
        if (result.status) {
          notification.success({
            top: 92,
            message: this.state.dict['main.password.resetsuccess'],
            message: '修改成功,请重新登录。',
            duration: 2
          })
          setTimeout(() => {
            sessionStorage.clear()
            this.props.logout()
            this.props.history.replace('/login')
          }, 2000)
        } else {
          notification.warning({
            top: 92,
@@ -139,31 +146,33 @@
    // 获取角色权限
    let roledefer = new Promise(resolve => {
      // edition_type 接口版本控制 ''、'Y'、'A'
      Api.getSystemConfig({
        func: 's_Get_TrdMenu_Role',
        edition_type: 'A',
        pro_sys: window.GLOB.systemType === 'production' ? 'Y' : ''
      }).then(result => {
        let _permAction = {loaded: true} // 按钮权限
        if (result && result.status) {
          if (result.UserRoles_Menu) {
            result.UserRoles_Menu.forEach(menu => {
              if (!menu.MenuID) return
              _permAction[menu.MenuID] = true
      setTimeout(() => {
        Api.getSystemConfig({
          func: 's_Get_TrdMenu_Role',
          edition_type: 'A',
          pro_sys: window.GLOB.systemType === 'production' ? 'Y' : ''
        }).then(result => {
          let _permAction = {loaded: true} // 按钮权限
          if (result && result.status) {
            if (result.UserRoles_Menu) {
              result.UserRoles_Menu.forEach(menu => {
                if (!menu.MenuID) return
                _permAction[menu.MenuID] = true
              })
            }
          } else if (result) {
            notification.error({
              top: 92,
              message: result.message,
              duration: 10
            })
          }
        } else if (result) {
          notification.error({
            top: 92,
            message: result.message,
            duration: 10
          })
        }
        this.props.initActionPermission(_permAction)
        resolve()
      })
          this.props.initActionPermission(_permAction)
          resolve()
        })
      }, 50)
    })
    // 获取主菜单参数
@@ -183,10 +192,19 @@
        const { menulist, thdMenuList } = this.getMenulist(result)
        let systems = []
        if ((options.sysType === 'local' || options.sysType === 'SSO') && result.sys_list) {
          systems = result.sys_list
          if (options.sysType === 'local' && window.GLOB.systemType !== 'production' && systems.length > 10) {
            systems.length = 10
          }
        }
        this.setState({
          menulist,
          thdMenuList,
          systems: window.GLOB.systemType === 'production' || options.sysType === 'SSO' ? (result.sys_list || []) : []
          systems: systems
        })
        
        let mainMenu = menulist[0] || ''
@@ -213,7 +231,6 @@
          sessionStorage.removeItem('ThirdMenu')
        }
        this.props.modifyMenuTree(menulist)
        this.props.modifyMainMenu(mainMenu)
        this.props.initMenuPermission([...thdMenuList, {MenuID: 'home_page_id', EasyCode: '', MenuName: 'home', type: 'CustomPage'}])
@@ -223,21 +240,12 @@
    
    Promise.all([roledefer, menudefer]).then(response => {
      if (response[1]) {
        let tabs = fromJS(this.props.tabviews).toJS()
        let menu = fromJS(response[1]).toJS()
        if (this.state.navBar === 'topmenu') {
          menu.selected = true
          this.props.modifyTabview([menu])
        if (this.state.navBar === 'topmenu' && this.state.menuType !== 'menu_board_navigation') {
          MKEmitter.emit('modifyTabs', menu, 'replace')
        } else {
          tabs = tabs.map(tab => {
            tab.selected = false
            return tab
          })
          menu.selected = true
          tabs.push(menu)
          this.props.modifyTabview(tabs)
          MKEmitter.emit('modifyTabs', menu, 'plus')
        }
      }
    })
@@ -386,21 +394,38 @@
      sessionStorage.setItem('dataM', sessionStorage.getItem('cloudDataM'))
      sessionStorage.setItem('isEditState', 'true')
      this.props.modifyMenuTree([])
      this.props.modifyMainMenu(null)
      this.props.modifyTabview([])
      this.props.history.replace('/design')
    }
  }
  loginSubmit = () => {
    if (!this.loginRef) return
    this.setState({
      loginLoading: true
    })
    this.loginRef.handleConfirm().then(param => {
      Api.getusermsg(param.username, param.password, true).then(res => {
        if (res.status) {
          this.setState({
            loginLoading: false
          })
          if (res.modifydate) {
            let s = (new Date().getTime() - new Date(res.modifydate).getTime()) / (1000 * 24 * 60 * 60)
            if (!isNaN(s) && s > 90) {
              Modal.warning({
                width: 520,
                title: <span>系统检测到您的账户存在风险,请及时到<a target="_blank" rel="noopener noreferrer" href="https://cloud.mk9h.cn/admin/index.html">云中心</a>修改密码!</span>,
                okText: '知道了'
              })
              return
            }
          }
          sessionStorage.setItem('CloudUserID', res.UserID)
          sessionStorage.setItem('CloudLoginUID', res.LoginUID)
          sessionStorage.setItem('CloudUserName', res.UserName)
@@ -413,12 +438,14 @@
          sessionStorage.setItem('dataM', res.dataM ? 'true' : '')
          sessionStorage.setItem('isEditState', 'true')
          if (param.remember) {
            let _url = window.location.href.split('#')[0] + 'cloud'
            localStorage.setItem(_url, window.btoa(window.encodeURIComponent(JSON.stringify({time: new Date().getTime(), username: param.username, password: param.password}))))
          }
          this.setSystemFuncs()
          this.props.modifyMenuTree([])
          this.props.modifyMainMenu(null)
          this.props.modifyTabview([])
          this.props.history.replace('/design')
        } else {
          if (res.message.indexOf('密码错误') > -1) {
@@ -450,7 +477,6 @@
            message: result.message,
            duration: 10
          })
          return
        } else if (result.func_detail && result.func_detail.length > 0) {
          this.writeFuncs(result.func_detail)
        }
@@ -555,18 +581,40 @@
      url = url + '/'
    }
    let href = url + 'index.html#/ssologin/' + window.btoa(window.encodeURIComponent(JSON.stringify({
      UserID: sessionStorage.getItem('UserID'),
      LoginUID: sessionStorage.getItem('LoginUID'),
      User_Name: sessionStorage.getItem('User_Name'),
      Full_Name: sessionStorage.getItem('Full_Name'),
      avatar: sessionStorage.getItem('avatar'),
      dataM: system.dataM ? 'true' : '',
      debug: system.debug || '',
      role_id: system.role_id || ''
    })))
    let key = Utils.getuuid()
    window.open(href)
    let _param = {
      func: 'webapi_scan_binding_key',
      binding_type: 'mk',
      scan_type: 'toggle',
      scan_appkey: system.scan_appkey,
      id: key
    }
    Api.getSystemConfig(_param).then(res => {
      if (!res.status) {
        notification.warning({
          top: 92,
          message: res.message,
          duration: 5
        })
      } else if (res.thd_party_appid && res.thd_party_member_id && res.thd_party_openid) {
        let href = url + 'admin/index.html#/ssologin/' + window.btoa(window.encodeURIComponent(JSON.stringify({
          appid: res.thd_party_appid,
          memberId: res.thd_party_member_id,
          openid: res.thd_party_openid,
          key: key
        })))
        window.open(href)
      } else {
        notification.warning({
          top: 92,
          message: '信息缺失,请联系管理员!',
          duration: 5
        })
      }
    })
  }
  dropdownMenuChange = (visible) => {
@@ -583,26 +631,28 @@
  UNSAFE_componentWillMount () {
    // 组件加载时,获取菜单数据
    this.getRolesMenu()
  }
  UNSAFE_componentWillReceiveProps (nextProps) {
    if (!is(fromJS(this.props.menuTree), fromJS(nextProps.menuTree)) && !is(fromJS(this.state.menulist), fromJS(nextProps.menuTree))) {
      this.setState({
        menulist: nextProps.menuTree
      })
    let fullName = sessionStorage.getItem('Full_Name') || ''
    let userName = sessionStorage.getItem('User_Name') || ''
    if (fullName.toLowerCase() === userName.toLowerCase()) {
      userName = ''
    }
    this.setState({fullName, userName})
  }
  componentDidMount () {
    // 获取系统的版本信息,延时查询
    setTimeout(() => {
      Api.getAppVersion().then(res => {
        this.setState({
          oriVersion: res.oldVersion,
          newVersion: res.newVersion
        })
      }, () => {})
      Api.getAppVersion().then(() => {}, () => {})
    }, 1000)
    // Api.genericInterface({
    //   func: 's_get_fcc_account_data',
    //   fcc_date: '2022-03-01',
    //   search_type: ''
    // }).then(res => {
    // })
  }
  shouldComponentUpdate (nextProps, nextState) {
@@ -618,45 +668,13 @@
    }
  }
  verup = () => {
    const { oriVersion, newVersion } = this.state
    const _this = this
    confirm({
      title: this.state.dict['main.verup'],
      content: `最新版本${newVersion},当前版本${oriVersion}`,
      onOk() {
        return new Promise(resolve => {
          if (!window.GLOB.WebSql) {
            notification.warning({
              top: 92,
              message: '升级失败,请刷新页面重试!',
              duration: 2
            })
            resolve()
          } else {
            Api.updateAppVersion(newVersion)
            notification.success({
              top: 92,
              message: '升级成功!',
              duration: 2
            })
            _this.setState({oriVersion: newVersion})
            resolve()
          }
        })
      },
      onCancel() {}
    })
  }
  gotoDoc = () => {
    if (options.sysType === 'local' && window.GLOB.mainSystemApi) {
      let ssodomain = window.GLOB.mainSystemApi.replace('/webapi/dostars', '')
      let url = `${ssodomain}/doc/index.html#?appkey=${window.GLOB.appkey}&LoginUID=${sessionStorage.getItem('LoginUID')}`
      window.open(url)
    } else if (options.sysType === 'SSO' || options.sysType === 'cloud') {
      window.open(`${window.location.href.replace(/\/index.html(.*)|\/#(.*)/ig, '')}/doc/index.html#?appkey=${window.GLOB.appkey}&LoginUID=${sessionStorage.getItem('LoginUID')}`)
      window.open(`${window.location.href.replace(/\/admin(.*)|\/index.html(.*)|\/#(.*)/ig, '')}/doc/index.html#?appkey=${window.GLOB.appkey}&LoginUID=${sessionStorage.getItem('LoginUID')}`)
    }
  }
@@ -671,27 +689,11 @@
      if (menu.OpenType === 'newpage' || menu.OpenType === 'NewPage') { // NewPage为打开外部页面地址,newpage为打开系统菜单
        window.open(menu.src)
      } else if (menu.OpenType === 'blank') {
        menu.selected = true
        this.props.modifyTabview([menu])
        MKEmitter.emit('modifyTabs', menu, 'replace')
      } else if (this.state.navBar === 'topmenu' && this.state.menuType !== 'menu_board_navigation') {
        menu.selected = true
        this.props.modifyTabview([menu])
        MKEmitter.emit('modifyTabs', menu, 'replace')
      } else {
        let tabs = fromJS(this.props.tabviews).toJS()
        tabs = tabs.filter(tab => {
          tab.selected = false
          return tab.MenuID !== menu.MenuID
        })
        if (this.props.tabviews.length > tabs.length) {
          this.props.modifyTabview(fromJS(tabs).toJS())
        }
        this.setState({}, () => {
          menu.selected = true
          tabs.push(menu)
          this.props.modifyTabview(tabs)
        })
        MKEmitter.emit('modifyTabs', menu, 'plus')
      }
  
      if (window.GLOB.systemType === 'production') {
@@ -700,9 +702,45 @@
    }
  }
  verup = () => {
    confirm({
      title: '页面更新',
      content: '重新加载应用信息',
      onOk() {
        return new Promise(resolve => {
          if (!window.GLOB.WebSql && !window.GLOB.IndexDB) {
            notification.warning({
              top: 92,
              message: '更新失败,请刷新页面重试!',
              duration: 2
            })
            resolve()
          } else {
            Api.updateAppVersion()
            setTimeout(() => {
              notification.success({
                top: 92,
                message: '更新成功!',
                duration: 2
              })
              resolve()
            }, 1000)
          }
        })
      },
      onCancel() {}
    })
  }
  about = () => {
    Modal.success({
      title: '系统版本v' + this.state.appVersion
    })
  }
  render () {
    const { mainMenu, collapse } = this.props
    const { thdMenuList, searchkey, oriVersion, newVersion, debug, menulist, navBar, menuType } = this.state
    const { thdMenuList, searchkey, debug, menulist, navBar, menuType, appVersion } = this.state
    const menu = (
      <Menu className="header-dropdown">
@@ -717,8 +755,11 @@
          ))}
        </Menu.SubMenu> : null}
        <Menu.Item key="doc" onClick={this.gotoDoc}>{this.state.dict['main.doc']}</Menu.Item>
        {oriVersion ? <Menu.Item key="verup" onClick={this.verup}>
          <Badge dot={oriVersion !== newVersion}>{this.state.dict['main.verup']}</Badge>
        <Menu.Item key="verup" onClick={this.verup}>
          页面更新
        </Menu.Item>
        {appVersion ? <Menu.Item key="version" onClick={this.about}>
          关于
        </Menu.Item> : null}
        <Menu.Item key="logout" onClick={this.logout}>{this.state.dict['main.logout']}</Menu.Item>
      </Menu>
@@ -728,7 +769,7 @@
      <header className="header-container ant-menu-dark" id="main-header-container">
        <div className={'header-logo ' + (collapse && navBar !== 'topmenu' ? 'collapse' : '')}><img src={this.state.logourl} alt=""/></div>
        <div className={'header-collapse ' + (collapse && navBar !== 'topmenu' ? 'collapse' : '')}>
          {navBar !== 'topmenu' ? <Icon type={collapse ? 'menu-unfold' : 'menu-fold'} onClick={this.handleCollapse}/> : null}
          {navBar !== 'topmenu' ? (collapse ? <MenuUnfoldOutlined onClick={this.handleCollapse}/> : <MenuFoldOutlined onClick={this.handleCollapse}/>) : null}
        </div>
        {/* 正常菜单 */}
        {navBar !== 'topmenu' && menulist ?
@@ -828,7 +869,7 @@
          <div>
            <img src={this.state.avatar || avatar} alt=""/>
            <span>
              <span className="username">{this.state.userName}</span> <Icon type="down" />
              <span className="username"><span>{this.state.fullName}</span>{this.state.userName ? <span>{this.state.userName}</span> : null}</span> <DownOutlined />
            </span>
          </div>
        </Dropdown>
@@ -865,7 +906,7 @@
              </div>
            </div>
          } trigger={['click']} className="search-menu" placement="bottomRight" onVisibleChange={this.dropdownMenuChange}>
            <Icon className="search-menu" type="search" />
            <SearchOutlined className="search-menu" />
          </Dropdown> : null
        }
        {/* 修改密码 */}
@@ -898,19 +939,14 @@
const mapStateToProps = (state) => {
  return {
    tabviews: state.tabviews,
    collapse: state.collapse,
    menuTree: state.menuTree,
    mainMenu: state.mainMenu,
    permAction: state.permAction,
    mainMenu: state.mainMenu
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    toggleCollapse: (collapse) => dispatch(toggleCollapse(collapse)),
    modifyTabview: (tabviews) => dispatch(modifyTabview(tabviews)),
    modifyMenuTree: (menuTree) => dispatch(modifyMenuTree(menuTree)),
    modifyMainMenu: (mainMenu) => dispatch(modifyMainMenu(mainMenu)),
    initActionPermission: (permAction) => dispatch(initActionPermission(permAction)),
    initMenuPermission: (permMenus) => dispatch(initMenuPermission(permMenus)),