king
2022-04-26 5046d0d13dc6a8563b8e54e31913bc44cfa1072f
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
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import { DndProvider } from 'react-dnd'
import HTML5Backend from 'react-dnd-html5-backend'
import moment from 'moment'
import { Button, Card, Modal, Collapse, notification, Spin, Select, List, Empty, Switch, Tooltip } from 'antd'
import { QuestionCircleOutlined, CloseOutlined, RedoOutlined, SettingOutlined, PlusOutlined, DeleteOutlined, EditOutlined, SnippetsOutlined } from '@ant-design/icons'
 
import Api from '@/api'
import zhCN from '@/locales/zh-CN/model.js'
import enUS from '@/locales/en-US/model.js'
import Utils, { FuncUtils } from '@/utils/utils.js'
import { getModalForm, getActionForm } from '@/templates/zshare/formconfig'
import { queryTableSql } from '@/utils/option.js'
 
import TabsComponent from '@/templates/sharecomponent/tabscomponent'
 
import PasteForm from '@/templates/zshare/pasteform'
import ActionForm from './actionform'
import SettingForm from './settingform'
import DragElement from './dragelement'
import GroupForm from './groupform'
import EditCard from '@/templates/zshare/editcard'
 
import MenuForm from '@/templates/zshare/menuform'
import SourceElement from '@/templates/zshare/dragsource'
import asyncComponent from '@/utils/asyncComponent'
import Source from './source'
import './index.scss'
 
const { Panel } = Collapse
const { Option } = Select
const { confirm } = Modal
const ModalForm = asyncComponent(() => import('@/templates/zshare/modalform'))
const CreateFunc = asyncComponent(() => import('@/templates/zshare/createfunc'))
const VerifyCard = asyncComponent(() => import('@/templates/zshare/verifycard'))
 
class ComTableConfig extends Component {
  static propTpyes = {
    menu: PropTypes.any,
    btnTab: PropTypes.object,
    config: PropTypes.any,
    handleView: PropTypes.func
  }
 
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,        // 字典
    config: null,            // 页面配置
    modaltype: '',           // 模态框类型,控制模态框显示
    tableVisible: false,     // 数据表字段模态框
    tableColumns: [],        // 表格显示列
    fields: null,            // 搜索条件及显示列,可选字段
    menuformlist: null,      // 基本信息表单字段
    formlist: null,          // 搜索条件、按钮、显示列表单字段
    card: null,              // 编辑元素
    menuloading: false,      // 菜单保存中
    menucloseloading: false, // 菜单关闭时,选择保存
    loading: false,          // 加载中,页面spin
    settingVisible: false,   // 全局配置模态框
    closeVisible: false,     // 关闭模态框
    tables: [],              // 可用表名
    selectedTables: [],      // 已选表名
    originMenu: null,        // 原始菜单
    delActions: [],          // 删除按钮列表
    tabviews: [],            // 所有标签页
    profileVisible: false,   // 验证信息模态框
    editgroup: null,         // 当前编辑组
    groupVisible: false,     // 编辑组模态框
    activeKey: '0',          // 默认展开基本信息
    pasteVisible: false,     // 粘贴模态框
    sqlVerifing: false,      // sql验证
    openEdition: ''          // 编辑版本标记,防止多人操作
  }
 
  /**
   * @description 数据预处理
   * 1、设置页面配置信息,新建或无配置信息时(切换模板后无配置信息),使用模板默认配置
   * 2、设置操作类型、原始菜单信息(每次保存后重置)、已使用表及基本信息表单
   */
  UNSAFE_componentWillMount () {
    const { menu, btnTab, config } = this.props
 
    let _config = ''
    let columns = []
 
    if (!config) {
      _config = JSON.parse(JSON.stringify(Source.baseConfig))
      _config.isAdd = true
      if (menu && menu.LongParam && menu.LongParam.setting) {
        _config.setting.tableName = menu.LongParam.setting.tableName
        _config.setting.primaryKey = menu.LongParam.setting.primaryKey
        _config.setting.dataresource = menu.LongParam.setting.dataresource
        _config.setting.interType = menu.LongParam.setting.interType
        _config.setting.interface = menu.LongParam.setting.interface
        _config.setting.outerFunc = menu.LongParam.setting.outerFunc
        _config.setting.innerFunc = menu.LongParam.setting.innerFunc
        _config.setting.sysInterface = menu.LongParam.setting.sysInterface
      }
    } else {
      _config = config
 
      if (menu && menu.LongParam && menu.LongParam.setting) {
        _config.setting.primaryKey = menu.LongParam.setting.primaryKey
      }
    }
 
    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 (menu && menu.LongParam && menu.LongParam.columns) {
      columns = menu.LongParam.columns
    }
 
    // 配置默认值,兼容
    _config.Template = 'FormTab'
    _config.action = _config.action.map(item => {
      if (item.intertype === 'inner' && !item.innerFunc) {
        item.intertype = 'system'
      }
      return item
    })
 
    this.setState({
      config: _config,
      activeKey: btnTab.activeKey || '0',
      openEdition: btnTab.open_edition || '',
      columns: columns,
      originMenu: JSON.parse(JSON.stringify(_config)),
      selectedTables: _config.tables,
      menuformlist: [
        {
          type: 'text',
          key: 'menuName',
          label: this.state.dict['model.menu'] + this.state.dict['model.name'],
          initVal: menu.MenuName,
          readonly: true
        },
        {
          type: 'text',
          key: 'actionName',
          label: '按钮名称',
          initVal: btnTab.label,
          readonly: true
        }
      ]
    })
  }
 
  /**
   * @description 加载完成后
   * 1、获取系统可使用表
   * 2、根据配置信息中已使用表获取相关字段信息
   * 3、获取所有标签页信息
   */
  componentDidMount () {
    let param = {
      func: 'sPC_Get_SelectedList',
      LText: queryTableSql,
      obj_name: 'data',
      arr_field: 'TbName,Remark'
    }
 
    param.LText = Utils.formatOptions(param.LText)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt(param.LText, param.timestamp)
 
    param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp) // 云端数据验证
 
    Api.getSystemConfig(param).then(res => {
      if (res.status) {
        this.setState({
          tables: res.data
        })
      } else {
        notification.warning({
          top: 92,
          message: res.message,
          duration: 5
        })
      }
    })
 
    let deffers = this.state.selectedTables.map(item => {
      return new Promise(resolve => {
        Api.getSystemConfig({func: 'sPC_Get_FieldName', TBName: item.TbName}).then(res => {
          res.TBName = item.TbName
          resolve(res)
        })
      })
    })
    Promise.all(deffers).then(response => {
      let _columns = []
      response.forEach(res => {
        if (res.status) {
          let tabmsg = {
            tableName: res.TBName,
            columns: res.FDName.map(item => {
              let _type = item.FieldType.toLowerCase()
              let _decimal = 0
              if (/^nvarchar/.test(_type)) {
                _type = 'text'
              } else if (/^int/.test(_type)) {
                _type = 'number'
              } else if (/^decimal/.test(_type)) {
                _decimal = _type.split(',')[1]
                _decimal = parseInt(_decimal)
                if (_decimal > 4) {
                  _decimal = 4
                }
                _type = 'number'
              } else if (/^decimal/.test(_type)) {
                _decimal = _type.split(',')[1]
                _decimal = parseInt(_decimal)
                if (_decimal > 4) {
                  _decimal = 4
                }
                _type = 'number'
              } else if (/^datetime/.test(_type)) {
                _type = 'datetime'
              } else if (/^date/.test(_type)) {
                _type = 'date'
              } else {
                _type = 'text'
              }
  
              return {
                field: item.FieldName,
                label: item.FieldDec,
                type: _type,
                datatype: _type,
                decimal: _decimal
              }
            })
          }
          _columns.push(tabmsg)
        } else {
          notification.warning({
            top: 92,
            message: res.message,
            duration: 5
          })
        }
      })
 
      this.setState({
        tableColumns: _columns
      })
    })
 
    Api.getSystemConfig({func: 'sPC_Get_UserTemp', TypeCharTwo: 'tab'}).then(res => {
      if (res.status) {
        this.setState({
          tabviews: res.UserTemp.map(temp => {
            return {
              uuid: temp.MenuID,
              value: temp.MenuID,
              text: temp.MenuName,
              type: temp.Template,
              MenuNo: temp.MenuNo
            }
          })
        })
      } else {
        notification.warning({
          top: 92,
          message: res.message,
          duration: 5
        })
      }
    })
  }
 
  /**
   * @description 组件销毁,清除state更新
   */
  componentWillUnmount () {
    this.setState = () => {
      return
    }
  }
  
  /**
   * @description 加载或刷新标签信息
   */
  reloadTab = () => {
    this.setState({
      loading: true,
      tabviews: []
    })
    Api.getSystemConfig({func: 'sPC_Get_UserTemp', TypeCharTwo: 'tab'}).then(res => {
      if (res.status) {
        this.setState({
          loading: false,
          tabviews: res.UserTemp.map(temp => {
            return {
              uuid: temp.MenuID,
              value: temp.MenuID,
              text: temp.MenuName,
              type: temp.Template,
              MenuNo: temp.MenuNo
            }
          })
        })
        notification.success({
          top: 92,
          message: '刷新成功。',
          duration: 2
        })
      } else {
        this.setState({
          loading: false
        })
        notification.warning({
          top: 92,
          message: res.message,
          duration: 5
        })
      }
    })
  }
 
  // 页面返回
  handleViewBack = () => {
    const { menu } = this.props
    let _tabview = menu ? menu.LongParam.Template : ''
    let param = {
      editMenu: menu,
      editTab: null,
      tabConfig: null,
      editSubTab: null,
      subTabConfig: null,
      btnTab: null,
      btnTabConfig: null,
      editAction: null,
      subConfig: null,
      tabview: _tabview
    }
 
    this.props.handleView(param)
  }
 
  handleList = (type, list, card, groupId, elementId) => {
    const { config } = this.state
 
    if (type === 'action') {
      if (list.length > config.action.length) {
  
        this.handleAction(card)
      }
 
      this.setState({config: {...config, action: list}})
    } else if (type === 'search') {
      let _groups = null
 
      if (card) {
        // 元素添加
        if (config.groups.length === 1) {
          _groups = config.groups.map(group => {
            let _list = list.filter(item => !item.origin)
            return {...group, sublist: _list}
          })
        } else {
          _groups = config.groups.map(group => {
            if (group.uuid === groupId) {
              return {...group, sublist: list}
            } else {
              return group
            }
          })
        }
        this.handleSearch(card)
      } else if (elementId) {
        // 修改已有元素的分组
        let element = null
        _groups = config.groups.map(group => {
          group.sublist = group.sublist.filter(item => {
            if (item.uuid === elementId) {
              element = item
              return false
            } else {
              return true
            }
          })
          return group
        })
 
        _groups = _groups.map(group => {
          if (group.uuid === groupId) {
            group.sublist.push(element)
          }
          return group
        })
      } else {
        // 元素移动
        _groups = config.groups.map(group => {
          if (group.uuid === groupId) {
            return {...group, sublist: list}
          } else {
            return group
          }
        })
      }
 
      this.setState({
        config: {...config, groups: _groups}
      })
    }
  }
 
  handleSearch = (card) => {
    const { menu } = this.props
    const { config } = this.state
    let _inputfields = []
    let _tabfields = []
    let _linkableFields = []
    let _linksupFields = []
    let _formfields = []
 
    // 设置下拉菜单可关联字段
    config.groups.forEach(group => {
      _formfields = [..._formfields, ...group.sublist]
    })
 
    _inputfields = _formfields.filter(item => ['text', 'number', 'textarea', 'color'].includes(item.type) && card.field !== item.field)
    _tabfields = _formfields.filter(item => card.field !== item.field && item.hidden !== 'true' && ['text', 'number', 'select', 'link'].includes(item.type))
    _tabfields.unshift({field: '', text: '原表单'})
    
    if (card.linkSubField && card.linkSubField.length > 0) {
      let fields = _inputfields.map(item => item.field)
      card.linkSubField = card.linkSubField.filter(item => fields.includes(item))
    }
 
    let uniq = new Map()
    uniq.set(card.field, true)
 
    _formfields.forEach(item => {
      if (item.type !== 'select' && item.type !== 'link') return
      if (item.field && !uniq.has(item.field)) {
        uniq.set(item.field, true)
 
        _linkableFields.push({
          value: item.field,
          text: item.label + ' (表单)'
        })
        _linksupFields.push({
          value: item.field,
          text: item.label
        })
      }
    })
 
    if (menu.LongParam) {
      menu.LongParam.columns.forEach(col => {
        if (col.field && !uniq.has(col.field)) {
          uniq.set(col.field, true)
 
          _linkableFields.push({
            value: col.field,
            text: col.label + ' (显示列)'
          })
        }
      })
    }
 
    this.setState({
      modaltype: 'search',
      card: card,
      formlist: getModalForm(card, _inputfields, _tabfields, _linkableFields, _linksupFields).map(item => {
        if (item.key === 'type') {
          item.options = item.options.filter(option => !['switch', 'checkbox', 'radio', 'checkcard', 'hint'].includes(option.value))
        }
        return item
      })
    })
  }
 
  handleAction = (card) => {
    let usefulFields = sessionStorage.getItem('permFuncField')
    if (usefulFields) {
      try {
        usefulFields = JSON.parse(usefulFields)
      } catch (e) {
        usefulFields = []
      }
    } else {
      usefulFields = []
    }
 
    this.setState({
      modaltype: 'actionEdit',
      card: card,
      formlist: getActionForm(card, this.state.config, usefulFields)
    })
  }
 
 
  /**
   * @description 搜索、按钮、显示列修改后提交保存
   * 1、搜索条件保存,当类型为下拉框且存在数据源时,将查询条件拼接为sql,并用base64转码
   * 2、按钮包括正常编辑和复制,复制时,按钮列末尾添加
   * 3、添加或编辑列,保存时,如按钮位置设置为表格,则修改操作列显示状态
   */
  handleSubmit = () => {
    const { config, modaltype, card } = this.state
 
    if (modaltype === 'search') {
      this.modalFormRef.handleConfirm().then(res => {
        let _config = JSON.parse(JSON.stringify(config))
 
        if (_config.setting.primaryKey && _config.setting.primaryKey.toLowerCase() === res.field.toLowerCase()) {
          notification.warning({
            top: 92,
            message: '表单中字段名不可与主键重复!',
            duration: 5
          })
          return
        }
 
        let _groups = null
        let fieldrepet = false  // 字段重复
 
        if (card.iscopy) {
          _groups = _config.groups.map(group => {
            let _index = null
            group.sublist.forEach((item, index) => {
              if (item.uuid === card.originUuid) {
                _index = index
              }
 
              if (item.uuid !== res.uuid && item.field === res.field) {
                fieldrepet = true
              }
            })
 
            if (_index !== null) {
              group.sublist.splice(_index + 1, 0, res)
            }
 
            if (group.isDefault) {
              group.sublist = group.sublist.filter(item => !item.origin)
            }
            return group
          })
        } else {
          _groups = _config.groups.map(group => {
            group.sublist = group.sublist.map(item => {
              if (item.uuid !== res.uuid && item.field === res.field) {
                fieldrepet = true
              }
 
              if (item.uuid === res.uuid) {
                return res
              } else {
                return item
              }
            })
            if (group.isDefault) {
              group.sublist = group.sublist.filter(item => !item.origin)
            }
            return group
          })
        }
 
        if (fieldrepet) {
          notification.warning({
            top: 92,
            message: '字段已存在!',
            duration: 5
          })
          return
        }
 
        if ((res.type === 'select' || res.type === 'multiselect' || res.type === 'link') && res.resourceType === '1' && /\s/.test(res.dataSource)) {
          this.setState({
            sqlVerifing: true
          })
  
          let param = {
            func: 's_debug_sql',
            exec_type: 'y',
            LText: res.dataSource
          }
 
          param.LText = param.LText.replace(/@\$|\$@/ig, '')
 
          param.LText = Utils.formatOptions(param.LText)
          param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
          param.secretkey = Utils.encrypt('', param.timestamp)
  
          if (window.GLOB.mainSystemApi && res.database === 'sso') {
            param.rduri = window.GLOB.mainSystemApi
          }
          
          Api.getLocalConfig(param).then(result => {
            if (result.status) {
              this.setState({
                sqlVerifing: false,
                config: {..._config, groups: _groups},
                modaltype: ''
              })
            } else {
              this.setState({sqlVerifing: false})
 
              Modal.error({
                title: result.message
              })
            }
          })
        } else {
          this.setState({
            config: {..._config, groups: _groups},
            modaltype: ''
          })
        }
      })
    } else if (modaltype === 'actionEdit') {
      this.actionFormRef.handleConfirm().then(res => {
        let _action = config.action.map(item => {
          if (item.uuid === res.uuid) {
            return res
          } else {
            return item
          }
        })
 
        this.setState({
          config: {...config, action: _action},
          modaltype: ''
        })
      })
    }
  }
 
  editModalCancel = () => {
    const { config, card, modaltype } = this.state
 
    if (card.focus) {
      let _config = null
      if (modaltype === 'search') {
        let _groups = config.groups.map(group => {
          group.sublist = group.sublist.filter(item => item.uuid !== card.uuid)
          return group
        })
        _config = {...config, groups: _groups}
      } else if (modaltype === 'actionEdit') {
        let _action = config.action.filter(item => item.uuid !== card.uuid)
        _config = {...config, action: _action}
      } else {
        _config = config
      }
 
      this.setState({
        card: null,
        config: _config,
        modaltype: ''
      })
    } else {
      this.setState({
        card: null,
        modaltype: ''
      })
    }
  }
 
  /**
   * @description 创建按钮存储过程
   */
  creatFunc = () => {
    const { menu } = this.props
    let _config = JSON.parse(JSON.stringify(this.state.config))
 
    this.actionFormRef.handleConfirm().then(res => {
      let btn = res         // 按钮信息
      let newLText = ''     // 创建存储过程sql
      let DelText = ''      // 删除存储过程sql
 
      // 创建存储过程,必须填写内部函数名
      if (!btn.innerFunc) {
        notification.warning({
          top: 92,
          message: '请填写内部函数!',
          duration: 5
        })
        return
      }
 
      let fields = []
      _config.groups.forEach(group => {
        fields = [...fields, ...group.sublist]
      })
 
      let _param = {
        funcName: btn.innerFunc,
        name: _config.setting.tableName || '',
        fields: fields,
        menuNo: menu.MenuNo
      }
 
      newLText = Utils.formatOptions(FuncUtils.getfunc(_param, btn, menu, _config))
      DelText = Utils.formatOptions(FuncUtils.dropfunc(_param.funcName))
 
      this.refs.btnCreatFunc.exec(btn.innerFunc, newLText, DelText)
    })
  }
 
  /**
   * @description 创建表格存储过程
   */
  tableCreatFunc = () => {
    const { menu } = this.props
    const { config } = this.state
 
    this.settingRef.handleConfirm().then(setting => {
 
      if (!(setting.interType === 'inner') || !setting.innerFunc) {
        notification.warning({
          top: 92,
          message: '接口类型为-内部,且存在内部函数时,才可以创建存储过程!',
          duration: 5
        })
        return
      }
 
      if (/[^\s]+\s+[^\s]+/ig.test(setting.dataresource) && config.setting.dataresource !== setting.dataresource) {
        let param = {
          func: 's_DataSrc_Save',
          LText: setting.dataresource,
          MenuID: menu.MenuID
        }
 
        param.LText = Utils.formatOptions(param.LText)
        param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
        param.secretkey = Utils.encrypt(param.LText, param.timestamp)
 
        Api.getLocalConfig(param)
      }
 
      let _config = {...config, setting: setting}
      let newLText = Utils.formatOptions(FuncUtils.getTableFunc(setting, menu, _config)) // 创建存储过程sql
      let DelText = Utils.formatOptions(FuncUtils.dropfunc(setting.innerFunc))          // 删除存储过程sql
 
      this.refs.tableCreatFunc.exec(setting.innerFunc, newLText, DelText).then(result => {
        if (result === 'success') {
          this.setState({
            config: _config
          })
        }
      })
    })
  }
 
  deleteElement = (element) => {
    let _this = this
    confirm({
      content: `确定删除<<${element.card.label}>>吗?`,
      onOk() {
        let _config = JSON.parse(JSON.stringify(_this.state.config))
        let _delActions = _this.state.delActions
 
        if (element.type === 'search') {
          _config.groups = _config.groups.map(group => {
            group.sublist = group.sublist.filter(item => item.uuid !== element.card.uuid)
            return group
          })
        } else {
          _config[element.type] = _config[element.type].filter(item => {
            if (item.uuid === element.card.uuid) {
              return false
            } else {
              return true
            }
          })
          _delActions.push(element.card.uuid)
        }
 
        _this.setState({
          config: _config,
          delActions: _delActions
        })
      },
      onCancel() {}
    })
  }
 
  /**
   * @description 验证信息配置
   */
  profileAction = (element) => {
    this.setState({
      profileVisible: true,
      card: element
    })
  }
 
  /**
   * @description 验证信息保存
   */
  verifySubmit = () => {
    const { card } = this.state
    let config = JSON.parse(JSON.stringify(this.state.config))
 
    this.verifyRef.handleConfirm().then(res => {
      config.action = config.action.map(item => {
        if (item.uuid === card.uuid) {
          item.verify = res
        }
  
        return item
      })
  
      this.setState({
        profileVisible: false,
        config: config,
        card: ''
      })
    })
  }
 
  /**
   * @description 菜单保存
   */
  submitConfig = () => {
    const { menu, btnTab } = this.props
    const { delActions, openEdition } = this.state
 
    let config = JSON.parse(JSON.stringify(this.state.config))
 
    this.menuformRef.handleConfirm().then(res => {
      if (config.isAdd) {
        if (config.groups[0] && config.groups[0].sublist[0] && config.groups[0].sublist[0].origin) {
          config.groups[0].sublist = config.groups[0].sublist.filter(item => !item.origin)
        }
        config.tabgroups[0].sublist = config.tabgroups[0].sublist.filter(item => !item.origin)
      }
 
      let btnNames = config.action.map(item => item.label)
      btnNames = Array.from(new Set(btnNames))
      if (btnNames.length < config.action.length) {
        notification.warning({
          top: 92,
          message: '按钮名称不可相同!',
          duration: 5
        })
        return
      }
 
      let _LongParam = ''
      let _config = {...config, tables: this.state.selectedTables}
 
      // 数据来源为查询且未设置主键时,启用为false
      if (_config.setting.datatype === 'query' && !_config.setting.primaryKey) {
        _config.enabled = false
      } else if (_config.setting.datatype === 'query' && _config.setting.interType === 'inner' && !_config.setting.innerFunc && !_config.setting.dataresource) {
        _config.enabled = false
      }
 
      // 标签不合法时,启用状态为false
      if (_config.tabgroups.length > 1) {
        _config.tabgroups.forEach(group => {
          if (group.sublist.length === 0) {
            _config.enabled = false
          }
        })
      }
 
      // 存在多余的空表单组
      let _ismutil = _config.groups.length > 1
      let _primary = _config.setting.primaryKey ? _config.setting.primaryKey.toLowerCase() : ''
 
      _config.groups.forEach(group => {
        if (_ismutil && group.sublist.length === 0) {
          _config.enabled = false
        }
        let arr = group.sublist.filter(item => item.field && item.field.toLowerCase() === _primary)
 
        if (arr.length > 0) {
          _config.enabled = false
        }
      })
 
      _config.funcs = [] // 页面及子页面存储过程集
 
      if (_config.setting.datatype === 'query') {
        _config.funcs.push({
          type: 'view',
          subtype: 'view',
          uuid: btnTab.uuid,
          intertype: _config.setting.interType || 'inner',
          interface: _config.setting.interface || '',
          tableName: _config.setting.tableName || '',
          innerFunc: _config.setting.innerFunc || '',
          outerFunc: _config.setting.outerFunc || ''
        })
      }
 
      _config.action.forEach(item => {
        if (item.btnType !== 'cancel') {
          _config.funcs.push({
            type: 'button',
            subtype: 'btn',
            uuid: item.uuid,
            label: item.label,
            tableName: item.sql || '',
            intertype: item.intertype,
            interface: item.interface || '',
            innerFunc: item.innerFunc || '',
            outerFunc: item.outerFunc || '',
            callbackFunc: item.callbackFunc || ''
          })
        }
      })
 
      _config.tabgroups.forEach(group => {
        group.sublist.forEach(tab => {
          _config.funcs.push({
            type: 'tab',
            subtype: 'tab',
            uuid: tab.uuid,
            label: tab.label,
            linkTab: tab.linkTab
          })
        })
      })
 
      if (this.state.closeVisible) { // 显示关闭对话框时,模态框中保存按钮,显示保存中状态
        this.setState({
          menucloseloading: true
        })
      } else {
        this.setState({
          menuloading: true
        })
      }
 
      new Promise(resolve => {
        let deffers = []
        _config.funcs.forEach(item => {
          if (item.type === 'tab') {
            let deffer = new Promise(resolve => {
              Api.getSystemConfig({
                func: 'sPC_Get_LongParam',
                MenuID: item.linkTab
              }).then(result => {
                if (result.status && result.LongParam) {
                  let _LongParam = ''
        
                  if (result.LongParam) {
                    try {
                      _LongParam = JSON.parse(window.decodeURIComponent(window.atob(result.LongParam)))
                    } catch (e) {
                      console.warn('Parse Failure')
                      _LongParam = ''
                    }
                  }
      
                  if (_LongParam) {
                    item.menuNo = _LongParam.tabNo
                    item.subfuncs = _LongParam.funcs || []
                  }
                }
                resolve()
              })
            })
 
            deffers.push(deffer)
          }
        })
 
        if (deffers.length === 0) {
          resolve()
        } else {
          Promise.all(deffers).then(() => {
            resolve()
          })
        }
      }).then(() => {
        
        // 删除添加标识
        delete _config.isAdd
  
        try {
          _LongParam = window.btoa(window.encodeURIComponent(JSON.stringify(_config)))
        } catch (e) {
          notification.warning({
            top: 92,
            message: '编译错误',
            duration: 5
          })
 
          this.setState({
            menucloseloading: false,
            menuloading: false
          })
          return
        }
  
        let _sort = 0 // 按钮及标签排序
 
        let btnParam = { // 添加菜单按钮
          func: 'sPC_Button_AddUpt',
          Type: 60,      // 添加按钮表单页下的按钮
          ParentID: btnTab.uuid,
          MenuNo: menu.MenuNo,
          Template: menu.PageParam.Template || '',
          PageParam: '',
          LongParam: '',
          LText: config.action.map((item, index) => {
            _sort++
            return `select '${item.uuid}' as menuid, '${item.label}' as menuname, '${_sort * 10}' as Sort`
          })
        }
  
        btnParam.LText = btnParam.LText.join(' union all ')
        btnParam.LText = Utils.formatOptions(btnParam.LText)
        btnParam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
        btnParam.secretkey = Utils.encrypt(btnParam.LText, btnParam.timestamp)
        
        let tabParam = { // 添加菜单tab页
          func: 'sPC_sMenusTab_AddUpt',
          MenuID: btnTab.uuid
        }
        
        let _LText = []
 
        config.tabgroups.forEach(group => {
          group.sublist.forEach(item => {
            _sort++
            _LText.push(`select '${btnTab.uuid}' as MenuID ,'${item.linkTab}' as Tabid,'${item.label}' as TabName ,'${_sort * 10}' as Sort`)
          })
        })
 
        _LText = _LText.join(' union all ')
 
        tabParam.LText = Utils.formatOptions(_LText)
 
        tabParam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
        tabParam.secretkey = Utils.encrypt(tabParam.LText, tabParam.timestamp)
  
        let param = {
          func: 'sPC_ButtonParam_AddUpt',
          ParentID: menu.MenuID,
          MenuID: btnTab.uuid,
          MenuNo: menu.MenuNo,
          Template: 'FormTab',
          MenuName: btnTab.label,
          PageParam: JSON.stringify({Template: 'FormTab'}),
          LongParam: _LongParam
        }
 
        if (openEdition) {
          param.open_edition = openEdition
        }
 
        // 有按钮或标签删除时,先进行删除操作
        // 删除成功后,保存页面配置
        new Promise(resolve => {
          if (delActions.length > 0) {
            let deffers = delActions.map(item => {
              let _param = {
                func: 'sPC_MainMenu_Del',
                MenuID: item
              }
              return new Promise(resolve => {
                Api.getSystemConfig(_param).then(response => {
                  resolve(response)
                })
              })
            })
            Promise.all(deffers).then(result => {
              let error = null
              result.forEach(response => {
                if (!response.status) {
                  error = response
                }
              })
    
              if (error) {
                this.setState({
                  menuloading: false,
                  menucloseloading: false
                })
                notification.warning({
                  top: 92,
                  message: error.message,
                  duration: 5
                })
                resolve(false)
              } else {
                this.setState({
                  delActions: []
                })
                resolve(true)
              }
            })
          } else if (delActions.length === 0) {
            resolve(true)
          }
        }).then(resp => {
          if (resp === false) return
    
          Api.getSystemConfig(param).then(response => {
            if (response.status) {
              this.setState({
                openEdition: response.open_edition || '',
                config: _config,
                originMenu: _config
              })
    
              this.submitAction(btnParam, tabParam)
            } else {
              this.setState({
                menuloading: false,
                menucloseloading: false
              })
              notification.warning({
                top: 92,
                message: response.message,
                duration: 5
              })
            }
          })
        })
      })
    }, () => {
      notification.warning({
        top: 92,
        message: this.state.dict['model.menu.basemsg'],
        duration: 5
      })
    })
  }
 
  /**
   * @description 保存或修改菜单按钮
   */
  submitAction = (btnParam, tabParam) => {
    new Promise(resolve => {
      let deffers = []
 
      if (tabParam.LText) {
        let defer = new Promise(resolve => {
          Api.getSystemConfig(tabParam).then(result => {
            resolve(result)
          })
        })
        deffers.push(defer)
      }
 
      if (btnParam.LText) {
        let defer = new Promise(resolve => {
          Api.getSystemConfig(btnParam).then(result => {
            resolve(result)
          })
        })
        deffers.push(defer)
      }
 
      if (deffers.length === 0) {
        resolve(true)
      } else {
        Promise.all(deffers).then(result => {
          let error = false
          result.forEach(res => {
            if (!res.status) {
              error = res
            }
          })
 
          if (error) {
            notification.warning({
              top: 92,
              message: error.message,
              duration: 5
            })
            resolve(false)
          } else {
            resolve(true)
          }
        })
      }
    }).then(response => {
      if (response) {
        notification.success({
          top: 92,
          message: '保存成功',
          duration: 2
        })
        if (this.state.closeVisible) {
          this.handleViewBack()
        } else {
          this.setState({
            menuloading: false,
            menucloseloading: false
          })
        }
      } else {
        this.setState({
          menuloading: false,
          menucloseloading: false
        })
      }
    })
  }
 
  cancelConfig = () => {
    const { config, originMenu } = this.state
 
    let _this = this
 
    if (config.isAdd) {
      confirm({
        content: '按钮配置尚未提交,确定放弃保存吗?',
        onOk() {
          _this.handleViewBack()
        },
        onCancel() {}
      })
    } else {
      let _config = {...config, tables: this.state.selectedTables}
 
      if (!is(fromJS(_config), fromJS(originMenu))) {
        this.setState({
          closeVisible: true
        })
      } else {
        this.handleViewBack()
      }
    }
  }
 
  queryField = (type) => {
    const {selectedTables, tableColumns, config} = this.state
    // 判断是否已选择表名
    if (selectedTables.length === 0) {
      notification.warning({
        top: 92,
        message: '请选择表名!',
        duration: 5
      })
      return
    }
 
    // 表字段集转为map数据
    let columns = new Map()
    tableColumns.forEach(table => {
      table.columns.forEach(column => {
        columns.set(column.field, column)
      })
    })
 
    if (type === 'search') {
      // 添加搜索条件,字段集中存在搜索条件字段,使用搜索条件对象替换字段集,设置数据类型
      config.groups.forEach(group => {
        group.sublist.forEach(item => {
          if (columns.has(item.field)) {
            let _datatype = columns.get(item.field).datatype
            columns.set(item.field, {...item, selected: true, datatype: _datatype})
          }
        })
      })
    }
 
    // 显示字段集弹窗
    this.setState({
      tableVisible: true,
      fields: [...columns.values()]
    })
  }
 
  addFieldSubmit = () => {
    const {config} = this.state
    // 字段集为空,关闭弹窗
    if (!this.state.fields || this.state.fields.length === 0) {
      this.setState({
        tableVisible: false,
      })
    }
 
    // 获取已选字段集合
    let cards = this.refs.searchcard.state.selectCards
    let columnsMap = new Map()
    cards.forEach(card => {
      columnsMap.set(card.field, card)
    })
 
    let groups = config.groups.map(group => {
      group.sublist = group.sublist.map(item => {
        if (columnsMap.has(item.field)) {
          let cell = columnsMap.get(item.field)
  
          if (cell.selected && cell.type !== item.type) { // 数据类型修改
            item.type = cell.type
            item.initval = ''
          }
          columnsMap.delete(item.field)
        }
        return item
      })
      return group
    })
 
    let items =  [...columnsMap.values()].map(item => {
      let newcard = {
        uuid: Utils.getuuid(),
        label: item.label,
        field: item.field,
        initval: '',
        type: item.type,
        resourceType: '0',
        options: [],
        orderType: 'asc'
      }
 
      return newcard
    })
 
    groups = groups.map(group => {
      if (group.isDefault) {
        group.sublist = [...group.sublist, ...items]
        group.sublist = group.sublist.filter(item => !item.origin)
      }
      return group
    })
 
    this.setState({
      config: {...config, groups: groups}
    })
    notification.success({
      top: 92,
      message: '操作成功',
      duration: 2
    })
  }
 
  onTableChange = (value) => {
    const {tables, selectedTables, tableColumns} = this.state
 
    let _table = tables.filter(item => item.TbName === value)[0]
    let isSelected = !!selectedTables.filter(cell => cell.TbName === value)[0]
    if (!isSelected) {
      this.setState({
        selectedTables: [...selectedTables, _table]
      })
      Api.getSystemConfig({func: 'sPC_Get_FieldName', TBName: value}).then(res => {
        if (res.status) {
          let tabmsg = {
            tableName: _table.name,
            columns: res.FDName.map(item => {
              let _type = item.FieldType.toLowerCase()
              let _decimal = 0
              if (/^nvarchar/.test(_type)) {
                _type = 'text'
              } else if (/^int/.test(_type)) {
                _type = 'number'
              } else if (/^decimal/.test(_type)) {
                _decimal = _type.split(',')[1]
                _decimal = parseInt(_decimal)
                _type = 'number'
              } else if (/^datetime/.test(_type)) {
                _type = 'datetime'
              } else if (/^date/.test(_type)) {
                _type = 'date'
              } else {
                _type = 'text'
              }
 
              return {
                field: item.FieldName,
                label: item.FieldDec,
                type: _type,
                datatype: _type,
                decimal: _decimal
              }
            })
          }
          this.setState({
            tableColumns: [...tableColumns, tabmsg]
          })
        } else {
          notification.warning({
            top: 92,
            message: res.message,
            duration: 5
          })
        }
      })
    }
  }
 
  deleteTable = (table) => {
    const {selectedTables, tableColumns} = this.state
 
    this.setState({
      selectedTables: selectedTables.filter(item => item.TbName !== table.TbName),
      tableColumns: tableColumns.filter(item => item.tableName !== table.TbName)
    })
  }
 
  changeSetting = () => {
    this.setState({
      settingVisible: true
    })
  }
 
  settingSave = () => {
    const { menu } = this.props
    const {config} = this.state
 
    this.settingRef.handleConfirm().then(res => {
      if (
        res.interType === 'inner' &&
        !res.innerFunc &&
        /[^\s]+\s+[^\s]+/ig.test(res.dataresource) &&
        config.setting.dataresource !== res.dataresource
      ) {
        let param = {
          func: 's_DataSrc_Save',
          LText: res.dataresource,
          MenuID: menu.MenuID
        }
 
        param.LText = Utils.formatOptions(param.LText)
        param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
        param.secretkey = Utils.encrypt(param.LText, param.timestamp)
 
        Api.getLocalConfig(param)
      }
 
      if (res.interType === 'inner' && !res.innerFunc && res.dataresource && /\s/.test(res.dataresource)) {
        this.setState({
          sqlVerifing: true
        })
 
        let param = {
          func: 's_debug_sql',
          exec_type: 'y',
          LText: res.dataresource
        }
 
        param.LText = param.LText.replace(/@\$|\$@/ig, '')
 
        param.LText = Utils.formatOptions(param.LText)
        param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
        param.secretkey = Utils.encrypt('', param.timestamp)
        
        Api.getLocalConfig(param).then(result => {
          if (result.status) {
            this.setState({
              sqlVerifing: false,
              config: {...config, setting: res},
              settingVisible: false
            })
          } else {
            this.setState({sqlVerifing: false})
            
            Modal.error({
              title: result.message
            })
          }
        })
      } else {
        this.setState({
          config: {...config, setting: res},
          settingVisible: false
        })
      }
    })
  }
 
  /**
   * @description 设置可配置标签
   */
  setSubConfig = (btn) => {
    const {menu, btnTab} = this.props
    const { config, originMenu, activeKey, openEdition } = this.state
 
    if (config.isAdd) {
      notification.warning({
        top: 92,
        message: '菜单尚未保存,请保存菜单配置!',
        duration: 5
      })
    } else {
      this.menuformRef.handleConfirm().then(res => {
        let _config = {...config, tables: this.state.selectedTables}
 
        if (!is(fromJS(originMenu), fromJS(_config))) {
          notification.warning({
            top: 92,
            message: '菜单配置已修改,请保存!',
            duration: 5
          })
        } else {
          this.setState({
            loading: true
          })
 
          btnTab.activeKey = activeKey       // 保存当前打开页签
          btnTab.open_edition = openEdition  // 更新版本号
 
          let param = {
            editMenu: menu,
            editTab: btn,
            tabConfig: null,
            editSubTab: null,
            subTabConfig: null,
            btnTab: btnTab,
            btnTabConfig: _config,
            editAction: null,
            subConfig: '',
            tabview: btn.type
          }
 
          Api.getSystemConfig({
            func: 'sPC_Get_LongParam',
            MenuID: btn.linkTab
          }).then(res => {
            if (res.status) {
              this.setState({
                loading: false
              })
              let _LongParam = ''
              if (res.LongParam) {
                try {
                  _LongParam = JSON.parse(window.decodeURIComponent(window.atob(res.LongParam)))
                } catch (e) {
                  console.warn('Parse Failure')
                  _LongParam = ''
                }
              }
 
              if (_LongParam && param.tabview === 'SubTable' && _LongParam.Template === 'SubTable') {
                param.subConfig = _LongParam
              }
 
              if (param.editTab) {
                param.editTab.open_edition = res.open_edition || ''
              }
 
              this.props.handleView(param)
            } else {
              this.setState({
                loading: false
              })
              notification.warning({
                top: 92,
                message: res.message,
                duration: 5
              })
            }
          })
        }
      }, () => {
        notification.warning({
          top: 92,
          message: '菜单基本信息已修改,请保存!',
          duration: 5
        })
      })
    }
  }
 
  onEnabledChange = () => {
    const { config } = this.state
 
    let tabinvalid = true
    if (config.tabgroups.length > 1) {
      config.tabgroups.forEach(group => {
        if (group.sublist.length === 0) {
          tabinvalid = false
        }
      })
    }
    let forminvalid = true
    if (config.groups.length > 1) {
      config.groups.forEach(group => {
        if (group.sublist.length === 0) {
          forminvalid = false
        }
      })
    }
 
    let _primary = config.setting.primaryKey ? config.setting.primaryKey.toLowerCase() : ''
    let primaryrepeat = false
 
    config.groups.forEach(group => {
      let arr = group.sublist.filter(item => item.field && item.field.toLowerCase() === _primary)
 
      if (arr.length > 0) {
        primaryrepeat = true
      }
    })
 
    if (config.setting.datatype === 'query' && config.setting.interType === 'inner' && !config.setting.innerFunc && !config.setting.dataresource) {
      notification.warning({
        top: 92,
        message: '尚未设置数据源,不可启用!',
        duration: 5
      })
    } else if (config.setting.datatype === 'query' && !config.setting.primaryKey) {
      notification.warning({
        top: 92,
        message: '尚未设置主键,不可启用!',
        duration: 5
      })
    } else if (!tabinvalid) {
      notification.warning({
        top: 92,
        message: '存在多余标签组,不可启用!',
        duration: 5
      })
    } else if (!forminvalid) {
      notification.warning({
        top: 92,
        message: '存在多余空表单组,不可启用!',
        duration: 5
      })
    } else if (primaryrepeat) {
      notification.warning({
        top: 92,
        message: '表单字段与主键重复,不可启用!',
        duration: 5
      })
    } else {
      this.setState({
        config: {...config, enabled: !config.enabled}
      })
    }
  }
 
 
 
  handleGroup = (group) => {
    let editgroup = {
      label: '',
      sort: 0,
      uuid: Utils.getuuid(),
      sublist: []
    }
 
    if (group) {
      editgroup = group
    }
 
    this.setState({
      groupVisible: true,
      editgroup: editgroup
    })
  }
 
  closeGroup = (group) => {
    const { config } = this.state
    let _this = this
 
    confirm({
      content: `确定删除分组<<${group.label}>>吗?`,
      onOk() {
        let groups = config.groups.filter(item => !(item.uuid === group.uuid))
        groups = groups.map(item => {
          if (item.isDefault) {
            item.sublist = [...item.sublist, ...group.sublist]
          }
 
          return item
        })
 
        _this.setState({
          config: {...config, groups: groups},
        })
      },
      onCancel() {}
    })
  }
 
  handleGroupSave = () => {
    const { editgroup, config } = this.state
    let groups = config.groups.filter(item => !item.isDefault && item.uuid !== editgroup.uuid)
 
    this.groupRef.handleConfirm().then(res => {
      if (editgroup.isDefault) {
        groups.push(res)
      } else {
        groups.push(res.default, res.target)
      }
 
      groups = groups.sort((a, b) => {
        return a.sort - b.sort
      })
 
      this.setState({
        config: {...config, groups: groups},
        editgroup: '',
        groupVisible: false,
      })
    })
  }
 
 
  pasteSubmit = () => {
    let _config = JSON.parse(JSON.stringify(this.state.config))
 
    this.pasteFormRef.handleConfirm().then(res => {
      if (res.copyType === 'form') {
        _config.groups.forEach(group => {
          if (group.isDefault) {
            group.sublist.push(res)
          }
        })
 
        if (res.type === 'linkMain') {
          notification.warning({
            top: 92,
            message: '不支持此表单类型!',
            duration: 5
          })
          return
        }
 
        this.setState({
          config: _config,
          pasteVisible: null
        }, () => {
          this.handleSearch(res)
        })
      } else {
        notification.warning({
          top: 92,
          message: '配置信息格式错误!',
          duration: 5
        })
      }
    })
  }
 
  /**
   * @description 更新标签配置信息
   */
  updatetabs = (config, delcards) => {
    const { delActions } = this.state
 
    this.setState({
      config: config,
      delActions: delcards ? [...delActions, ...delcards.map(item => item.uuid)] : delActions
    })
  }
 
  render () {
    const { config, modaltype, activeKey } = this.state
    let _length = config.groups.length
 
    let configTabs = []
    config.tabgroups.forEach(group => {
      configTabs.push(...group.sublist)
    })
 
    return (
      <div className="form-tab-board">
        <DndProvider backend={HTML5Backend}>
          {/* 工具栏 */}
          <div className="tools">
            <Collapse accordion defaultActiveKey={activeKey} bordered={false} onChange={(key) => this.setState({activeKey: key})}>
              {/* 基本信息 */}
              <Panel forceRender={true} header={this.state.dict['header.menu.basedata']} key="0" id="common-basedata">
                {/* 菜单信息 */}
                <MenuForm
                  dict={this.state.dict}
                  formlist={this.state.menuformlist}
                  wrappedComponentRef={(inst) => this.menuformRef = inst}
                />
                {/* 表名添加 */}
                <div className="ant-col ant-form-item-label">
                  <label>
                    <Tooltip placement="topLeft" title="此处可以添加配置相关的常用表,在添加搜索条件和显示列时,可通过工具栏中的添加按钮,批量添加表格相关字段。">
                      <QuestionCircleOutlined className="mk-form-tip" />
                      {this.state.dict['header.menu.table.add']}
                    </Tooltip>
                  </label>
                </div>
                <Select
                  showSearch
                  className="tables"
                  style={{ width: '100%' }}
                  optionFilterProp="children"
                  value="请选择表名"
                  onChange={this.onTableChange}
                  showArrow={false}
                  getPopupContainer={() => document.getElementById('common-basedata')}
                  filterOption={(input, option) => {
                    return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                      option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }}
                > 
                  {this.state.tables.map((table, index) => (
                    <Option key={index} title={table.TbName} value={table.TbName}>{table.Remark}</Option>
                  ))}
                </Select>
                {this.state.selectedTables.length > 0 && <List
                  size="small"
                  bordered
                  dataSource={this.state.selectedTables}
                  renderItem={(item, index) => <List.Item key={index} title={item.Remark + ' (' + item.TbName + ')'}>
                    {item.Remark + ' (' + item.TbName + ')'}
                    <CloseOutlined onClick={() => this.deleteTable(item)}/>
                    <div className="bottom-mask"></div>
                  </List.Item>}
                />}
              </Panel>
              {/* 搜索条件添加 */}
              <Panel header={this.state.dict['header.menu.form']} key="1">
                <div className="search-element">
                  {Source.searchItems.map((item, index) => {
                    return (<SourceElement key={index} content={item}/>)
                  })}
                </div>
                <Button type="primary" block onClick={() => this.queryField('search')}>批量添加</Button>
              </Panel>
              {/* 按钮添加 */}
              <Panel header={this.state.dict['header.menu.action']} key="2">
                <div className="search-element">
                  {Source.actionItems.map((item, index) => {
                    return (<SourceElement key={index} content={item}/>)
                  })}
                </div>
              </Panel>
              {/* 添加标签 */}
              <Panel header={this.state.dict['header.menu.tab']} key="4">
                <div className="search-element">
                  {Source.tabItems.map((item, index) => {
                    return (<SourceElement key={index} content={item}/>)
                  })}
                </div>
                {configTabs.length > 0 ?
                  <p className="config-btn-title">
                    <Tooltip placement="topLeft" title="点击按钮,可完成或查看标签配置信息。">
                      <QuestionCircleOutlined className="mk-form-tip" />
                    </Tooltip>
                    标签配置
                  </p> : null
                }
                {configTabs.map((item, index) => {
                  return (
                    <div key={index}>
                      <Button
                        className="config-button"
                        icon={item.icon}
                        style={{marginBottom: '10px'}}
                        onClick={() => this.setSubConfig(item, 'tab')}
                      >{item.label}</Button>
                    </div>
                  )
                })}
              </Panel>
            </Collapse>
          </div>
          <div className="setting">
            <Card title={
              <div>
                页面配置 
                <RedoOutlined style={{marginLeft: '10px'}} title="刷新标签列表" onClick={this.reloadTab} />
              </div>
            } bordered={false} extra={
              <div>
                <Switch className="big" checkedChildren="启" unCheckedChildren="停" checked={this.state.config.enabled} onChange={this.onEnabledChange} />
                <Button type="primary" onClick={this.submitConfig} loading={this.state.menuloading}>{this.state.dict['model.save']}</Button>
                <Button onClick={this.cancelConfig}>{this.state.dict['model.back']}</Button>
              </div>
            } style={{ width: '100%' }}>
              <SettingOutlined onClick={this.changeSetting} />
              <Tooltip placement="bottomLeft" overlayClassName="middle" title="在左侧工具栏《搜索》中,选择对应搜索框拖至此处添加;或点击按钮《添加搜索条件》批量添加,选择批量添加时,需提前选择使用表。">
                <QuestionCircleOutlined style={{position: 'relative', color: '#c49f47', left: '5px', top: '20px'}} />
              </Tooltip>
              <Collapse
                activeKey={config.groups.map(group => group.uuid)}
                expandIconPosition={'right'}
              >
                {config.groups.map((group, index) => (
                  <Panel showArrow={false} header={group.label} key={group.uuid} extra={(
                    <span>
                      {index === _length - 1 ? <PlusOutlined
                        onClick={() => { this.handleGroup()}}
                      /> : null}
                      {_length > 1 && index !== _length - 1 ? <DeleteOutlined
                        onClick={() => { this.closeGroup(group) }}
                      /> : null}
                      <EditOutlined onClick={() => { this.handleGroup(group) }}/>
                    </span>
                  )}>
                    {group.isDefault ? <SnippetsOutlined title={this.state.dict['header.form.paste']} onClick={() => {this.setState({pasteVisible: true})}} /> : null}
                    <DragElement
                      type="search"
                      groupId={group.uuid}
                      list={group.sublist}
                      handleList={this.handleList}
                      setting={config.setting}
                      handleMenu={this.handleSearch}
                      deleteMenu={this.deleteElement}
                    />
                  </Panel>
                ))}
              </Collapse>
              <div className="action-list">
                <Tooltip placement="bottomLeft" overlayClassName="middle" title="在左侧工具栏《按钮》中,选择对应类型的按钮拖至此处添加,如选择按钮类型为表单、新标签页等含有配置页面的按钮,可在左侧工具栏-按钮-可配置按钮处,点击按钮完成相关配置。注:当设置按钮显示位置为表格时,显示列会增加操作列。">
                  <QuestionCircleOutlined style={{position: 'absolute', color: '#c49f47', left: '5px', top: '5px'}} />
                </Tooltip>
                <DragElement
                  type="action"
                  list={this.state.config.action}
                  handleList={this.handleList}
                  handleMenu={this.handleAction}
                  deleteMenu={this.deleteElement}
                  profileMenu={this.profileAction}
                />
              </div>
              {/* 标签组 */}
              <TabsComponent
                config={config}
                tabs={this.state.tabviews}
                setSubConfig={(item) => this.setSubConfig(item, 'tab')}
                updatetabs={this.updatetabs}
              />
            </Card>
          </div>
        </DndProvider>
        {/* 编辑表单 */}
        <Modal
          title={this.state.card && this.state.card.iscopy ? '表单-复制' : '表单-编辑'}
          visible={modaltype === 'search'}
          width={950}
          maskClosable={false}
          onOk={this.handleSubmit}
          confirmLoading={this.state.sqlVerifing}
          onCancel={this.editModalCancel}
          destroyOnClose
        >
          <ModalForm
            dict={this.state.dict}
            card={this.state.card}
            formlist={this.state.formlist}
            inputSubmit={this.handleSubmit}
            wrappedComponentRef={(inst) => this.modalFormRef = inst}
          />
        </Modal>
        {/* 编辑按钮:复制、编辑 */}
        <Modal
          title={this.state.dict['model.action'] + '-' + this.state.dict['model.edit']}
          visible={modaltype === 'actionEdit'}
          width={900}
          maskClosable={false}
          onCancel={this.editModalCancel}
          footer={[
            this.state.card && this.state.card.btnType !== 'cancel' ?
            <CreateFunc key="create" dict={this.state.dict} ref="btnCreatFunc" trigger={this.creatFunc}/> : null,
            <Button key="cancel" onClick={this.editModalCancel}>{this.state.dict['model.cancel']}</Button>,
            <Button key="confirm" type="primary" onClick={this.handleSubmit}>{this.state.dict['model.confirm']}</Button>
          ]}
          destroyOnClose
        >
          <ActionForm
            dict={this.state.dict}
            card={this.state.card}
            tabs={this.state.tabviews}
            formlist={this.state.formlist}
            inputSubmit={this.handleSubmit}
            wrappedComponentRef={(inst) => this.actionFormRef = inst}
          />
        </Modal>
        {/* 根据字段名添加显示列及搜索条件 */}
        <Modal
          wrapClassName="common-table-fields-modal"
          title={this.state.dict['model.edit']}
          visible={this.state.tableVisible}
          width={'65vw'}
          maskClosable={false}
          cancelText={this.state.dict['model.close']}
          onOk={this.addFieldSubmit}
          onCancel={() => { // 取消添加
            this.setState({
              tableVisible: false
            })
          }}
          destroyOnClose
        >
          {this.state.fields && this.state.fields.length > 0 ?
            <EditCard data={this.state.fields} ref="searchcard" type={'form'} dict={this.state.dict} /> : null
          }
          {(!this.state.fields || this.state.fields.length === 0) &&
            <Empty />
          }
        </Modal>
        {/* 按钮使用系统存储过程时,验证信息模态框 */}
        <Modal
          wrapClassName="common-table-fields-modal"
          title={'验证信息'}
          visible={this.state.profileVisible}
          width={'90vw'}
          maskClosable={false}
          okText={this.state.dict['model.submit']}
          onOk={this.verifySubmit}
          onCancel={() => {
            if (this.verifyRef.handleCancel) {
              this.verifyRef.handleCancel().then(() => {
                this.setState({ profileVisible: false })
              })
            } else {
              this.setState({ profileVisible: false })
            }
          }}
          destroyOnClose
        >
          <VerifyCard
            card={this.state.card}
            btnTab={this.props.btnTab}
            config={this.state.config}
            columns={this.state.columns}
            wrappedComponentRef={(inst) => this.verifyRef = inst}
            dict={this.state.dict}
          />
        </Modal>
        {/* 设置全局配置及列表数据源 */}
        <Modal
          title={this.state.dict['model.edit']}
          visible={this.state.settingVisible}
          width={700}
          maskClosable={false}
          onCancel={() => { // 取消修改
            this.setState({
              settingVisible: false
            })
          }}
          footer={[
            <CreateFunc key="create" dict={this.state.dict} ref="tableCreatFunc" trigger={this.tableCreatFunc}/>,
            <Button key="cancel" onClick={() => { this.setState({ settingVisible: false }) }}>{this.state.dict['model.cancel']}</Button>,
            <Button key="confirm" type="primary" loading={this.state.sqlVerifing} onClick={this.settingSave}>{this.state.dict['model.confirm']}</Button>
          ]}
          destroyOnClose
        >
          <SettingForm
            dict={this.state.dict}
            menu={this.props.menu}
            config={this.state.config}
            inputSubmit={this.settingSave}
            wrappedComponentRef={(inst) => this.settingRef = inst}
          />
        </Modal>
        <Modal
          bodyStyle={{textAlign: 'center', color: '#000000', fontSize: '16px'}}
          closable={false}
          maskClosable={false}
          visible={this.state.closeVisible}
          onCancel={() => { this.setState({closeVisible: false}) }}
          footer={[
            <Button key="save" className="mk-btn mk-green" loading={this.state.menucloseloading} onClick={this.submitConfig}>{this.state.dict['model.save']}</Button>,
            <Button key="confirm" className="mk-btn mk-yellow" onClick={this.handleViewBack}>{this.state.dict['model.notsave']}</Button>,
            <Button key="cancel" onClick={() => { this.setState({closeVisible: false}) }}>{this.state.dict['model.cancel']}</Button>
          ]}
          destroyOnClose
        >
          {this.state.dict['header.menu.config.placeholder']}
        </Modal>
        <Modal
          title="分组管理"
          visible={this.state.groupVisible}
          width={700}
          maskClosable={false}
          onOk={this.handleGroupSave}
          onCancel={() => { this.setState({ groupVisible: false }) }}
          destroyOnClose
        >
          <GroupForm
            groups={config.groups}
            dict={this.state.dict}
            group={this.state.editgroup}
            inputSubmit={this.handleGroupSave}
            wrappedComponentRef={(inst) => this.groupRef = inst}
          />
        </Modal>
        {/* 按钮配置信息粘贴复制 */}
        <Modal
          title={this.state.dict['header.form.paste']}
          visible={this.state.pasteVisible}
          width={600}
          maskClosable={false}
          onOk={this.pasteSubmit}
          onCancel={() => {this.setState({pasteVisible: null})}}
          destroyOnClose
        >
          <PasteForm
            dict={this.state.dict}
            wrappedComponentRef={(inst) => this.pasteFormRef = inst}
          />
        </Modal>
        {this.state.loading && <Spin size="large" />}
      </div>
    )
  }
}
 
const mapStateToProps = () => {
  return {}
}
 
const mapDispatchToProps = () => {
  return {}
}
 
export default connect(mapStateToProps, mapDispatchToProps)(ComTableConfig)