king
2022-03-29 b6cbfb08b51e87e6eac995be8e7751815715e6a1
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
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import { Button, Modal, notification, message } from 'antd'
 
import Api from '@/api'
import Utils from '@/utils/utils.js'
import options from '@/store/options.js'
import zhCN from '@/locales/zh-CN/main.js'
import enUS from '@/locales/en-US/main.js'
import asyncSpinComponent from '@/utils/asyncSpinComponent'
import { updateForm } from '@/utils/utils-update.js'
import MKEmitter from '@/utils/events.js'
import MkIcon from '@/components/mk-icon'
// import './index.scss'
 
const MutilForm = asyncSpinComponent(() => import('@/tabviews/zshare/mutilform'))
const { confirm } = Modal
let socket = null
 
class PrintButton extends Component {
  static propTpyes = {
    show: PropTypes.any,              // 按钮显示样式控制
    BID: PropTypes.string,            // 主表ID
    BData: PropTypes.any,             // 主表数据
    selectedData: PropTypes.any,      // 子表中选择数据
    Tab: PropTypes.any,               // 如果当前元素为标签时,tab为标签信息
    MenuID: PropTypes.string,         // 菜单ID
    btn: PropTypes.object,            // 按钮
    setting: PropTypes.any,           // 页面通用设置
    ContainerId: PropTypes.any,       // tab页面ID,用于弹窗控制
    disabled: PropTypes.any,          // 行按钮禁用
    lineId: PropTypes.any,            // 行索引+主键值,用于行按钮双击
  }
 
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    visible: false,
    formdata: null,
    selines: null,
    btnconfig: null,
    loading: false,
    disabled: false,
    hidden: false,
    loadingNumber: '',
    autoMatic: false
  }
 
  UNSAFE_componentWillMount () {
    const { btn, selectedData, BData } = this.props
    let disabled = false
 
    if (btn.controlField && selectedData && selectedData.length > 0) { // 表格中按钮隐藏控制
      selectedData.forEach(item => {
        let s = item[btn.controlField] !== undefined ? item[btn.controlField] + '' : ''
        if (s === btn.controlVal || (btn.controlVal && btn.controlVal.split(',').includes(s))) {
          disabled = true
        }
      })
      this.setState({hidden: disabled && btn.control === 'hidden'})
    } else if (btn.control === 'parent') {
      if (!BData || !BData.hasOwnProperty(btn.controlField)) {
        this.setState({hidden: true})
      } else {
        let s = BData[btn.controlField] + ''
        if (s === btn.controlVal || (btn.controlVal && btn.controlVal.split(',').includes(s))) {
          this.setState({hidden: true})
        } else {
          this.setState({hidden: false})
        }
      }
    }
 
    if (this.props.disabled || disabled) {
      this.setState({disabled: true})
    }
  }
 
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
 
  componentDidMount () {
    const { btn } = this.props
 
    MKEmitter.addListener('triggerBtnId', this.actionTrigger)
 
    if (btn.autoMatic) {
      MKEmitter.addListener('triggerBtnPopSubmit', this.triggerBtnPopSubmit)
    }
  }
 
  UNSAFE_componentWillReceiveProps (nextProps) {
    const { btn, selectedData, BData } = this.props
 
    let disabled = false
    if (btn.controlField && !is(fromJS(nextProps.selectedData || []), fromJS(selectedData || []))) {
      if (nextProps.selectedData && nextProps.selectedData.length > 0) { // 表格中按钮隐藏控制
        nextProps.selectedData.forEach(item => {
          let s = item[btn.controlField] !== undefined ? item[btn.controlField] + '' : ''
          if (s === btn.controlVal || (btn.controlVal && btn.controlVal.split(',').includes(s))) {
            disabled = true
          }
        })
      }
      this.setState({disabled, hidden: disabled && btn.control === 'hidden'})
    } else if (btn.control === 'parent' && !is(fromJS(nextProps.BData || {}), fromJS(BData || {}))) {
      if (!nextProps.BData || !nextProps.BData.hasOwnProperty(btn.controlField)) {
        this.setState({hidden: true})
      } else {
        let s = nextProps.BData[btn.controlField] + ''
        if (s === btn.controlVal || (btn.controlVal && btn.controlVal.split(',').includes(s))) {
          this.setState({hidden: true})
        } else {
          this.setState({hidden: false})
        }
      }
    }
 
    if (nextProps.disabled || disabled) {
      this.setState({disabled: true})
    } else {
      this.setState({disabled: false})
    }
  }
 
  componentWillUnmount () {
    this.setState = () => {
      return
    }
    MKEmitter.removeListener('triggerBtnId', this.actionTrigger)
    MKEmitter.removeListener('triggerBtnPopSubmit', this.triggerBtnPopSubmit)
  }
 
  triggerBtnPopSubmit = (id) => {
    const { btn } = this.props
 
    if (btn.uuid !== id) return
 
    this.handleOk()
  }
  
  /**
   * @description 触发按钮操作
   */
  actionTrigger = (triggerId, record, type) => {
    const { Tab, BID, btn, selectedData, setting } = this.props
    const { loading, disabled } = this.state
 
    if (loading || disabled) return
    if (triggerId) {
      if (btn.uuid !== triggerId) return
      if (this.props.lineId && record && record[0] && this.props.lineId !== record[0].$$key) {
        return
      }
    }
 
    if (((Tab && Tab.supMenu) || setting.supModule) && !BID) {
      notification.warning({
        top: 92,
        message: '需要上级主键值!',
        duration: 5
      })
      return
    } else if (type === 'linkbtn' && selectedData && selectedData.length === 1) {
      if (record[0].$Index !== selectedData[0].$Index) {
        return
      }
    }
 
    this.setState({autoMatic: type === 'autoMatic'})
 
    let _this = this
    let data = record || selectedData || []
 
    if (btn.Ot !== 'notRequired' && data.length === 0) {
      // 需要选择行时,校验数据
      notification.warning({
        top: 92,
        message: this.state.dict['main.action.confirm.selectline'],
        duration: 5
      })
      return
    } else if (btn.Ot === 'requiredSgl' && data.length !== 1) {
      // 需要选择单行时,校验数据
      notification.warning({
        top: 92,
        message: this.state.dict['main.action.confirm.selectSingleLine'],
        duration: 5
      })
      return
    } else if (!['requiredSgl', 'notRequired', 'requiredOnce', 'required'].includes(btn.Ot)) {
      // 数据选择类型校验
      this.actionSettingError()
      return
    } else if (
      !btn.verify ||
      (btn.verify.printMode === 'normal' && (!btn.verify.Template || !btn.verify.linkUrl)) ||
      (btn.verify.printMode === 'custom' && (!btn.verify.printFunc || !btn.verify.linkUrl))
    ) {
      notification.warning({
        top: 92,
        message: '请完善打印验证信息!',
        duration: 5
      })
      return
    }
 
    this.setState({
      selines: data
    })
 
    if (btn.execMode === 'pop') {
      let modal = this.state.btnconfig
      if (!modal && btn.modal) {
        modal = this.handleModelConfig(btn.modal)
      }
 
      this.setState({
        loading: true,
        btnconfig: modal
      }, () => {
        this.improveAction()
      })
    } else if (btn.execMode === 'prompt') {
      this.setState({ loading: true })
      confirm({
        title: this.state.dict['main.action.confirm.tip'],
        onOk() {
          _this.triggerPrint(data)
        },
        onCancel() {
          _this.setState({ loading: false })
        }
      })
    } else {
      this.triggerPrint(data)
    }
 
    if (window.GLOB.systemType === 'production') {
      MKEmitter.emit('queryTrigger', {menuId: btn.uuid, name: '标签打印'})
    }
  }
 
  /**
   * @description 触发打印
   */
  triggerPrint = (data, formlist = []) => {
    const { btn } = this.props
    let formdata = {}
    
    formlist.forEach(_data => {
      formdata[_data.key] = _data.value
    })
 
    let printlist = []
    let templates = []
    let printCount = +(formdata.printCount || formdata.PrintCount || formdata.printcount || formdata.Printcount || 1)
 
    if (isNaN(printCount) || printCount < 1) {
      printCount = 1
    }
 
    new Promise(resolve => {
      if (btn.intertype === 'system') { // 使用系统时,直接从表格或表单中选取数据
        let printcell = {}
 
        printcell.printType = formdata.printType || formdata.PrintType || formdata.printtype || formdata.Printtype || ''
        printcell.printCount = printCount
        printcell.templateID = btn.verify.Template || ''
 
        if (btn.Ot === 'notRequired') {
          printcell.data = [formdata]
        } else {
          printcell.data = data.map(cell => {
            return {...cell, ...formdata}
          })
        }
 
        templates.push(printcell.templateID)
 
        printlist.push(printcell)
 
        resolve(true)
      } else {
        this.getprintdata(btn, data, formdata, formlist).then(result => {
          if (result.next) {
            result.list.forEach(cell => {
              // 系统打印数据,校验data字段
              if (btn.verify.printMode !== 'custom' && (!cell.data || cell.data.length === 0)) return
 
              cell.templateID = cell.templateID || cell.TemplateID || cell.Templateid || cell.templateid || btn.verify.Template
              cell.printType = cell.printType || cell.PrintType || cell.printtype || cell.Printtype || formdata.printType || formdata.PrintType || formdata.printtype || formdata.Printtype || ''
 
              let _printCount = +(cell.printCount || cell.PrintCount || cell.printcount || cell.Printcount || 0)
 
              if (isNaN(_printCount) || _printCount < 1) {
                _printCount = printCount
              }
              
              cell.printCount = _printCount
 
              templates.push(cell.templateID)
 
              printlist.push(cell)
            })
          }
          
          resolve(result.next)
        })
      }
    }).then(res => {
      // 获取打印模板 getTemp
      if (!res) return false
 
      if (btn.verify.printMode === 'custom') {
        this.execCustomPrint(printlist, formdata)
 
        return false
      }
 
      templates = Array.from(new Set(templates)) // 去重
 
      let deffers = templates.map(tempId => {
        return new Promise(resolve => {
          let param = {
            func: 's_PrintTemplateMGetData',
            Type: 'Y',
            // ID: tempId, // 添加模板时,保存及查询使用模板参数
            PrintTempNO: tempId
          }
    
          if (window.GLOB.mainSystemApi) { // 从单点登录服务器取打印配置信息
            param.rduri = window.GLOB.mainSystemApi
          }
    
          Api.getLocalConfig(param).then(result => {
            result.tempId = tempId
            resolve(result)
          })
        })
      })
 
      return Promise.all(deffers)
    }).then(result => {
      if (!result) return
 
      let errorMsg = ''
      let _temps = {}
      let images = []
 
      result.forEach(res => {
        if (res.status && !errorMsg) {
          let _temp = this.getPrintConfigParam(res)
 
          if (_temp.error) {
            errorMsg = {
              ErrCode: 'N',
              message: _temp.error,
              ErrMesg: _temp.error,
              status: false
            }
          } else {
            images = [...images, ..._temp.imgs]
            _temps[res.tempId] = _temp
          }
        } else if (!errorMsg) {
          errorMsg = res
        }
      })
 
      if (!errorMsg) {
        if (images.length > 0) {
          let errorUrls = []
          images.forEach(url => {
            let img = new Image()
            img.onerror = () => {
              errorUrls.push(url)
            }
            img.src = url
          })
 
          setTimeout(() => {
            if (errorUrls.length > 0) {
              notification.warning({
                top: 92,
                message: '模板中图片 ' + errorUrls.join(',') + ' 已失效!',
                duration: 5
              })
              Object.keys(_temps).forEach(key => {
                _temps[key].config.ReportHeader.Control = _temps[key].config.ReportHeader.Control.map(item => {
                  if (item.Type === 'image' && errorUrls.includes(item.Value)) {
                    item.Value = ''
                  }
                  return item
                })
              })
            }
 
            this.execPrint(printlist, _temps, formdata)
          }, 500)
        } else {
          this.execPrint(printlist, _temps, formdata)
        }
      } else {
        this.execError(errorMsg)
      }
    })
  }
 
  /**
   * @description 自定义打印,解析自定义js
   */
  execCustomPrint = (printlist, formdata) => {
    const { btn } = this.props
 
    this.execSuccess({
      ErrCode: '-1',
      message: '',
      ErrMesg: '',
      status: true
    })
 
    try {
      // eslint-disable-next-line
      let func = new Function('data', 'form', 'printer', 'notification', 'Api', 'systemType', btn.verify.printFunc)
      func(printlist, formdata, btn.verify, notification, Api, window.GLOB.systemType)
 
      // 自定义打印示例
      // let defaultPrinter = printer.defaultPrinter || 'lackprinter'
      // let printers = {}
      // let getuuid = () => {
      //   let uuid = []
      //   let _options = '0123456789abcdefghigklmnopqrstuv'
      //   for (let i = 0; i < 32; i++) {
      //     uuid.push(_options.substr(Math.floor(Math.random() * 0x20), 1))
      //   }
      //   return uuid.join('')
      // }
      // if (printer.printerTypeList && printer.printerTypeList.length > 0) {
      //   printer.printerTypeList.forEach(cell => {
      //     if (cell.printer) {
      //       printers[cell.Value] = cell.printer
      //     }
      //   })
      // }
 
      // let jdList = [];
      // let jdNewList = [];
      // let otherList = [];
      // let _map = new Map()
      // data.forEach(m => {
      //   if (!m.print_data || m.print_data.length === 0) return
        
      //   m.print_data.forEach(n => {
      //     if (n.InsideBill) {
      //       if (_map.has(n.InsideBill)) {
      //         return
      //       }
      //       _map.set(n.InsideBill, true)
      //     }
      //     if (n.CustomData) {
      //       n.CustomData = JSON.parse(n.CustomData.replace(/\n/g,"\\n").replace(/\r/g,"\\r"))
      //     }
 
      //     if (n.hasOwnProperty('StdTemplate')) {
      //       jdNewList.push(n);
      //       return
      //     } else if (!n.PrintData) {
      //       return
      //     }
 
      //     n.PrintData = JSON.parse(n.PrintData.replace(/\n/g,"\\n").replace(/\r/g,"\\r"))
      //     n.PrintData.data = {...form, ...n.PrintData.data}
 
      //     if (n.PrintData.ectype === 'jdpop') {
      //       jdList.push(n)
      //     } else {
      //       otherList.push(n)
      //     }
      //   })
      // })
 
      // if (jdList.length === 0 && otherList.length === 0 && jdNewList.length === 0) {
      //   notification.warning({
      //     top: 92,
      //     message: '无打印数据!',
      //     duration: 5
      //   })
      //   return
      // }
 
      // let execPrint = (list, linkUrl, type) => {
      //   let printdata = {};
      //   let printerList = [];
 
      //   if (type === 'jd') {
      //     printerList = list.map(m => {
      //       let _printer = defaultPrinter;
 
      //       if (m.printType && printers[m.printType]) {
      //         _printer = printers[m.printType];
      //       }
 
      //       return {
      //         orderType: "print", 
      //         parameters: {
      //           printName: _printer === 'lackprinter' ? '' : _printer,
      //           tempUrl: m.StdTemplate,
      //           customTempUrl: m.CusTemplate,
      //           customData: [m.CustomData],
      //           printData: [m.PrintData]
      //         } 
      //       }
      //     })
      //   } else {
      //     list.forEach(res => {
      //       let _printer = defaultPrinter
 
      //       if (res.printType && printers[res.printType]) {
      //         _printer = printers[res.printType]
      //       }
 
      //       printdata[_printer] = printdata[_printer] || []
 
      //       printdata[_printer].push(res)
      //     })
 
      //     Object.keys(printdata).forEach(printer => {
      //       let _documents = []
      //       printdata[printer].forEach(item => {
      //         let _cell = {
      //           documentID: getuuid(),
      //           contents: []
      //         }
 
      //         if (item.PrintData) {
      //           _cell.contents.push(item.PrintData)
      //         }
      //         if (item.CustomData) {
      //           _cell.contents.push(item.CustomData)
      //         }
 
      //         _documents.push(_cell)
      //       })
      //       printerList.push({
      //         cmd: 'print',
      //         requestID: '',
      //         version: '',
      //         task: {
      //           taskID: getuuid(),
      //           preview: false,
      //           printer: printer === 'lackprinter' ? '' : printer,
      //           documents: _documents
      //         }
      //       })
      //     })
      //   }
 
      //   let socket = new WebSocket('ws://' + linkUrl)
 
      //   // 打开Socket
      //   socket.onopen = () =>{
      //       printerList.forEach((cell, i) => {
      //         setTimeout(() => {
      //           socket.send(JSON.stringify(cell).replace(/\\r/g,"\r").replace(/\\n/g,"\n"))
      //       }, 1000 * i)
      //       });
 
      //       notification.success({
      //         top: 92,
      //         message: '打印请求已发出。',
      //         duration: 2
      //       })
      //   }
      //   // 监听消息
      //   socket.onmessage = (event) => {
      //     let data = ''
 
      //     if (event.data) {
      //       try {
      //         data = JSON.parse(event.data)
      //       } catch (e) {
      //         notification.warning({
      //           top: 92,
      //           message: event.data,
      //           duration: 10
      //         })
      //         data = ''
      //       }
      //     }
 
      //     if (data && data.message && !data.status) {
      //       notification.warning({
      //         top: 92,
      //         message: data.message,
      //         duration: 10
      //       })
      //     }
      //   }
 
      //   socket.onerror = () => {
      //     notification.warning({
      //       top: 92,
      //       message: '无法连接到:' + linkUrl,
      //       duration: 10
      //     })
      //   }
      // }
 
      // if (jdNewList.length > 0) {
      //   execPrint(jdNewList, '127.0.0.1:9113', 'jd');
      // }
      // if (jdList.length > 0) {
      //   execPrint(jdList, '127.0.0.1:13529')
      // }
      // if (otherList.length > 0) {
      //   execPrint(otherList, '127.0.0.1:13528')
      // }
    } catch (e) {
      console.warn(e)
 
      try {
        // eslint-disable-next-line
        let evalfunc = eval('(true && function (data, form, printer, notification, Api, systemType) {' + btn.verify.printFunc + '})')
        evalfunc(printlist, formdata, btn.verify, notification, Api, window.GLOB.systemType)
      } catch (error) {
        console.warn(error)
        notification.warning({
          top: 92,
          message: '自定义函数执行错误!',
          duration: 5
        })
      }
    }
  }
 
  /**
   * @description 获取打印数据
   */
  getprintdata = (btn, data, formdata, formlist) => {
    const { setting } = this.props
 
    let _list = []
    return new Promise(resolve => {
      let params = []
      let param = {}
 
      if (this.props.BID) {
        param.BID = this.props.BID
      }
 
      if (btn.Ot === 'notRequired') {
        let _param = { ...param, ...formdata }
        params.push(_param)
      } else if (btn.Ot === 'requiredSgl') {
        if (setting.primaryKey) {
          param[setting.primaryKey] = data[0][setting.primaryKey]
        }
 
        let _param = { ...param, ...formdata }
 
        params.push(_param)
      } else if (btn.Ot === 'requiredOnce') {
        if (setting.primaryKey) {
          let ids = data.map(d => { return d[setting.primaryKey]})
          ids = ids.filter(Boolean)
          ids = ids.join(',')
  
          param[setting.primaryKey] = ids
        }
 
        let _param = { ...param, ...formdata }
 
        params.push(_param)
      } else if (btn.Ot === 'required') {
        params = data.map((cell, index) => {
          let _param = { ...param }
          
          if (setting.primaryKey) {
            _param[setting.primaryKey] = cell[setting.primaryKey]
          }
 
          formlist.forEach(_data => {
            if (index !== 0 && _data.readin && cell.hasOwnProperty(_data.key)) {
              _param[_data.key] = cell[_data.key]
            } else {
              _param[_data.key] = _data.value
            }
          })
          return _param
        })
      }
 
      if (btn.intertype === 'inner') {
        params = params.map(_param => {
          _param.func = btn.innerFunc
 
          return _param
        })
 
        if (params.length <= 20) {
          let deffers = params.map(par => {
            return new Promise(resolve => {
              Api.genericInterface(par).then(res => {
                resolve(res)
              })
            })
          })
          Promise.all(deffers).then(result => {
            let errorMsg = ''
            result.forEach(res => {
              if (!res.status) {
                errorMsg = res
              }
            })
            if (!errorMsg) {
              resolve({next: true, list: result})
            } else {
              this.execError(errorMsg)
              resolve({next: false, list: []})
            }
          })
        } else {
          this.printInnerLoopRequest(params, btn, _list, resolve)
        }
      } else {
        this.printOuterLoopRequest(params, btn, _list, resolve)
      }
    })
  }
 
  /**
   * @description 外部请求循环执行
   */
  printOuterLoopRequest = (params, btn, _list, _resolve) => {
    let param = params.shift()
    let _outParam = null
 
    new Promise(resolve => {
      // 内部请求
      if (btn.innerFunc) {
        param.func = btn.innerFunc
        // 存在内部函数时,数据预处理
        Api.genericInterface(param).then(res => {
          if (res.status) {
            delete res.ErrCode
            delete res.ErrMesg
            delete res.message
            delete res.status
 
            // 使用处理后的数据调用外部接口
            let keys = Object.keys(res) // 提交外部接口前,添加BID
            if (this.props.BID && keys.filter(key => key.toLowerCase() === 'bid').length === 0) {
              res.BID = this.props.BID
            }
            
            resolve(res)
          } else {
            this.execError(res)
            resolve(false)
            _resolve({next: false, list: []})
          }
        })
      } else {
        resolve(param)
      }
    }).then(res => {
      if (!res) return
      // 外部请求
      _outParam = JSON.parse(JSON.stringify(res))
 
      if (this.props.menuType === 'HS') {
        if (btn.sysInterface === 'true' && options.cloudServiceApi) {
          res.rduri = options.cloudServiceApi
        } else if (btn.sysInterface !== 'true') {
          if (window.GLOB.systemType === 'production' && btn.proInterface) {
            res.rduri = btn.proInterface
          } else {
            res.rduri = btn.interface
          }
        }
      } else {
        if (btn.sysInterface === 'true' && window.GLOB.mainSystemApi) {
          res.rduri = window.GLOB.mainSystemApi
        } else if (btn.sysInterface !== 'true') {
          if (window.GLOB.systemType === 'production' && btn.proInterface) {
            res.rduri = btn.proInterface
          } else {
            res.rduri = btn.interface
          }
        }
      }
 
      if (btn.outerFunc) {
        res.func = btn.outerFunc
      }
 
      return Api.genericInterface(res)
    }).then(response => {
      if (!response) return
 
      if (btn.callbackFunc) {
        // 存在回调函数时,调用
        delete response.message
        delete response.status
 
        response.func = btn.callbackFunc
 
        let _callbackparam = {..._outParam, ...response}
 
        return Api.genericInterface(_callbackparam)
      } else if (response.status) {
 
        _list.push(response)
 
        // 一次请求成功,进行下一项请求
        if (params.length === 0) {
          _resolve({next: true, list: _list})
        } else {
          this.printOuterLoopRequest(params, btn, _list, _resolve)
        }
      } else {
        this.execError(response)
        _resolve({next: false, list: []})
      }
    }).then(response => {
      if (!response) return
 
      if (response.status) {
        _list.push(response)
 
        // 一次请求成功,进行下一项请求
        if (params.length === 0) {
          _resolve({next: true, list: _list})
        } else {
          this.printOuterLoopRequest(params, btn, _list, _resolve)
        }
      } else {
        this.execError(response)
        _resolve({next: false, list: []})
      }
    })
  }
 
  /**
   * @description 内部请求循环执行
   */
  printInnerLoopRequest = (params, btn, _list, _resolve) => {
    let param = params.shift()
 
    Api.genericInterface(param).then(res => {
      if (res.status) {
        _list.push(res)
 
        if (params.length === 0) {
          _resolve({next: true, list: _list})
        } else {
          this.printInnerLoopRequest(params, btn, _list, _resolve)
        }
      } else {
        this.execError(res)
        _resolve({next: false, list: []})
      }
    })
  }
 
  getPrintConfigParam = (res) => {
    let error = ''         // 错误信息
    let configParam = ''   // 模板配置信息
    let _configparam = ''  // 打印配置信息
    let fields = []        // 模板中所需字段
    let nonEFields = []    // 非空字段
    let imgs = []
 
    if (!res.ConfigParam) {
      error = '未获取到打印模板信息!'
    } else {
      try {
        configParam = JSON.parse(window.decodeURIComponent(window.atob(res.ConfigParam)))
      } catch (e) {
        configParam = ''
      }
 
      if (!configParam) {
        error = '打印模板解析错误!'
      } else {
        let control = configParam.elements.map(element => {
          let _field = element.field
 
          if (_field === 'other_field') {
            _field = element.cusfield || ''
          }
 
          let item = {
            Name: element.name || '',
            Type: element.type,
            Value: element.value || '',
            Field: _field,
            Left: element.left,
            Top: element.top,
            Width: element.width,
            Height: element.height,
            Rotate: element.rotate,
            BorderSize: element.borderSize / 10,
            BorderColor: element.borderColor,
            Align: element.align,
            VerticalAlign: element.vertialAlign,
            BackColor: element.background,
            ForeColor: 'black'
          }
  
          if (!item.Width || !item.Height) {
            item.Type = 'line'
            item.Value = ''
            item.Field = ''
            item.FontFamily = element.fontFamily || ''
            item.FontSize = element.fontSize || ''
            item.FontStyle = (!element.fontWeight || element.fontWeight === 'normal') ? 'regular' : element.fontWeight
            item.Padding = 0
            item.Trimming = ''
            if (!item.Width) {
              item.Width = item.BorderSize
              item.Left = item.Left - item.Width
            } else if (!item.Height) {
              item.Height = item.BorderSize
              item.Top = item.Top - item.Height
            }
            item.BorderSize = 0
          } else if (item.Type === 'image') {
            item.ImageWidth = element.imgWidth
            item.ImageHeight = element.imgHeight
            item.Trimming = ''
            if (element.productValue && window.GLOB.systemType === 'production') {
              item.Value = element.productValue
              imgs.push(item.Value)
            } else if (item.Value) {
              imgs.push(item.Value)
            }
          } else if (item.Type === 'text') {
            item.FontFamily = element.fontFamily
            item.FontSize = element.fontSize
            item.FontStyle = element.fontWeight === 'normal' ? 'regular' : element.fontWeight
            item.Padding = element.padding / 2
            item.Trimming = ''
          } else if (item.Type === 'barcode') {
            item.BarcodeType = element.barcodeType
            item.BarcodeWidth = element.barcodeWidth
            item.BarcodeHeight = element.barcodeHeight
            item.BarcodeLabel = element.barcodeLabel
            item.LabelSize = element.fontSize
          } else if (item.Type === 'qrcode') {
            item.Type = 'barcode'
            item.BarcodeType = element.qrcodeType
            item.BarcodeWidth = element.qrcodeWidth
            item.BarcodeHeight = element.qrcodeWidth
            item.BarcodeLabel = false
          }
 
          if (item.Field) {
            fields.push(item.Field)
            // 条码二维码字段不可为空
            if (item.Type === 'qrcode' || item.Type === 'barcode') {
              nonEFields.push(item.Field)
            }
          }
 
          return item
        })
 
        _configparam = {
          Version: '',
          Title: configParam.name,
          Author: sessionStorage.getItem('UserID'),
          Description: configParam.remark,
          PrintTempNO: configParam.PrintTempNO,
          PageSetting: {
            Width: configParam.width,
            Height: configParam.height,
            Left: '0',
            Right: '0',
            Top: '0',
            Bottom: '0',
            Landscape: false
          },
          PageHeader: [],
          ReportHeader: {
            Control: control
          },
          ReportFooter: [],
          PageFooter: []
        }
      }
    }
 
    return {
      error: error,
      config: _configparam,
      fields: fields,
      nonEFields: nonEFields,
      imgs: imgs
    }
  }
 
  execPrint = (list, template, formdata) => {
    const { btn } = this.props
    let _errors = []
    
    let defaultPrinter = btn.verify.defaultPrinter || 'lackprinter'
    let printers = {}
    if (btn.verify.printerTypeList && btn.verify.printerTypeList.length > 0) {
      btn.verify.printerTypeList.forEach(cell => {
        if (cell.printer) {
          printers[cell.Value] = cell.printer
        }
      })
    }
 
    let printdata = {}
 
    list.forEach(res => {
      let _printer = defaultPrinter
 
      if (res.printType && printers[res.printType]) {
        _printer = printers[res.printType]
      }
 
      printdata[_printer] = printdata[_printer] || []
 
      printdata[_printer].push(res)
    })
 
    let printerList = []
 
    Object.keys(printdata).forEach(printer => {
      Object.keys(template).forEach(key => {
        let _datalist = printdata[printer].filter(cell => cell.templateID === key)
 
        if (_datalist.length === 0) return
 
        let _data = []
        _datalist.forEach(res => {
          res.data.forEach(_cell => {
            for (let i = 0; i < res.printCount; i++) {
              _data.push({...formdata, ..._cell})
            }
          })
        })
 
        let _fields = Array.from(new Set(template[key].fields))
        let _nonEFields = Array.from(new Set(template[key].nonEFields))
        let lacks = []
        let emptys = []
 
        _data.forEach(d => {
          _fields.forEach(f => {
            if (!d.hasOwnProperty(f)) {
              lacks.push(f)
            } else if (_nonEFields.includes(f) && !d[f] && d[f] !== 0) {
              emptys.push(f)
            }
          })
        })
 
        if (lacks.length > 0 || emptys.length > 0) {
          lacks = Array.from(new Set(lacks))
          emptys = Array.from(new Set(emptys))
 
          _errors.push({
            title: template[key].config.Title,
            lacks: lacks,
            emptys: emptys
          })
        }
 
        let results = []
        let num = 100
        for(let i = 0, len = _data.length; i < len; i += num){
          results.push(_data.slice(i, i + num))
        }
 
        results.forEach(result => {
          let _cell = {
            documentID: Utils.getuuid(),
            contents: [
              {
                data: result,
                templateURL: JSON.stringify(template[key].config)
              }
            ]
          }
  
          printerList.push({
            cmd: 'print',
            requestID: Utils.getuuid(),
            version: Utils.getuuid(),
            task: {
              taskID: Utils.getuuid(),
              preview: false,
              printer: printer === 'lackprinter' ? '' : printer,
              documents: [_cell]
            }
          })
        })
      })
    })
 
    if (list.length === 0) {
      this.execError({
        ErrCode: 'N',
        message: '未获取到打印信息!',
        ErrMesg: '',
        status: false
      })
      return
    } else if (_errors.length > 0) {
      let lackerror = []
      let emptyerror = []
 
      _errors.forEach(err => {
        if (err.lacks.length > 0) {
          lackerror.push(`数据中未获取到模板(${err.title})${err.lacks.join('、')} 字段`)
        }
        if (err.emptys.length > 0) {
          emptyerror.push(`数据中模板(${err.title}) ${err.emptys.join('、')} 字段不可为空`)
        }
      })
 
      let msg = []
      if (lackerror.length > 0) {
        msg.push(lackerror.join(' ; '))
      }
 
      if (emptyerror.length > 0) {
        msg.push(emptyerror.join(' ; '))
      }
 
      this.execError({
        ErrCode: 'N',
        message: msg.join(' ; ') + ' !',
        ErrMesg: '',
        status: false
      })
      return
    }
 
    // let lackItems = printerList.filter(cell => cell.task.printer === 'lackprinter')[0]
 
    if (!socket || socket.readyState !== 1 || socket.url !== 'ws://' + btn.verify.linkUrl) {
      socket = new WebSocket('ws://' + btn.verify.linkUrl)
    } else {
      // if (lackItems) {
      //   let request  = {
      //     requestID: '',
      //     version: '',
      //     cmd: 'getPrinters'
      //   }
      //   socket.send(JSON.stringify(request))
      // } else {
        this.syncMessageSend(printerList)
 
        this.execSuccess({
          ErrCode: 'S',
          message: '',
          ErrMesg: '打印请求已发出。',
          status: true
        })
      // }
    }
 
    // 打开Socket
    socket.onopen = () =>{
      // if (lackItems) {
      //   let request  = {
      //     requestID: '',
      //     version: '',
      //     cmd: 'getPrinters'
      //   }
      //   socket.send(JSON.stringify(request))
      // } else {
        this.syncMessageSend(printerList)
 
        this.execSuccess({
          ErrCode: 'S',
          message: '',
          ErrMesg: '打印请求已发出。',
          status: true
        })
      // }
    }
    // 监听消息
    socket.onmessage = (event) => {
      let data = ''
 
      if (event.data) {
        try {
          data = JSON.parse(event.data)
        } catch (e) {
          this.execError({
            ErrCode: 'N',
            message: event.data,
            ErrMesg: '',
            status: false
          })
 
          data = ''
        }
      }
 
      // if (data && data.cmd === 'getPrinters' && data.status) {
      //   printerList = printerList.map(cell => {
      //     if (cell.task.printer === 'lackprinter') {
      //       cell.task.printer = data.defaultPrinter
      //     }
      //     return cell
      //   })
 
      //   this.syncMessageSend(printerList)
 
      //   this.execSuccess({
      //     ErrCode: 'S',
      //     message: '',
      //     ErrMesg: '打印请求已发出。',
      //     status: true
      //   })
      // } else if (data && data.message && !data.status) {
      if (data && data.message && !data.status) {
        this.execError({
          ErrCode: 'N',
          message: data.message,
          ErrMesg: '',
          status: false
        })
      }
    }
 
    socket.onerror = () => {
      this.execError({
        ErrCode: 'N',
        message: '无法连接到:' + btn.verify.linkUrl,
        ErrMesg: '',
        status: false
      })
    }
  }
 
  syncMessageSend = (list) => {
    let param = list.shift()
 
    if (socket && param) {
      socket.send(JSON.stringify(param))
    }
 
    if (list && list.length > 0) {
      setTimeout(() => {this.syncMessageSend(list)}, 3000)
    }
  }
  /**
   * @description 操作成功后处理
   * 1、excel导出,成功后取消导出按钮加载中状态
   * 2、状态码为 S 时,显示成功信息后系统默认信息
   * 3、状态码为 -1 时,不显示任何信息
   * 4、模态框执行成功后是否关闭
   * 5、通知主列表刷新
   */
  execSuccess = (res) => {
    const { btn } = this.props
    const { autoMatic } = this.state
 
    if ((res && (res.ErrCode === 'S' || !res.ErrCode)) || autoMatic) { // 执行成功
      notification.success({
        top: 92,
        message: res.ErrMesg || this.state.dict['main.action.confirm.success'],
        duration: btn.verify && btn.verify.stime ? btn.verify.stime : 2
      })
    } else if (res && res.ErrCode === 'Y') { // 执行成功
      Modal.success({
        title: res.ErrMesg || this.state.dict['main.action.confirm.success']
      })
    } else if (res && res.ErrCode === '-1') { // 完成后不提示
 
    }
 
    this.setState({
      loading: false
    })
 
    if (autoMatic) {
      MKEmitter.emit('autoExecOver', btn.uuid, 'success')
      return
    }
 
    if (btn.execSuccess !== 'never') {
      MKEmitter.emit('refreshByButtonResult', btn.$menuId, btn.execSuccess, btn, '', this.state.selines)
    }
  }
 
  /**
   * @description 操作失败后处理
   * 1、状态码为 E、N、F、NM 时,显示相应提示信息
   * 2、excel导出,失败后取消导出按钮加载中状态
   * 3、通知主列表刷新
   */
  execError = (res) => {
    const { btn } = this.props
    const { btnconfig, autoMatic } = this.state
 
    if (res.ErrCode === 'E' && !autoMatic) {
      Modal.error({
        title: res.message || res.ErrMesg,
      })
    } else if (res.ErrCode === 'N' || autoMatic) {
      notification.error({
        top: 92,
        message: res.message || res.ErrMesg,
        duration: btn.verify && btn.verify.ntime ? btn.verify.ntime : 10
      })
    } else if (res.ErrCode === 'F') {
      notification.error({
        className: 'notification-custom-error',
        top: 92,
        message: res.message || res.ErrMesg,
        duration: btn.verify && btn.verify.ftime ? btn.verify.ftime : 10
      })
    } else if (res.ErrCode === 'NM') {
      message.error(res.message || res.ErrMesg)
    }
    
    this.setState({
      loading: false
    })
 
    if (autoMatic) {
      MKEmitter.emit('autoExecOver', btn.uuid, 'error')
      return
    }
 
    if (btnconfig && btnconfig.setting && btnconfig.setting.errFocus) {
      MKEmitter.emit('mkFC', 'focus', btnconfig.setting.errFocus)
    }
 
    if (btn.execError !== 'never') {
      MKEmitter.emit('refreshByButtonResult', btn.$menuId, btn.execError, btn, '', this.state.selines)
    }
  }
 
  /**
   * @description 按钮配置信息错误提示
   */
  actionSettingError = () => {
    notification.warning({
      top: 92,
      message: this.state.dict['main.action.settingerror'],
      duration: 5
    })
  }
 
  handleModelConfig = (config) => {
    let roleId = sessionStorage.getItem('role_id') || '' // 角色ID
    config.fields = config.fields.map(cell => {
      // 数据源sql语句,预处理,权限黑名单字段设置为隐藏表单
      if (['select', 'link', 'multiselect', 'radio', 'checkbox', 'checkcard'].includes(cell.type) && cell.resourceType === '1') {
        let _option = Utils.getSelectQueryOptions(cell)
 
        cell.data_sql = Utils.formatOptions(_option.sql)
        cell.base_sql = window.btoa(window.encodeURIComponent(_option.sql))
        cell.arr_field = _option.field
      }
 
      // 字段权限黑名单
      if (!cell.blacklist || cell.blacklist.length === 0) return cell
      if (cell.blacklist.filter(v => roleId.indexOf(v) > -1).length > 0) {
        cell.hidden = 'true'
      }
 
      return cell
    })
    return config
  }
 
  /**
   * @description 获取按钮配置信息
   */
  improveAction = () => {
    const { btn } = this.props
    const { btnconfig, autoMatic } = this.state
 
    if (btnconfig) {
      if (!autoMatic && (btnconfig.setting.display === 'prompt' || btnconfig.setting.display === 'exec')) { // 如果表单以是否框展示
        this.modelconfirm()
      } else {
        this.setState({
          visible: true
        })
      }
    } else {
      Api.getCacheConfig({
        func: 'sPC_Get_LongParam',
        MenuID: btn.uuid
      }).then(res => {
        let _LongParam = ''
 
        if (res.status && res.LongParam) {
          try {
            _LongParam = JSON.parse(window.decodeURIComponent(window.atob(res.LongParam)))
          } catch (e) {
            console.warn('Parse Failure')
            _LongParam = ''
          }
        }
 
        if (!res.status) {
          notification.warning({
            top: 92,
            message: res.message,
            duration: 5
          })
          this.setState({ loading: false })
        } else if (!_LongParam || (btn.execMode === 'pop' && _LongParam.type !== 'Modal')) {
          notification.warning({
            top: 92,
            message: '未获取到按钮配置信息!',
            duration: 5
          })
          this.setState({ loading: false })
        } else {
          _LongParam = updateForm(_LongParam)
          _LongParam = this.handleModelConfig(_LongParam)
 
          this.setState({
            btnconfig: _LongParam
          }, () => {
            if (!autoMatic && (_LongParam.setting.display === 'prompt' || _LongParam.setting.display === 'exec')) { // 如果表单以是否框展示
              this.modelconfirm()
            } else {
              this.setState({
                visible: true
              })
            }
          })
        }
      })
    }
  }
 
  /**
   * @description 模态框(表单),确认
   */
  handleOk = () => {
    const { btnconfig, autoMatic } = this.state
 
    if (!this.formRef) return
 
    this.formRef.handleConfirm().then(res => {
      if (btnconfig.setting.finish !== 'unclose' || autoMatic) {
        this.setState({
          visible: false
        })
      }
      this.triggerPrint(this.state.selines, res)
    })
  }
 
  /**
   * @description 模态框(表单),取消
   */
  handleCancel = () => {
    this.setState({
      loading: false,
      visible: false
    })
  }
 
  modelconfirm = () => {
    const { BData } = this.props
    const { btnconfig, selines } = this.state
    let _this = this
    let result = []
    
    btnconfig.fields.forEach(item => {
      if (!item.field) return
      let _readin = item.readin !== 'false'
      let _initval = item.initval
 
      if (item.type === 'linkMain' || item.type === 'funcvar') {
        _readin = false
      }
 
      if (item.type === 'linkMain' && BData && BData.hasOwnProperty(item.field)) {
        _initval = BData[item.field]
      } else if (_readin && selines[0] && selines[0].hasOwnProperty(item.field)) {
        _initval = selines[0][item.field]
      } else if (item.type === 'date' && _initval) {
        _initval = moment().subtract(_initval, 'days').format('YYYY-MM-DD')
      } else if (item.type === 'datemonth' && _initval) {
        _initval = moment().subtract(_initval, 'month').format('YYYY-MM')
      } else if (item.type === 'datetime' && _initval) {
        _initval = moment().subtract(_initval, 'days').format('YYYY-MM-DD HH:mm:ss')
      }
 
      let _fieldlen = item.fieldlength || 50
      if (item.type === 'textarea' || item.type === 'fileupload' || item.type === 'multiselect') {
        _fieldlen = item.fieldlength || 512
      } else if (item.type === 'number') {
        _fieldlen = item.decimal ? item.decimal : 0
      } else if (item.type === 'rate') {
        item.rateCount = item.rateCount || 5
        let allowHalf = item.allowHalf === 'true'
 
        if (allowHalf) {
          _initval = parseFloat(_initval)
          if (_initval % 0.5 !== 0) {
            _initval = parseInt(_initval)
          }
        } else {
          _initval = parseInt(_initval)
        }
 
        if (isNaN(_initval) || _initval < 0) {
          _initval = 0
        } else if (_initval > item.rateCount) {
          _initval = item.rateCount
        }
      }
 
      if (_initval === undefined) {
        _initval = ''
      }
 
      result.push({
        key: item.field,
        readonly: item.readonly === 'true',
        readin: item.readin !== 'false' && item.readin !== 'top',
        fieldlen: _fieldlen,
        type: item.type,
        value: _initval
      })
    })
 
    if (btnconfig.setting.display === 'exec') {
      this.execSubmit(selines, () => {}, result)
    } else {
      confirm({
        title: this.state.dict['main.action.confirm.tip'],
        onOk() {
          _this.triggerPrint(selines, result)
        },
        onCancel() {
          _this.setState({ loading: false })
        }
      })
    }
  }
 
  /**
   * @description 显示模态框
   */
  getModels = () => {
    const { setting, BID, btn } = this.props
    const { btnconfig } = this.state
 
    if (!this.state.visible || !btnconfig || !btnconfig.setting) return null
 
    let title = btnconfig.setting.title
    let width = btnconfig.setting.width > 100 ? btnconfig.setting.width : btnconfig.setting.width + 'vw'
    let clickouter = false
    let container = document.body
 
    if (
      (setting.tabType === 'main' && btnconfig.setting.container === 'tab' && this.props.ContainerId) ||
      (btnconfig.setting.container === 'tab' && btn.ContainerId)
    ) {
      width = btnconfig.setting.width > 100 ? btnconfig.setting.width : btnconfig.setting.width + '%'
      container = () => document.getElementById(this.props.ContainerId || btn.ContainerId)
    }
 
    if (btnconfig.setting.clickouter === 'close') {
      clickouter = true
    }
 
    return (
      <Modal
        title={title}
        maskClosable={clickouter}
        getContainer={container}
        wrapClassName='action-modal'
        visible={this.state.visible}
        width={width}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        destroyOnClose
      >
        <MutilForm
          BID={BID}
          dict={this.state.dict}
          menuType={this.props.menuType}
          action={btnconfig}
          inputSubmit={this.handleOk}
          data={this.state.selines[0]}
          BData={this.props.BData}
          wrappedComponentRef={(inst) => this.formRef = inst}
        />
      </Modal>
    )
  }
 
  render() {
    const { btn, show } = this.props
    const { loadingNumber, loading, disabled, hidden } = this.state
 
    if (hidden) return null
 
    if (show === 'actionList') {
      return <div style={{display: 'inline-block'}} onClick={(e) => e.stopPropagation()}>
        <Button
          icon={btn.icon}
          loading={loading}
          disabled={disabled}
          title={disabled ? (btn.reason || '') : ''}
          className={'mk-btn mk-' + btn.class}
          onClick={() => {this.actionTrigger()}}
        >{loadingNumber ? `(${loadingNumber})` : '' + btn.label}</Button>
        {this.getModels()}
      </div>
    } else { // icon、text、 all 卡片
      let label = ''
      let icon = ''
 
      if (show === 'button') {
        label = btn.label
        icon = btn.icon || ''
      } else if (show === 'link') {
        label = <span>{btn.label}{btn.icon ? <MkIcon style={{marginLeft: '8px'}} type={btn.icon}/> : ''}</span>
        icon = ''
      } else if (show === 'icon') {
        icon = btn.icon || ''
      // } else if (show === 'text') {
      } else {
        label = btn.label
      }
 
      return <div style={{display: 'inline-block'}} onClick={(e) => e.stopPropagation()}>
        <Button
          type="link"
          title={disabled ? (btn.reason || '') : (show === 'icon' ? btn.label : '')}
          loading={loading}
          disabled={disabled}
          style={btn.style}
          icon={icon}
          onClick={() => {this.actionTrigger()}}
        >{label}</Button>
        {this.getModels()}
      </div>
    }
  }
}
 
const mapStateToProps = (state) => {
  return {
    menuType: state.editLevel
  }
}
 
const mapDispatchToProps = () => {
  return {}
}
 
export default connect(mapStateToProps, mapDispatchToProps)(PrintButton)