king
2020-01-17 a0a285c90987eb9b1591f90333f3aeb15659ded2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import React, {Component} from 'react'
import { withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
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,
  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/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'))
const { confirm } = Modal
 
class Header extends Component {
  static propTpyes = {
    collapse: PropTypes.bool,
    mainMenu: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object
    ])
  }
  state = {
    menulist: null, // 一级菜单
    visible: false, // 修改密码模态框
    dict: (!localStorage.getItem('lang') || localStorage.getItem('lang') === 'zh-CN') ? zhCN : enUS,
    confirmLoading: false,
    userName: sessionStorage.getItem('User_Name'),
    logourl: window.GLOB.mainlogo || logourl,
    loginVisible: false,
    loginLoading: false,
    avatar: avatar,
    systems: []
  }
 
  handleCollapse = () => {
    // 展开、收起左侧菜单栏
    if (!this.props.editState) {
      this.props.toggleCollapse(!this.props.collapse)
    }
  }
 
  changePassword = () => {
    // 点击修改密码,显示弹窗
    this.setState({
      visible: true
    })
  }
 
  resetPwdSubmit = () => {
    this.formRef.handleConfirm().then(res => {
      this.setState({
        confirmLoading: true
      })
      this.resetPwdSubmitexec(res)
    }, () => {})
  }
 
  async resetPwdSubmitexec (param) {
    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
      })
      notification.success({
        top: 92,
        message: this.state.dict['header.password.resetsuccess'],
        duration: 2
      })
    } else {
      notification.warning({
        top: 92,
        message: result.message || localResult.message,
        duration: 10
      })
      this.setState({
        confirmLoading: false
      })
    }
  }
 
  handleCancel = () => {
    // 取消时关闭修改密码模态框,清空表单数据
    this.setState({
      visible: false
    })
  }
 
  logout = () => {
    // 退出登录
    let _this = this
    confirm({
      title: this.state.dict['header.logout.hint'],
      content: '',
      okText: this.state.dict['header.confirm'],
      cancelText: this.state.dict['header.cancel'],
      onOk() {
        sessionStorage.clear()
        _this.props.logout()
        _this.props.history.replace('/login')
      },
      onCancel() {}
    })
  }
 
  changeMenu (value) {
    // 主菜单切换
    if (this.props.editState && this.props.editLevel) {
      // 编辑状态下,不可切换菜单
      return
    }
    if (value.PageParam.OpenType === 'menu') {
      this.props.modifyMainMenu(value)
    } else {
      window.open('#/' + value.PageParam.linkUrl + '/')
    }
  }
 
  async loadmenu () {
    // 获取主菜单
    let result = await Api.getSystemConfig({func: 'sPC_Get_MainMenu'})
    if (result.status) {
      if (result.debug === 'true') { // 是否为debug模式,即可复制菜单参数
        this.props.resetDebug()
      }
 
      let MainMenuId = sessionStorage.getItem('MainMenu') // 是否为打开新页面
      if (MainMenuId) {
        // 通过url中menuid筛选出选中的主菜单
        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])
      }
 
      this.setState({
        menulist: result.data.map((item, index) => {
          item.id = index
          item.text = item.MenuName
          if (item.PageParam) {
            try {
              item.PageParam = JSON.parse(item.PageParam)
            } catch (e) {
              item.PageParam = {OpenType: 'menu', linkUrl: ''}
            }
          } else {
            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.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)
    }
  }
 
  reload = () => {
    this.setState({
      menulist: null
    })
    this.loadmenu()
  }
 
  changeEditState = (state) => {
    // 修改编辑状态
    let UserID = sessionStorage.getItem('CloudUserID')
    let LoginUID = sessionStorage.getItem('CloudLoginUID')
 
    sessionStorage.setItem('isEditState', state)
    if (state && (!UserID || !LoginUID)) {
      this.setState({
        loginVisible: true
      })
    } else {
      this.setState({
        menulist: null
      })
      this.loadmenu()
      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)
 
          this.setState({
            menulist: null,
            loginVisible: false,
            loginLoading: false
          })
          this.loadmenu()
          this.props.resetEditState(true)
        } else {
          notification.error({
            top: 92,
            message: res.message,
            duration: 15
          })
        }
      })
    })
  }
 
  enterEdit = () => {
    // 进入编辑状态
    this.props.resetEditLevel('level1')
  }
  
  exitEdit = () => {
    // 退出编辑状态
    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()
  }
 
  UNSAFE_componentWillReceiveProps () {
 
  }
 
  shouldComponentUpdate (nextProps, nextState) {
    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} checked={this.props.editState} onChange={this.changeEditState} />
        </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={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>
        {/* 正常菜单 */}
        {this.props.editLevel !== 'level1' && this.state.menulist &&
        <ul className="header-menu">{
          this.state.menulist.map(item => {
            return (
              <li key={item.MenuID} onClick={() => {this.changeMenu(item)}} className={this.props.selectmenu.MenuID === item.MenuID ? 'active' : ''}>
                <span>{item.MenuName}</span>
              </li>
            )
          })}
        </ul>}
        {/* 进入编辑按钮 */}
        {this.props.editState && !this.props.editLevel && <Icon onClick={this.enterEdit} className="edit-check" type="edit" />}
        {/* 编辑菜单 */}
        {this.props.editLevel === 'level1' && <EditMenu menulist={this.state.menulist} reload={this.reload} exitEdit={this.exitEdit}/>}
        {/* 头像、用户名 */}
        <Dropdown className="header-setting" overlay={menu}>
          <div>
            <img src={this.state.avatar} alt=""/>
            <span>
              <span className="username">{this.state.userName}</span> <Icon type="down" />
            </span>
          </div>
        </Dropdown>
        {/* 修改密码 */}
        <Modal
          title={this.state.dict['header.password']}
          okText={this.state.dict['header.confirm']}
          cancelText={this.state.dict['header.cancel']}
          visible={this.state.visible}
          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>
    )
  }
}
 
const mapStateToProps = (state) => {
  return {
    collapse: state.collapse,
    selectmenu: state.selectedMainMenu,
    debug: state.debug,
    editState: state.editState,
    editLevel: state.editLevel,
    permAction: state.permAction,
    permFuncField: state.permFuncField
  }
}
 
const mapDispatchToProps = (dispatch) => {
  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()),
    logout: () => dispatch(logout())
  }
}
 
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Form.create()(Header)))