king
2020-08-09 ce2b708f61de1855771d78f35309bd77df9d3b15
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import { notification, Spin, Tabs, Icon} from 'antd'
import moment from 'moment'
 
import Api from '@/api'
import zhCN from '@/locales/zh-CN/main.js'
import enUS from '@/locales/en-US/main.js'
import Utils from '@/utils/utils.js'
import options from '@/store/options.js'
import asyncComponent from '@/utils/asyncLoadComponent'
 
import FormGroup from './formgroup'
import FormAction from './actionList'
import NotFount from '@/components/404'
import {refreshTabView, modifyTabview} from '@/store/action'
import './index.scss'
 
const { TabPane } = Tabs
const SubTable = asyncComponent(() => import('@/tabviews/subtable'))
 
class NormalTable extends Component {
  static propTpyes = {
    MenuID: PropTypes.string,       // 菜单Id
    param: PropTypes.any,           // 主表传递参数
    refresh: PropTypes.any          // 刷新主表页面
  }
 
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    ContainerId: Utils.getuuid(), // 菜单外层html Id
    loadingview: true,    // 页面加载中
    viewlost: false,      // 页面丢失:1、未获取到配置-页面丢失;2、页面未启用
    lostmsg: '',          // 页面丢失时的提示信息
    config: {},           // 页面配置信息,包括按钮、表单、标签等
    groups: null,         // 表单组
    actions: null,        // 按钮集
    arr_field: '',        // 使用 sPC_Get_TableData 时的查询字段集
    setting: null,        // 页面全局设置:数据源、按钮及显示列固定、主键等
    data: null,           // 列表数据集
    configMap: {},        // 页面配置信息:下拉、按钮等
    BIDs: {},             // 上级表id
    setsingle: false,     // 主表单选多选切换
    pickup: false,        // 主表数据隐藏显示切换
    popData: false,       // 弹框页面,所选的表格数据
    visible: false,       // 弹框显示隐藏控制
    primaryId: null,
    refreshtabs: null
  }
 
  /**
   * @description 获取页面配置信息
   */
  async loadconfig () {
    const { permAction } = this.props
 
    let param = {
      func: 'sPC_Get_LongParam',
      MenuID: this.props.MenuID
    }
    let result = await Api.getCacheConfig(param)
    if (result.status) {
      let config = ''
 
      try { // 配置信息解析
        config = JSON.parse(window.decodeURIComponent(window.atob(result.LongParam)))
      } catch (e) {
        console.warn('Parse Failure')
        config = ''
      }
 
      // 页面配置解析错误时提示
      if (!config) {
        this.setState({
          loadingview: false,
          viewlost: true
        })
        return
      }
 
      // 页面未启用时,显示未启用页面
      if (!config.enabled) {
        this.setState({
          loadingview: false,
          viewlost: true,
          lostmsg: this.state.dict['main.view.unenabled']
        })
        return
      }
 
      // 兼容标签
      if (!config.tabgroups) {
        config.tabgroups = [{ uuid: 'tabs', sublist: [] }]
      } else if (typeof(config.tabgroups[0]) === 'string') {
        let _tabgroups = []
        config.tabgroups.forEach(groupId => {
          let _group = {
            uuid: groupId,
            sublist: fromJS(config[groupId]).toJS()
          }
  
          delete config[groupId]
  
          _tabgroups.push(_group)
        })
  
        config.tabgroups = _tabgroups
      }
 
      // 权限过滤
      if (this.props.menuType !== 'HS') {
        config.action = config.action.filter(item => permAction[item.uuid])
        config.tabgroups.forEach(group => {
          group.sublist = group.sublist.filter(tab => permAction[tab.linkTab])
        })
      }
 
      let _arrField = [config.setting.primaryKey]     // 字段集 , 默认添加主键
 
      config.groups.forEach(group => {
        group.sublist = group.sublist.filter(item => {
          if (!item.blacklist || item.blacklist.length === 0) {
            _arrField.push(item.field)
            return true
          }
 
          let _black = item.blacklist.filter(v => {
            return this.props.permRoles.indexOf(v) !== -1
          })
 
          if (_black.length > 0) {
            return false
          } else {
            _arrField.push(item.field)
            return true
          }
        })
      })
      _arrField = _arrField.join(',')
 
      this.setState({
        config: config,
        setting: config.setting,
        actions: config.action,
        arr_field: _arrField,
        primaryId: this.props.param.primaryId || '',
        data: this.props.param.data || null,
        BIDs: {
          mainTable: config.setting.onload !== 'false' ? (this.props.param.primaryId || '') : '',
          mainTabledata: config.setting.onload !== 'false' ? (config.setting.datatype === 'query' ? '' : this.props.param.data) : ''
        }
      }, () => {
        this.improveSelectOption(config.groups)
 
        if (config.setting.datatype === 'query' && config.setting.onload !== 'false') {
          this.loadmaindata()
        } else if (config.setting.datatype !== 'query' && (!this.props.param.primaryId || !this.props.param.data)) {
          notification.warning({
            top: 92,
            message: '未获取到主表数据!',
            duration: 5
          })
        }
      })
    } else {
      this.setState({
        loadingview: false,
        viewlost: true
      })
      notification.warning({
        top: 92,
        message: result.message,
        duration: 5
      })
    }
  }
 
  /**
   * @description 表单下拉选项加载
   */
  improveSelectOption = (groups) => {
    let deffers = []
    groups.forEach(group => {
      group.sublist = group.sublist.map(item => {
        if (item.type !== 'multiselect' && item.type !== 'select' && item.type !== 'link') return item
 
        if (item.setAll === 'true') {
          item.options.unshift({
            key: Utils.getuuid(),
            Value: '',
            Text: this.state.dict['main.all']
          })
        }
  
        if (item.resourceType === '1' && item.dataSource) {
          let _option = Utils.getSelectQueryOptions(item)
          let _sql = Utils.formatOptions(_option.sql)
          let isSSO = item.database === 'sso'
  
          let param = {
            func: 'sPC_Get_SelectedList',
            LText: _sql,
            obj_name: 'data',
            arr_field: _option.field
          }
 
          if (this.props.dataManager) { // 数据权限
            param.LText = param.LText.replace(/\$@/ig, '/*')
            param.LText = param.LText.replace(/@\$/ig, '*/')
          } else {
            param.LText = param.LText.replace(/@\$|\$@/ig, '')
          }
  
          param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
          param.secretkey = Utils.encrypt(param.LText, param.timestamp)
 
          if (this.props.menuType === 'HS') { // 云端数据验证
            param.open_key = Utils.encrypt(param.secretkey, param.timestamp, true)
          }
  
          let defer = new Promise(resolve => {
            Api.getSystemCacheConfig(param, isSSO).then(res => {
              res.search = item
              resolve(res)
            })
          })
          deffers.push(defer)
        } else if (item.resourceType === '1' && !item.dataSource) {
          notification.warning({
            top: 92,
            message: item.label + ': ' + this.state.dict['main.datasource.settingerror'],
            duration: 5
          })
        }
 
        return item
      })
    })
    
    if (deffers.length === 0) {
      this.setState({
        loadingview: false,
        groups: groups
      })
      return
    }
 
    Promise.all(deffers).then(result => {
      let _result = {}
      result.forEach(res => {
        if (res.status) {
          let _options = res.data.map(cell => {
            let _item = {
              key: Utils.getuuid(),
              Value: cell[res.search.valueField],
              Text: cell[res.search.valueText]
            }
 
            if (res.search.type === 'link') {
              _item.ParentID = cell[res.search.linkField]
            } else if (res.search.type === 'select' && res.search.linkSubField && res.search.linkSubField.length > 0) {
              res.search.linkSubField.forEach(_field => {
                _item[_field] = (cell[_field] || cell[_field] === 0) ? cell[_field] : ''
              })
            }
 
            return _item
          })
 
          _result[res.search.uuid] = _options
        } else {
          notification.warning({
            top: 92,
            message: res.search.label + ':' + res.message,
            duration: 5
          })
        }
      })
 
      groups.forEach(group => {
        group.sublist = group.sublist.map(item => {
          if (item.type === 'select' || item.type === 'link' || item.type === 'multiselect') {
            if (_result[item.uuid]) {
              item.options = [...item.options, ..._result[item.uuid]]
            }
            item.oriOptions = JSON.parse(JSON.stringify(item.options))
          }
          
          return item
        })
      })
 
      this.setState({
        loadingview: false,
        groups: groups
      })
    })
  }
 
  /**
   * @description 主表数据加载
   */ 
  async loadmaindata () {
    const { setting, BIDs, config } = this.state
 
    if (setting.datatype !== 'query') {
      notification.warning({
        top: 92,
        message: '未设置数据查询配置!',
        duration: 5
      })
      return
    }
 
    let param = null
 
    if (setting.interType !== 'inner' || (setting.interType === 'inner' && setting.innerFunc)) {
      param = this.getCustomParam()
    } else {
      param = this.getDefaultParam()
    }
 
    if (!param) return // 未获取参数时,不发请求
 
    // 数据管理权限
    if (this.props.dataManager) {
      param.dataM = 'Y'
    }
 
    let result = await Api.genericInterface(param)
    if (result.status) {
      let _data = result.data[0] || ''
      let _primaryId = ''
 
      if (_data) {
        _primaryId = _data[setting.primaryKey] || ''
      } else {
        notification.warning({
          top: 92,
          message: '未查询到数据信息!',
          duration: 5
        })
      }
 
      this.setState({
        data: _data,
        primaryId: _primaryId,
        BIDs: {
          ...BIDs,
          mainTable: _primaryId,
          mainTabledata: _data
        }
      })
 
      if (_data && (setting.interType !== 'inner' || (setting.interType === 'inner' && setting.innerFunc))) {
        let keys = Object.keys(_data)
        let emptys = []
 
        if (!keys.includes(config.setting.primaryKey)) {
          emptys.push(config.setting.primaryKey)
        }
 
        config.groups.forEach(group => {
          group.sublist.forEach(item => {
            if (!keys.includes(item.field)) {
              emptys.push(item.field + '(' + item.label + ')')
            }
          })
        })
 
        if (emptys.length > 0) {
          notification.warning({
            top: 92,
            message: '未查询到' + emptys.join(', ') + '字段信息!',
            duration: 5
          })
        }
      }
    } else {
      notification.error({
        top: 92,
        message: result.message,
        duration: 10
      })
    }
  }
 
  /**
   * @description 获取系统存储过程 sPC_Get_TableData 的参数
   */
  getDefaultParam = () => {
    const { arr_field, setting, primaryId } = this.state
 
    if (!arr_field) {
      notification.warning({
        top: 92,
        message: '未设置表单字段!',
        duration: 5
      })
      return null
    }
    
    let param = {
      func: 'sPC_Get_TableData',
      obj_name: 'data',
      arr_field: arr_field,
      ID: primaryId
    }
    
    let _dataresource = setting.dataresource
 
    if (/\s/.test(_dataresource)) {
      _dataresource = '(' + _dataresource + ') tb'
    }
 
    if (this.props.dataManager) { // 数据权限
      _dataresource = _dataresource.replace(/\$@/ig, '/*')
      _dataresource = _dataresource.replace(/@\$/ig, '*/')
      // param.custom_script = param.custom_script.replace(/\$@/ig, '/*')
      // param.custom_script = param.custom_script.replace(/@\$/ig, '*/')
    } else {
      _dataresource = _dataresource.replace(/@\$|\$@/ig, '')
      // param.custom_script = param.custom_script.replace(/@\$|\$@/ig, '')
    }
 
    if (!/@ID@/ig.test(_dataresource)) {
      _dataresource = `${_dataresource} where ${setting.primaryKey}='${primaryId}'`
    }
 
    let LText = `select ${arr_field} from ${_dataresource}`
 
    param.LText = Utils.formatOptions(LText)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    param.secretkey = Utils.encrypt(param.LText, param.timestamp)
    param.DateCount = ''
 
    if (this.props.menuType !== 'HS') { // 云端数据验证
      param.open_key = Utils.encrypt(param.secretkey, param.timestamp, true)
    }
 
    return param
  }
 
  /**
   * @description 获取用户自定义存储过程传参
   */
  getCustomParam = () => {
    const { setting, primaryId } = this.state
 
    let param = {}
 
    if (setting.interType === 'inner') {
      param.func = setting.innerFunc
    } else {
      if (this.props.menuType === 'HS') {
        if (setting.sysInterface === 'true' && options.cloudServiceApi) {
          param.rduri = options.cloudServiceApi
        } else if (setting.sysInterface !== 'true') {
          param.rduri = setting.interface
        }
      } else {
        if (setting.sysInterface === 'true' && window.GLOB.mainSystemApi) {
          param.rduri = window.GLOB.mainSystemApi
        } else if (setting.sysInterface !== 'true') {
          param.rduri = setting.interface
        }
      }
 
      if (setting.outerFunc) {
        param.func = setting.outerFunc
      }
    }
 
    param[setting.primaryKey] = primaryId
 
    return param
  }
 
  /**
   * @description 按钮操作完成后(成功或失败),页面刷新,重置页码及选择项
   */
  refreshbyaction = (btn, type, primaryId, formdata) => {
    const { BIDs } = this.state
 
    if (type === 'success' && btn.afterExecSuccess === 'notclose') {
      this.setState({
        primaryId: primaryId
      }, () => {
        if (btn.execSuccess === 'refresh') {
          this.loadmaindata()
        } else {
          let data = {}
 
          if (formdata && formdata.length > 0) {
            formdata.forEach(item => {
              data[item.key] = item.value
            })
          }
 
          this.setState({
            BIDs: {
              ...BIDs,
              mainTable: primaryId,
              mainTabledata: data
            }
          })
        }
      })
    } else if (type === 'success' && btn.afterExecSuccess === 'close') {
      if (this.props.refresh) {
        this.props.refresh(btn.execSuccess)
      } else {
        if (btn.execSuccess !== 'never') {
          let PMenu = {
            MenuID: this.props.param.parentId || '',
            position: btn.execSuccess
          }
          this.props.refreshTabView(PMenu)
        }
 
        let tabs = this.props.tabviews.filter(tab => {
          tab.selected = false
          if (tab.MenuID === this.props.param.parentId) {
            tab.selected = true
          }
 
          return tab.MenuID !== this.props.MenuID
        })
 
        this.props.modifyTabview(tabs)
      }
    } else if (type === 'error' && btn.afterExecError === 'notclose') {
      if (btn.execError === 'refresh') {
        this.loadmaindata()
      }
    } else if (type === 'error' && btn.afterExecError === 'close') {
      if (this.props.refresh) {
        this.props.refresh(btn.execError)
      } else {
        if (btn.execError !== 'never') {
          let PMenu = {
            MenuID: this.props.param.parentId || '',
            position: btn.execError
          }
          this.props.refreshTabView(PMenu)
        }
 
        let tabs = this.props.tabviews.filter(tab => {
          tab.selected = false
          if (tab.MenuID === this.props.param.parentId) {
            tab.selected = true
          }
 
          return tab.MenuID !== this.props.MenuID
        })
 
        this.props.modifyTabview(tabs)
      }
    }
  }
 
  /**
   * @description 表格Id变化
   */
  handleTableId = (type, id, data) => {
    const { BIDs } = this.state
 
    this.setState({
      BIDs: {
        ...BIDs,
        [type]: id,
        [type + 'data']: data
      }
    })
  }
 
  /**
   * @description 子表操作完成后刷新主表
   */
  handleMainTable = (type, tab) => {
    if ((type === 'maingrid' || type === 'mainline') && tab.supMenu === 'mainTable') {
      this.loadmaindata()
    } else if ((type === 'maingrid' || type === 'mainline') && tab.supMenu) {
      this.setState({
        refreshtabs: [type, tab.supMenu]
      }, () => {
        this.setState({
          refreshtabs: null
        })
      })
    } else if (type === 'equaltab' && tab.equalTab && tab.equalTab.length > 0) {
      this.setState({
        refreshtabs: tab.equalTab
      }, () => {
        this.setState({
          refreshtabs: null
        })
      })
    }
  }
 
  /**
   * @description 获取表单参数
   */
  getFormData = () => {
    return this.formGroupRef.handleConfirm()
  }
 
  reloadview = () => {
    this.setState({
      loadingview: true,
      viewlost: false,
      lostmsg: '',
      config: {},
      groups: null,
      actions: null,
      arr_field: '',
      setting: null,
      data: null,
      configMap: {},
      BIDs: {},
      setsingle: false,
      pickup: false,
      popData: false,
      visible: false,
      primaryId: null,
      refreshtabs: null
    }, () => {
      this.loadconfig()
    })
  }
 
  UNSAFE_componentWillMount () {
    // 组件加载时,获取菜单数据
    this.loadconfig()
  }
 
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.refreshTab && nextProps.refreshTab.MenuID === this.props.MenuID) {
      this.reloadview()
      this.props.refreshTabView('')
    }
  }
 
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
 
  /**
   * @description 组件销毁,清除state更新
   */
  componentWillUnmount () {
    this.setState = () => {
      return
    }
  }
 
  render() {
    const { setting, actions, loadingview, viewlost, config, groups, data } = this.state
    let hasform = false
 
    if (groups && (groups.length > 1 || groups[0].sublist.length > 0)) {
      hasform = true
    }
 
    return (
      <div className="formtab" id={this.state.ContainerId}>
        {loadingview && <Spin size="large" />}
        {hasform ?
          <FormGroup
            dict={this.state.dict}
            data={data}
            groups={groups}
            setting={setting}
            wrappedComponentRef={(inst) => this.formGroupRef = inst}
          /> : null
        }
        {hasform ?
          <FormAction
            menuType={this.props.menuType}
            logcolumns={[]}
            setting={setting}
            actions={actions}
            dict={this.state.dict}
            data={this.state.data}
            MenuID={this.props.MenuID}
            primaryId={this.state.primaryId}
            getFormData={this.getFormData}
            refreshdata={this.refreshbyaction}
          /> : null
        }
        {!loadingview && !viewlost && config.tabgroups.map(group => {
            if (group.sublist.length === 0) return null
 
            return (
              <Tabs defaultActiveKey="0" key={group.uuid}>
                {group.sublist.map((_tab, index) => {
                  return (
                    <TabPane tab={
                      <span>
                        {_tab.icon ? <Icon type={_tab.icon} /> : null}
                        {_tab.label}
                      </span>
                    } key={`${index}`}>
                      {_tab.type === 'SubTable' ?
                        <SubTable
                          Tab={_tab}
                          MenuID={_tab.linkTab}
                          SupMenuID={this.props.MenuID}
                          refreshtabs={this.state.refreshtabs}
                          ContainerId={this.state.ContainerId}
                          BID={this.state.BIDs[_tab.supMenu] || ''}
                          BData={this.state.BIDs[_tab.supMenu + 'data'] || ''}
                          handleTableId={this.handleTableId}
                          handleMainTable={(type) => this.handleMainTable(type, _tab)}
                        /> : null}
                    </TabPane>
                  )
                })}
              </Tabs>
            )
          })
        }
        {viewlost ? <NotFount msg={this.state.lostmsg} /> : null}
      </div>
    )
  }
}
 
const mapStateToProps = (state) => {
  return {
    menuType: state.editLevel,
    tabviews: state.tabviews,
    refreshTab: state.refreshTab,
    permAction: state.permAction,
    dataManager: state.dataManager,
    permRoles: state.permRoles
  }
}
 
const mapDispatchToProps = (dispatch) => {
  return {
    refreshTabView: (refreshTab) => dispatch(refreshTabView(refreshTab)),
    modifyTabview: (tabviews) => dispatch(modifyTabview(tabviews))
  }
}
 
export default connect(mapStateToProps, mapDispatchToProps)(NormalTable)