king
2020-03-26 f7d1f17bdcb8c3e794a798165737bb7529dbe8ca
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
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, Switch, Modal, Button, message, Tree, Typography } 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 asyncLoadComponent from '@/utils/asyncLoadComponent'
import {refreshTabView, modifyTabview} from '@/store/action'
 
import MainTable from '@/tabviews/zshare/normalTable'
import MainSearch from '@/tabviews/zshare/topSearch'
import NotFount from '@/components/404'
import './index.scss'
 
const VerifyCard = asyncLoadComponent(() => import('@/tabviews/zshare/verifycard'))
const MainAction = asyncLoadComponent(() => import('@/tabviews/zshare/actionList'))
const SubTable = asyncLoadComponent(() => import('@/tabviews/subtable'))
const SubTabTable = asyncLoadComponent(() => import('@/tabviews/subtabtable'))
const FormTab = asyncLoadComponent(() => import('@/tabviews/formtab'))
 
const { TabPane } = Tabs
const { TreeNode } = Tree
const { Paragraph } = Typography
 
class NormalTable extends Component {
  static propTpyes = {
    MenuNo: PropTypes.string,    // 菜单参数
    MenuName: PropTypes.string,  // 菜单参数
    MenuID: PropTypes.string     // 菜单Id
  }
 
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    ContainerId: Utils.getuuid(), // 菜单外层html Id
    view: 'commontable',  // 当前页面默认为主表
    loadingview: true,    // 页面加载中
    viewlost: false,      // 页面丢失:1、未获取到配置-页面丢失;2、页面未启用
    lostmsg: '',          // 页面丢失时的提示信息
    config: {},           // 页面配置信息,包括按钮、搜索、显示列、标签等
    userConfig: null,     // 用户自定义设置
    userParam: null,      // 保存用户编辑中的配置
    searchlist: null,     // 搜索条件
    actions: null,        // 按钮集
    columns: null,        // 显示列
    logcolumns: null,     // 日志中显示的列信息 (增加至全部列,除去合并列)
    arr_field: '',        // 使用 sPC_Get_TableData 时的查询字段集
    setting: null,        // 页面全局设置:数据源、按钮及显示列固定、主键等
    data: null,           // 列表数据集
    total: 0,             // 总数
    loading: false,       // 列表数据加载中
    pageIndex: 1,         // 页码
    pageSize: 10,         // 每页数据条数
    orderBy: '',          // 排序
    search: '',           // 搜索条件数组,使用时需分场景处理
    BIDs: {},             // 上级表id
    pickup: false,        // 主表数据隐藏显示切换
    popAction: false,     // 弹框页面,按钮信息
    popData: false,       // 弹框页面,所选的表格数据
    visible: false,       // 弹框显示隐藏控制
    treevisible: false,   // 菜单结构树弹框显示隐藏控制
    tabBtn: null,         // 表单标签按钮
    tabParam: null,       // 表单标签参数
    refreshtabs: null,    // 需要刷新的标签集
    confirmLoading: false,// 自定义设置模态框加载中
    settingVisible: false,// 自定义设置模态框
    triggerBtn: null      // 点击表格中或快捷键触发的按钮
  }
 
  /**
   * @description 获取页面配置信息
   */
  async loadconfig () {
    const { permAction } = this.props
 
    let param = {
      func: 'sPC_Get_LongParam',
      MenuID: this.props.MenuID
    }
    let result = await Api.getSystemCacheConfig(param)
 
    if (result.status) {
      let config = ''
      let userConfig = null
      let _curUserConfig = ''
 
      try { // 配置信息解析
        config = JSON.parse(window.decodeURIComponent(window.atob(result.LongParam)))
      } catch (e) {
        console.warn('Parse Failure')
        config = ''
      }
      
      if (result.LongParamUser) {
        try { // 配置信息解析
          userConfig = JSON.parse(window.decodeURIComponent(window.atob(result.LongParamUser)))
          _curUserConfig = userConfig[this.props.MenuID]
        } catch (e) {
          console.warn('Parse Failure')
          userConfig = null
        }
      }
 
      // 页面配置解析错误时提示
      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
      }
 
      // 权限过滤
      config.action = config.action.filter(item => permAction[item.uuid])
      config.tabgroups.forEach(group => {
        if (!config[group]) return
 
        config[group] = config[group].filter(tab => permAction[tab.linkTab])
      })
 
      // 字段权限黑名单
      config.search = config.search.filter(item => {
        if (!item.blacklist || item.blacklist.length === 0) return true
 
        let _black = item.blacklist.filter(v => {
          return this.props.permRoles.indexOf(v) !== -1
        })
 
        if (_black.length > 0) {
          return false
        } else {
          return true
        }
      })
 
      config.columns = config.columns.filter(col => {
        if (!col.field || !col.blacklist || col.blacklist.length === 0 || config.setting.primaryKey === col.field) return true
 
        let _black = col.blacklist.filter(v => {
          return this.props.permRoles.indexOf(v) !== -1
        })
 
        if (_black.length > 0) {
          return false
        } else {
          return true
        }
      })
 
      if (_curUserConfig) {
        config.setting = {...config.setting, ..._curUserConfig.setting}
 
        config.action = config.action.map(item => {
          if (item.execMode) {
            item.OpenType = 'funcbutton'
          }
 
          if (_curUserConfig.action[item.uuid]) {
            item = {...item, ..._curUserConfig.action[item.uuid]}
          }
          
          if (item.OpenType === 'funcbutton' && item.funcType === 'print' && item.verify && item.printer) {
            item.verify.defaultPrinter = item.printer.defaultPrinter || ''
            if (item.verify.printerTypeList && item.printer.printerList) {
              item.verify.printerTypeList = item.verify.printerTypeList.map(cell => {
                cell.printer = item.printer.printerList[cell.Value] || ''
 
                return cell
              })
            }
          }
 
          return item
        })
      }
 
      let _arrField = []     // 字段集
      let _columns = []      // 显示列
      let _logcolumns = []   // 日志显示列
      let _hideCol = []      // 隐藏及合并列中字段的uuid集
      let colMap = new Map() // 用于字段过滤
 
      let _actions = []      // 工具栏按钮
      let _operations = []   // 操作列按钮(存在时)
 
      config.action.forEach(item => {
        if (item.execMode) {
          item.OpenType = 'funcbutton'
        }
 
        if (item.position === 'toolbar') {
          _actions.push(item)
        } else if (item.position === 'grid') {
          _operations.push(item)
        }
      })
 
      if (config.gridBtn && config.gridBtn.display && _operations.length > 0) {
        _columns.push({
          ...config.gridBtn,
          operations: _operations
        })
      }
 
      // 1、筛选字段集,2、过滤隐藏列及合并列中的字段uuid
      config.columns.forEach(col => {
        if (col.field) {
          _arrField.push(col.field)
 
          _logcolumns.push(col)
        }
        if (col.type === 'colspan' && col.sublist) { // 筛选隐藏列
          _hideCol = _hideCol.concat(col.sublist)
        } else if (col.Hide === 'true') {
          _hideCol.push(col.uuid)
        }
        colMap.set(col.uuid, col)
      })
 
      // 生成显示列,处理合并列中的字段
      config.columns.forEach(col => {
        if (_hideCol.includes(col.uuid)) return
 
        if (col.type === 'colspan' && col.sublist) {
          let _col = JSON.parse(JSON.stringify(col))
          let subColumn = []
          _col.sublist.forEach(sub => {
            if (colMap.has(sub)) {
              subColumn.push(colMap.get(sub))
            }
          })
          _col.subColumn = subColumn
          _columns.push(_col)
        } else {
          _columns.push(col)
        }
      })
 
      let valid = true // 搜索条件必填验证
      config.search.forEach(field => {
        if (field.required === 'true' && !field.initval) {
          valid = false
        }
      })
 
      if (_curUserConfig) {
        _columns = _columns.map(item => {
          if (_curUserConfig.columns[item.uuid]) {
            item = {...item, ..._curUserConfig.columns[item.uuid]}
          }
 
          return item
        })
 
        _columns.sort((pre, next) => {
          return pre.sort - next.sort
        })
      }
 
      this.setState({
        loadingview: false,
        config: config,
        userConfig: userConfig,
        setting: config.setting,
        searchlist: config.search,
        actions: _actions,
        columns: _columns,
        logcolumns: _logcolumns,
        arr_field: _arrField.join(','),
        search: Utils.initMainSearch(config.search) // 搜索条件初始化(含有时间格式,需要转化)
      }, () => {
        this.improveSearch()
        if (config.setting.onload !== 'false' && valid) { // 初始化可加载
          this.loadmaindata()
        }
        this.setShortcut()
      })
    } else {
      this.setState({
        loadingview: false,
        viewlost: true
      })
      notification.warning({
        top: 92,
        message: result.message,
        duration: 10
      })
    }
  }
 
  setShortcut = () => {
    const { actions, userConfig } = this.state
    if (!userConfig) return
 
    document.onkeydown = (event) => {
      let e = event || window.event
      let keyCode = e.keyCode || e.which || e.charCode
      let preKey = ''
 
      if (e.ctrlKey) {
        preKey = 'ctrl'
      } else if (e.shiftKey) {
        preKey = 'shift'
      } else if (e.altKey) {
        preKey = 'alt'
      }
 
      if (!preKey) return
 
      let istrigger = false
 
      actions.forEach(item => {
        if (!item.shortcut || typeof(item.shortcut) !== 'object' || item.shortcut.length === 0 || istrigger) return
 
        if (preKey === item.shortcut[0] && keyCode === item.shortcut[1]) {
          e.preventDefault()
          istrigger = true
 
          this.setState({
            triggerBtn: {
              uuid: new Date().getTime(),
              parentId: this.props.MenuID,
              button: item,
              data: null
            }
          })
        }
      })
 
      if (istrigger) return
 
      Object.keys(userConfig).forEach(key => {
        if (key === this.props.MenuID || !userConfig[key].action || istrigger) return
 
        let _actions = userConfig[key].action
 
        Object.keys(_actions).forEach(btnkey => {
          let item = _actions[btnkey]
 
          if (!item.shortcut || typeof(item.shortcut) !== 'object' || item.shortcut.length === 0 || istrigger) return
 
          if (preKey === item.shortcut[0] && keyCode === item.shortcut[1]) {
            e.preventDefault()
            istrigger = true
 
            this.setState({
              triggerBtn: {
                uuid: new Date().getTime(),
                parentId: key,
                button: {...item, uuid: btnkey},
                data: null
              }
            })
          }
        })
      })
    }
  }
 
  /**
   * @description 搜索条件下拉选项预加载
   */
  improveSearch = () => {
    let searchlist = JSON.parse(JSON.stringify(this.state.searchlist))
    let deffers = []
    searchlist.forEach(item => {
      if (item.type !== 'multiselect' && item.type !== 'select' && item.type !== 'link') return
      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
        }
 
        param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
        param.secretkey = Utils.encrypt(param.LText, param.timestamp)
 
        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: 10
        })
      }
    })
 
    if (deffers.length === 0) {
      this.setState({searchlist: JSON.parse(JSON.stringify(searchlist))})
      return
    }
 
    Promise.all(deffers).then(result => {
      result.forEach(res => {
        if (res.status) {
          searchlist = searchlist.map(item => {
            if (item.uuid === res.search.uuid) {
              res.data.forEach(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]
                }
 
                item.options.push(_item)
              })
            }
            return item
          })
        } else {
          notification.warning({
            top: 92,
            message: res.search.label + ':' + res.message,
            duration: 10
          })
        }
      })
 
      this.setState({searchlist})
    })
  }
 
  /**
   * @description 主表数据加载
   */ 
  async loadmaindata () {
    const { setting, BIDs, search } = this.state
    let param = ''
 
    let requireFields = search.filter(item => item.required && !item.value)
 
    if (requireFields.length > 0) {
      notification.warning({
        top: 92,
        message: this.state.dict['form.required.input'] + requireFields.map(item => item.label).join('、') + ' !',
        duration: 3
      })
      return
    }
 
    this.setState({
      loading: true
    })
 
    if (setting.interType !== 'inner' || (setting.interType === 'inner' && setting.innerFunc)) {
      param = this.getCustomParam()
    } else {
      param = this.getDefaultParam()
    }
 
    this.handleTableId('mainTable', '', '')
 
    if (!param) { // 未获取参数时,不发请求
      return
    }
 
    let result = await Api.genericInterface(param)
    if (result.status) {
      this.setState({
        data: result.data.map((item, index) => {
          item.key = index
          return item
        }),
        total: result.total,
        loading: false,
        pickup: false,
        BIDs: {
          ...BIDs,
          mainTable: ''
        }
      })
    } else {
      this.setState({
        loading: false
      })
      notification.error({
        top: 92,
        message: result.message,
        duration: 15
      })
    }
  }
 
  /**
   * @description 获取用户自定义存储过程传参
   */
  getCustomParam = () => {
    const { pageIndex, pageSize, orderBy, search, setting } = this.state
 
    let _search = Utils.formatCustomMainSearch(search)
 
    let param = {
      PageIndex: pageIndex,
      PageSize: pageSize,
      OrderCol: orderBy || setting.order,
      ..._search
    }
 
    if (setting.interType === 'inner') {
      param.func = setting.innerFunc
    } else {
      if (setting.sysInterface === 'true') {
        param.rduri = window.GLOB.mainSystemApi || window.GLOB.subSystemApi
      } else {
        param.rduri = setting.interface
      }
 
      param.appkey = window.GLOB.appkey || '' // 调用外部接口增加appkey
 
      if (setting.outerFunc) {
        param.func = setting.outerFunc
      }
    }
 
    return param
  }
 
  /**
   * @description 获取系统存储过程 sPC_Get_TableData 的参数
   */
  getDefaultParam = () => {
    const { arr_field, pageIndex, pageSize, orderBy, search, setting } = this.state
 
    if (!arr_field) {
      notification.warning({
        top: 92,
        message: '未设置显示列!',
        duration: 10
      })
      return null
    }
 
    let _search = Utils.joinMainSearchkey(search)
 
    _search = _search ? 'where ' + _search : ''
    
    let param = {
      func: 'sPC_Get_TableData',
      obj_name: 'data',
      arr_field: arr_field,
      appkey: window.GLOB.appkey || ''
    }
    
    let _orderBy = orderBy || setting.order
    let _dataresource = setting.dataresource
 
    if (/\s/.test(_dataresource)) {
      _dataresource = '(' + _dataresource + ') tb'
    }
 
    if (setting.queryType === 'statistics') { // 统计数据源,内容替换
      let fieldmap = new Map()
      let options = search.map(item => {
        let _field = item.key
 
        if (fieldmap.has(_field)) {
          _field = _field + '1'
        }
 
        fieldmap.set(item.key, true)
 
        return {
          reg: new RegExp('@' + _field, 'ig'),
          value: item.value
        }
      })
 
      options.reverse()
 
      options.forEach(item => {
        _dataresource = _dataresource.replace(item.reg, `'${item.value}'`)
      })
 
      _search = ''
    }
 
    let LText = `select top ${pageSize} ${arr_field} from (select ${arr_field} ,ROW_NUMBER() over(order by ${_orderBy}) as rows from ${_dataresource} ${_search}) tmptable where rows > ${pageSize * (pageIndex - 1)} order by tmptable.rows`
    let DateCount = `select count(1) as total from ${_dataresource} ${_search}`
 
    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 = Utils.formatOptions(DateCount)
 
    return param
  }
 
  /**
   * @description 搜索条件改变时,重置表格数据
   * 含有初始不加载的页面,修改设置
   */
  refreshbysearch = (searches) => {
    const { setting } = this.state
 
    if (setting.onload === 'false') {
      this.setState({
        pageIndex: 1,
        search: searches,
        setting: {...setting, onload: 'true'}
      }, () => {
        this.loadmaindata()
      })
    } else {
      this.refs.mainTable.resetTable()
 
      this.setState({
        pageIndex: 1,
        search: searches
      }, () => {
        this.loadmaindata()
      })
    }
  }
 
  /**
   * @description 表格条件改变时重置数据(分页或排序)
   */
  refreshbytable = (pagination, filters, sorter) => {
    if (sorter.order) {
      let _chg = {
        ascend: 'asc',
        descend: 'desc'
      }
      sorter.order = _chg[sorter.order]
    }
 
    this.setState({
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      orderBy: (sorter.field && sorter.order) ? `${sorter.field} ${sorter.order}` : ''
    }, () => {
      this.loadmaindata()
    })
  }
 
  /**
   * @description 表格刷新
   */
  reloadtable = () => {
    this.refs.mainTable.resetTable()
    this.setState({
      pageIndex: 1
    }, () => {
      this.loadmaindata()
    })
  }
 
  /**
   * @description 页面刷新,重新获取配置
   */
  reloadview = () => {
    this.setState({
      view: 'commontable',
      loadingview: true,
      viewlost: false,
      lostmsg: '',
      config: {},
      userConfig: null,
      userParam: null,
      searchlist: null,
      actions: null,
      columns: null,
      arr_field: '',
      setting: null,
      data: null,
      total: 0,
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      orderBy: '',
      search: '',
      BIDs: {},
      pickup: false
    }, () => {
      this.loadconfig()
    })
  }
 
  /**
   * @description 按钮操作完成后(成功或失败),页面刷新,重置页码及选择项
   */
  refreshbyaction = (btn, type) => {
    if (btn.execSuccess === 'grid' && type === 'success') {
      this.reloadtable()
    } else if (btn.execError === 'grid' && type === 'error') {
      this.reloadtable()
    } else if (btn.execSuccess === 'view' && type === 'success') {
      this.reloadview()
    } else if (btn.execError === 'view' && type === 'error') {
      this.reloadview()
    } else if (btn.popClose === 'view' && type === 'pop') {
      this.reloadview()
    } else if (btn.popClose === 'grid' && type === 'pop') {
      this.reloadtable()
    }
  }
 
  /**
   * @description 表单操作完成后刷新主页面
   */
  refreshbyformtab = (type) => {
    this.setState({
      view: 'commontable',
      tabBtn: null,
      tabParam: null
    }, () => {
      if (type === 'grid') {
        this.reloadtable()
      } else if (type === 'view') {
        this.reloadview()
      }
    })
  }
 
  /**
   * @description 子表操作完成后刷新主表
   */
  handleMainTable = (type, tab) => {
    if (type === 'maingrid' && tab.supMenu === 'mainTable') {
      this.reloadtable()
    } else if (type === 'maingrid' && tab.supMenu) {
      this.setState({
        refreshtabs: [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 导出Excel时,获取页面搜索排序等参数
   */
  getexceloutparam = () => {
    const { MenuName } = this.props
    const { arr_field, orderBy, search, setting} = this.state
 
    return {
      arr_field: arr_field,
      orderBy: orderBy || setting.order,
      search: search,
      menuName: MenuName
    }
  }
 
  /**
   * @description 获取表格选择项
   */
  gettableselected = () => {
    let data = []
    this.refs.mainTable.state.selectedRowKeys.forEach(item => {
      data.push(this.refs.mainTable.props.data[item])
    })
    return data
  }
 
  /**
   * @description 表格中,按钮触发事件传递
   */
  buttonTrigger = (btn, record) => {
    this.setState({
      triggerBtn: {
        uuid: new Date().getTime(),
        parentId: this.props.MenuID,
        button: btn,
        data: record
      }
    })
  }
 
  /**
   * @description 表格Id变化
   */
  handleTableId = (type, id, data) => {
    const { BIDs } = this.state
 
    this.setState({
      BIDs: {
        ...BIDs,
        [type]: id,
        [type + 'data']: data
      }
    })
  }
  
  /**
   * @description 数据展开合并切换
   */
  pickupChange = () => {
    const { pickup } = this.state
    this.setState({
      pickup: !pickup
    })
  }
 
  /**
   * @description 触发按钮弹窗(标签页)
   */
  triggerPopview = (btn, data) => {
    const { setting } = this.state
 
    let _primaryId = ''
 
    if (data && data[0] && setting.primaryKey) {
      _primaryId = data[0][setting.primaryKey] || ''
    }
 
    if (btn.OpenType === 'popview') {
      this.setState({
        popAction: btn,
        popData: data[0] || null,
        visible: true
      })
    } else if (btn.OpenType === 'tab') {
      const { tabviews, MenuNo, MenuID } = this.props
      let newtab = {
        MenuNo: MenuNo,
        MenuID: btn.uuid,
        MenuName: btn.label,
        type: btn.tabTemplate,
        selected: true,
        param: {
          menuType: 'main',
          parentId: this.props.MenuID,
          btn: btn,
          data: data[0] || null,
          primaryId: btn.Ot !== 'notRequired' ? _primaryId : '',
          arr_field: this.state.arr_field
        }
      }
 
      let index = 0
      let isexit = false
      let tabs = tabviews.map((tab, i) => {
        tab.selected = false
 
        if (tab.MenuID === MenuID) {
          index = i
        } else if (tab.MenuID === btn.uuid) {
          tab.selected = true
          isexit = true
        }
 
        return tab
      })
 
      if (!isexit) {
        tabs.splice(index + 1, 0, newtab)
      }
 
      this.props.modifyTabview(tabs)
    } else if (btn.OpenType === 'blank') {
      this.setState({
        view: 'formtab',
        tabBtn: btn,
        tabParam: {
          menuType: 'main',
          btn: btn,
          data: data[0] || null,
          primaryId: btn.Ot !== 'notRequired' ? _primaryId : '',
          arr_field: this.state.arr_field
        }
      })
    }
  }
 
  popclose = () => {
    this.setState({
      visible: false
    })
    this.refreshbyaction(this.state.popAction, 'pop')
  }
 
  handleviewconfig = (e) => {
    e.stopPropagation()
 
    const { MenuNo } = this.props
    const { config } = this.state
 
    if (config && config.funcs && config.funcs.length > 0) {
      this.setState({
        treevisible: true
      })
    } else {
      let oInput = document.createElement('input')
      oInput.value = MenuNo || ''
      document.body.appendChild(oInput)
      oInput.select()
      document.execCommand('Copy')
      document.body.removeChild(oInput)
      message.success(this.state.dict['main.copy.success'])
    }
  }
 
  getTreeNode = (data) => {
    let _type = {
      view: '页面',
      btn: '按钮',
      tab: '标签'
    }
 
    return data.map(item => {
      let _title = _type[item.subtype]
      let _others = []
 
      _others.push(
        (item.menuNo ? item.menuNo + '(菜单参数)' : ''),
        (item.tableName ? item.tableName + '(表名) ' : ''),
        (item.innerFunc ? item.innerFunc + '(内部函数) ' : ''),
        (item.outerFunc ? item.outerFunc + '(外部函数)' : '')
      )
      _others = _others.filter(Boolean)
      _others = _others.join('、')
 
      if (item.label) {
        _title = _title + '(' + item.label + ')'
      }
      if (_others) {
        _title = _title + ': ' + _others
      }
 
      if (item.subfuncs && item.subfuncs.length > 0) {
        return (
          <TreeNode title={_title} key={item.uuid} dataRef={item} selectable={false}>
            {this.getTreeNode(item.subfuncs)}
          </TreeNode>
        )
      }
      return <TreeNode key={item.uuid} title={_title} isLeaf selectable={false} />
    })
  }
 
  controlCustomSetting = () => {
    this.setState({
      settingVisible: true,
      confirmLoading: false
    })
  }
 
  changeMenuParam = (param) => {
    this.setState({userParam: param})
  }
 
  settingSubmit = () => {
    const { userParam } = this.state
    let _LongParam = ''
 
    try {
      _LongParam = window.btoa(window.encodeURIComponent(JSON.stringify(userParam)))
    } catch (e) {
      notification.warning({
        top: 92,
        message: '编译错误',
        duration: 10
      })
      return
    }
 
    let param = {
      func: 'sPC_TrdMenu_UserParam',
      MenuID: this.props.MenuID,
      LongParam: _LongParam
    }
 
    this.setState({
      confirmLoading: true
    })
 
    Api.getSystemConfig(param).then(result => {
      if (!result.status) {
        this.setState({
          confirmLoading: false
        })
        notification.warning({
          top: 92,
          message: result.message,
          duration: 10
        })
        return
      }
      this.setState({
        settingVisible: false,
        confirmLoading: false
      }, () => {
        window.GLOB.CacheMap = new Map()
        this.reloadview()
      })
    })
  }
 
  UNSAFE_componentWillMount () {
    // 组件加载时,获取菜单数据
    this.loadconfig()
  }
 
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.refreshTab && nextProps.refreshTab.MenuID === this.props.MenuID) {
      if (nextProps.refreshTab.position === 'grid') {
        this.reloadtable()
      } else if (nextProps.refreshTab.position === 'view') {
        this.reloadview()
      }
      this.props.refreshTabView('')
    } else if (!is(fromJS(this.props.tabviews), fromJS(nextProps.tabviews))) {
      let selectTab = nextProps.tabviews.filter(tab => tab.selected)[0]
      if (selectTab && selectTab.MenuID === this.props.MenuID) {
        this.setShortcut()
      }
    }
  }
 
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
 
  /**
   * @description 组件销毁,清除state更新,清除快捷键设置
   */
  componentWillUnmount () {
    this.setState = () => {
      return
    }
    document.onkeydown = () => {}
  }
 
  render() {
    const { view, setting, searchlist, actions, columns, loadingview, viewlost, pickup, config, triggerBtn, userConfig } = this.state
 
    return (
      <div>
        {view === 'commontable' ? <div className="commontable pick-control" id={this.state.ContainerId}>
          {loadingview && <Spin size="large" />}
          {searchlist && searchlist.length > 0 ?
            <MainSearch
              ref="mainSearch"
              dict={this.state.dict}
              searchlist={searchlist}
              refreshdata={this.refreshbysearch}
            /> : null
          }
          {actions && setting.onload !== 'false' ?
            <div style={{minHeight: '25px'}}>
              <MainAction
                BID=""
                type="main"
                menuType="main"
                setting={setting}
                actions={actions}
                triggerBtn={triggerBtn}
                dict={this.state.dict}
                MenuID={this.props.MenuID}
                permRoles={this.props.permRoles}
                logcolumns={this.state.logcolumns}
                ContainerId={this.state.ContainerId}
                refreshdata={this.refreshbyaction}
                triggerPopview={this.triggerPopview}
                getexceloutparam={this.getexceloutparam}
                gettableselected={this.gettableselected}
              />
            </div> : null
          }
          {columns && setting.onload !== 'false' ?
            <div className="main-table-box">
              <Icon className="custom-control" type="setting" onClick={this.controlCustomSetting} />
              {this.state.data && this.state.data.length > 0 ?
                <Switch title="收起" className="main-pickup" checkedChildren="开" unCheckedChildren="关" defaultChecked={pickup} onChange={this.pickupChange} /> : null
              }
              <MainTable
                ref="mainTable"
                tableId="mainTable"
                pickup={pickup}
                setting={setting}
                columns={columns}
                dict={this.state.dict}
                data={this.state.data}
                total={this.state.total}
                MenuID={this.props.MenuID}
                loading={this.state.loading}
                refreshdata={this.refreshbytable}
                buttonTrigger={this.buttonTrigger}
                handleTableId={this.handleTableId}
              />
            </div> : null
          }
          {setting && setting.onload !== 'false' &&
            config.tabgroups.map(group => {
              if (config[group].length === 0) return null
 
              return (
                <Tabs defaultActiveKey="0" key={group}>
                  {config[group].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}
                            menuType="main"
                            MenuID={_tab.linkTab}
                            userConfig={userConfig ? userConfig[_tab.linkTab] : null}
                            triggerBtn={triggerBtn}
                            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>
              )
            })
          }
          <Button
            icon="copy"
            shape="circle"
            className="common-table-copy"
            onClick={this.handleviewconfig}
          />
          <Modal
            className="popview-modal"
            title={this.state.popAction.label}
            width={'80vw'}
            maskClosable={false}
            visible={this.state.visible}
            onCancel={this.popclose}
            footer={[
              <Button key="close" onClick={this.popclose}>{this.state.dict['main.close']}</Button>
            ]}
            destroyOnClose
          >
            {<SubTabTable 
              BID={''}
              menuType="main"
              SupMenuID={this.props.MenuID}
              MenuID={this.state.popAction.linkTab}
              BData={this.state.BIDs['mainTabledata'] || ''}
              ContainerId={this.state.ContainerId}
              ID={this.state.popData ? this.state.popData[setting.primaryKey] : ''}
              refreshSupView={this.reloadtable}
            />}
          </Modal>
          <Modal
            className="menu-tree-modal"
            title={'菜单结构树'}
            width={'650px'}
            maskClosable={false}
            visible={this.state.treevisible}
            onCancel={() => this.setState({treevisible: false})}
            footer={[
              <Button key="close" onClick={() => this.setState({treevisible: false})}>{this.state.dict['main.close']}</Button>
            ]}
            destroyOnClose
          >
            <div className="menu-header">
              <span>菜单名称:{this.props.MenuName}</span>
              <span>菜单参数:{<Paragraph copyable>{this.props.MenuNo}</Paragraph>}</span>
            </div>
            {this.state.treevisible ? <Tree defaultExpandAll showLine={true}>
              {this.getTreeNode(config.funcs)}
            </Tree> : null}
          </Modal>
          {/* 按钮使用系统存储过程时,验证信息模态框 */}
          <Modal
            wrapClassName="common-table-custom-modal"
            title={'自定义设置'}
            maskClosable={false}
            width={950}
            visible={this.state.settingVisible}
            onOk={this.settingSubmit}
            onCancel={() => { this.setState({ settingVisible: false }) }}
            confirmLoading={this.state.confirmLoading}
            destroyOnClose
          >
            {this.state.settingVisible ?
              <VerifyCard
                MenuID={this.props.MenuID}
                MenuName={this.props.MenuName}
                permAction={this.props.permAction}
                permRoles={this.props.permRoles}
                config={this.state.config}
                userConfig={this.state.userConfig}
                columns={this.state.columns}
                handleParam={this.changeMenuParam}
              /> : null
            }
          </Modal>
          {viewlost ? <NotFount msg={this.state.lostmsg} /> : null}
        </div> : null}
        {view === 'formtab' ? <FormTab MenuID={this.state.tabBtn.uuid} param={this.state.tabParam} refresh={this.refreshbyformtab}/> : null}
      </div>
    )
  }
}
 
const mapStateToProps = (state) => {
  return {
    tabviews: state.tabviews,
    refreshTab: state.refreshTab,
    permAction: state.permAction,
    permRoles: state.permRoles
  }
}
 
const mapDispatchToProps = (dispatch) => {
  return {
    refreshTabView: (refreshTab) => dispatch(refreshTabView(refreshTab)),
    modifyTabview: (tabviews) => dispatch(modifyTabview(tabviews))
  }
}
 
export default connect(mapStateToProps, mapDispatchToProps)(NormalTable)