fs-danaus
2023-07-10 4849078e3450b8d3b3030a658a34dd58b0630fc5
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
package com.yc.api.controller;
 
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.yc.action.BaseAction;
import com.yc.action.grid.GridUtils;
import com.yc.action.grid.TreeGridDTO;
import com.yc.action.new38action.Type38action;
import com.yc.action.panval.DocNavigation;
import com.yc.action.upload.AttachmentAction;
import com.yc.action.upload.PostBeanInfo;
import com.yc.api.bean.*;
import com.yc.api.service.ApiServiceIfc;
import com.yc.api.utils.FileUtil;
import com.yc.entity.AttachmentConfig;
import com.yc.entity.DataSourceActionEntity;
import com.yc.entity.DataSourceEntity;
import com.yc.entity.UserAccountEntity;
import com.yc.exception.ApplicationException;
import com.yc.exception.CallBackMessage;
import com.yc.factory.FactoryBean;
import com.yc.ionic.action.LinksBean;
import com.yc.ionic.schedule.ZipUtil;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.sdk.WebSocketMessage.action.WebSocketMessageServer;
import com.yc.sdk.WebSocketMessage.entity.MessageInfo;
import com.yc.sdk.WebSocketMessage.entity.MessageType;
import com.yc.sdk.password.action.ChangePassword;
import com.yc.sdk.shopping.action.VerificationCodes;
import com.yc.sdk.shopping.action.api.InvitationCode;
import com.yc.service.BaseService;
import com.yc.service.approving.ApprovingEntity;
import com.yc.service.approving.ApprovingPwdIfc;
import com.yc.service.build.top.BuildTopIfc;
import com.yc.service.grid.GridServiceIfc;
import com.yc.service.impl.BaseDoIfc;
import com.yc.service.sqlformat.entity.SqlFormatEntity;
import com.yc.service.sqlformat.utils.SqlFormatUtils;
import com.yc.service.user.EquipmentEntry;
import com.yc.service.user.LoginEquipmentIfc;
import com.yc.service.user.UserAccountServiceIfc;
import com.yc.utils.EncodeUtil;
import com.yc.utils.SessionKey;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.WebAsyncTask;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
 
import static java.util.stream.Collectors.toList;
 
@Controller
public class ApiController extends BaseAction {
 
    @Autowired
    GridServiceIfc gridService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ThreadPoolTaskExecutor threadPoolExecutor;
    @Autowired
    ApiServiceIfc apiServiceIfc;
    @Autowired
    ApprovingPwdIfc approvingPwdIfc;
    @Autowired
    LoginEquipmentIfc loginEquipmentIfc;
    @Autowired
    BaseDoIfc baseDoIfc;
    private static String sysfunclink = "b.[origformid]            " +
            ",b.[origformtype]         " +
            ",b.[sortid]               " +
            ",b.[linklabel]            " +
            ",b.[linkformid]           " +
            ",b.[linkformtype]         " +
            ",b.[linkdescribe]         " +
            ",b.[linkmode]             " +
            ",b.[hotkey]               " +
            ",b.[spfield]              " +
            ",b.[close_origform]       " +
            ",b.[origfields]           " +
            ",b.[linkfields]           " +
            ",b.[orighdfields]         " +
            ",b.[linkhdfields]         " +
            ",b.[efilter]              " +
            ",b.[warnmessage]          " +
            ",b.[self_datafields]      " +
            ",b.[link_datafields]      " +
            ",b.[firstrecord_editmode] " +
            ",b.[return_one_record]    " +
            ",b.[numfieldid]           " +
            ",b.[locksqlwhere]         " +
            ",b.[showbutton]           " +
            ",b.[returndataset]        " +
            ",b.[refresh_origform]     " +
            ",b.[numfieldid_origform]  " +
            ",b.[noshowspmessage]      " +
            ",b.[linkformdisplayfields]" +
            ",b.[ftlockconditionflag]  " +
            ",b.[groupname]            " +
            ",b.[navigateyn]           " +
            ",b.[editstatus]           " +
            ",b.[isshowpwdedit]        " +
            ",b.[selectchecker]        " +
            ",b.[returncurchecker]     " +
            ",b.[returncurcheckername] " +
            ",b.[smallimagefilename]   " +
            ",b.[smallimagefilepath]   " +
            ",b.[ft]                   " +
            ",b.[ftformtype]           " +
            ",b.[fk]                   " +
            ",b.[seekgroupid]          " +
            ",b.[spremissfield]        " +
            ",b.[dpremissfield]        " +
            ",b.[fkefilter]            " +
            ",b.[isautosaved]          " +
            ",b.[showitemexpression]   " +
            ",b.[linkscope]            ";
 
    private static String gformFilter = "[formid]            " +
            ",[statisid]         " +
            ",[fieldid]          " +
            ",[fieldname]        " +
            ",[ft]               " +
            ",[ftformtype]       " +
            ",[emptyrefdata]     " +
            ",[fk]               " +
            ",[seekgroupid]      " +
            ",[spremissfield]    " +
            ",[dpremissfield]    " +
            ",[efilter]          " +
            ",[return_one_record]" +
            ",[numfieldid]        " +
            ",[visible]           " +
            ",[hidelabel]         " +
            ",[controltype]       " +
            ",[rowno]             " +
            ",[colno]             " +
            ",[lengthnum]         " +
            ",[heightnum]         " +
            ",[initvalue]         " +
            ",[compsingle]        " +
            ",[sqlscript]         " +
            ",[memo]              ";
    private static String sysmasterdetail = "[formid]   " +
            ",[detailformid]    " +
            ",[masterfield]     " +
            ",[masterkeys]      " +
            ",[detailkeys]      " +
            ",[mastersumfields] " +
            ",[detailsumfields] " +
            ",[detailreadonly]  " +
            ",[detailmemo]      " +
            ",[sequenceid]      " +
            ",[gridheight]      ";
 
    private static String systreeset = "[formid]              " +
            ",[formtype]           " +
            ",[treeformid]         " +
            ",[treeName]           " +
            ",[SortID]             " +
            ",[keyfield]           " +
            ",[parentfield]        " +
            ",[nodeid]             " +
            ",[listfield]          " +
            ",[displayfield]       " +
            ",[separatedst]        " +
            ",[treefield]          " +
            ",[autocodefield]      " +
            ",[treefilterstr]      " +
            ",[authcheck]          " +
            ",[allowdrag]          " +
            ",[defNodeTypeFilter]  " +
            ",[startnodetypefilter]" +
            ",[treewidth]";
 
    private static String TabPageFormid = "[mainformid]      " +
            ",[mainformname]   " +
            ",[FormGroupID]    " +
            ",[FormGroupName] " +
            ",[SortBy]        " +
            ",[formid]        " +
            ",[formname]      " +
            ",[formtype]      " +
            ",[LabelName]     " +
            ",[FT]            " +
            ",[FTName]        " +
            ",[FK]            " +
            ",[SeekGroupID]   " +
            ",[GridHeight]    " +
            ",[GroupID]       " +
            ",[GroupName]     " +
            ",[TabID]         " +
            ",[TabName]         " +
            ",[TabHeight]     " +
            ",[isStartupCollapsed]";
    private static String table3 =
            "a.[buttonID]              ," +
                    "a.[ButtonName]            ," +
                    "a.[formid]                ," +
                    "a.[headflag]              ," +
                    "a.[fieldid]               ," +
                    "a.[docitem]               ," +
                    "a.[ProcName]              ," +
                    "a.[Memo]                  ," +
                    "a.[isShowPwdEdit]         ," +
                    "a.[editStatus]            ," +
                    "a.[SelectChecker]         ," +
                    "a.[ReturnCurChecker]      ," +
                    "a.[ReturnCurCheckerName]  ," +
                    "a.[FT]                    ," +
                    "a.[FTFormType]            ," +
                    "a.[FK]                    ," +
                    "a.[SeekGroupID]           ," +
                    "a.[sPremissField]         ," +
                    "a.[dPremissField]         ," +
                    "a.[FKeFilter]             ," +
                    "a.[isAutoSaved]           ," +
                    "a.[showItemExpression]    ," +
                    "a.[isInspection]          ," +
                    "a.[isExchangeDataWithHost]," +
                    "a.[UrlShowLocation]       ," +
                    "a.[ExternalURL],           " +
                    "b.[IconPath],b.[isReturnToLastPage]          \n ";
 
    private String getDataType = "set nocount on select\n" +
            "col.COLUMN_NAME as ColumnName,\n" +
            "col.DATA_TYPE as DataType,\n" +
            "col.CHARACTER_OCTET_LENGTH as DataLength\n" +
            "--col.IS_NULLABLE as IsNullable,\n" +
            "--ccu.CONSTRAINT_NAME as IsPrimaryKey,\n" +
            "--de.value as Description\n" +
            "from INFORMATION_SCHEMA.COLUMNS col\n" +
            "left join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu\n" +
            "on ccu.TABLE_NAME=col.TABLE_NAME\n" +
            "and ccu.COLUMN_NAME=col.COLUMN_NAME\n" +
            "and ccu.CONSTRAINT_NAME like 'PK_%'\n" +
            "left join ::fn_listextendedproperty (NULL, 'user', 'dbo', 'table', ?,'column', default) as de\n" +
            "on col.COLUMN_NAME = de.objname COLLATE Chinese_PRC_CI_AS\n" +
            "where col.TABLE_NAME=?";
 
    /**
     * 出库扫序列号,检验是否与当前单据匹配
     * 1,如果不存在则返回错误,提示所扫的物料不在当前出库单
     * 2,如果有一个或多个结果,则返回给前端选择
     */
    @RequestMapping(value = "/qr/ScanSerialNumberOut.do")
    @ResponseBody
    public Object scanSerialNumberOut(@RequestBody SerialNumberEntity entity, HttpServletRequest request) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (StringUtils.isBlank(entity.getDocCode())) {
                throw new ApplicationException("单号不能为空");
            }
            if (StringUtils.isBlank(entity.getSerialNumber())) {
                throw new ApplicationException("序列号不能为空");
            }
            if (entity.getFormid() == null || entity.getFormid().intValue() == 0) {
                throw new ApplicationException("功能号不能为空");
            }
            if (entity.getFormType() == null || entity.getFormType().intValue() == 0) {
                throw new ApplicationException("功能类型不能为空");
            }
            final Map map = apiServiceIfc.getMatCodeBySerialNumberOut(entity);
 
            if (GridUtils.prossRowSetDataType_Int(map, "state") == 0) {
                if (GridUtils.prossRowSetDataType_Int(map, "Status") == 2) {
                    throw new ApplicationException(String.format("该序列号【%s】已经出库,不允许重复出库", entity.getSerialNumber()));
                }
                //表示序列号对应的物料存在于当前单据
                map.remove("state");
                callBackMessage.sendSuccessMessageByDefault();
                callBackMessage.setInfo(map);
            } else {
                //表示序列号对应的物料不存在于当前单据,拿错物料
                callBackMessage.sendErrorMessage("所扫物料不属于当前单据");
                map.remove("state");
                callBackMessage.setInfo(map);
            }
            return callBackMessage.toJSONObject();
        } catch (EmptyResultDataAccessException ex) {
            callBackMessage.sendErrorMessage(String.format("序列号【%s】不存在于当前库存,请检查", entity.getSerialNumber()));
            return callBackMessage.toJSONObject();
        } catch (Exception e) {
            callBackMessage.sendErrorMessage(e.getMessage());
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
 
    }
    /**
     * 盘点单扫序列号
     * 1,如果不存在则返回提示,前端显示物料列表,手动选择
     * 2,如果有一个或多个结果,则返回给前端选择
     */
    @RequestMapping(value = "/qr/ScanSerialNumberInventory.do")
    @ResponseBody
    public Object scanSerialNumberInventory(@RequestBody SerialNumberEntity entity, HttpServletRequest request) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (StringUtils.isBlank(entity.getDocCode())) {
                throw new ApplicationException("单号不能为空");
            }
            if (StringUtils.isBlank(entity.getSerialNumber())) {
                throw new ApplicationException("序列号不能为空");
            }
            if (entity.getFormid() == null || entity.getFormid().intValue() == 0) {
                throw new ApplicationException("功能号不能为空");
            }
            if (entity.getFormType() == null || entity.getFormType().intValue() == 0) {
                throw new ApplicationException("功能类型不能为空");
            }
            final Map map = apiServiceIfc.getMatCodeBySerialNumberInventory(entity);
 
            if (GridUtils.prossRowSetDataType_Int(map, "state") == 0) {
                if (GridUtils.prossRowSetDataType_Int(map, "Status") == 2) {
                    throw new ApplicationException(String.format("该序列号【%s】已经出库,不允许重复出库", entity.getSerialNumber()));
                }
                //表示序列号对应的物料存在于当前单据
                map.remove("state");
                callBackMessage.sendSuccessMessageByDefault();
                callBackMessage.setInfo(map);
            } else {
                //表示序列号对应的物料不存在于当前单据,拿错物料
                callBackMessage.sendErrorMessage("所扫物料不属于当前单据");
                map.remove("state");
                callBackMessage.setInfo(map);
            }
            return callBackMessage.toJSONObject();
        } catch (EmptyResultDataAccessException ex) {
            callBackMessage.sendErrorMessage(String.format("序列号【%s】不存在于当前库存,请检查", entity.getSerialNumber()));
            return callBackMessage.toJSONObject();
        } catch (Exception e) {
            callBackMessage.sendErrorMessage(e.getMessage());
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
 
    }
    /**
     * 入库扫序列号,检验是否与当前单据匹配
     * 1,如果不存在则返回错误,提示所扫的物料不在当前出库单
     * 2,如果有一个或多个结果,则返回给前端选择
     */
    @RequestMapping(value = "/qr/ScanSerialNumberIn.do")
    @ResponseBody
    public Object scanSerialNumberIn(@RequestBody SerialNumberEntity entity, HttpServletRequest request) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (StringUtils.isBlank(entity.getDocCode())) {
                throw new ApplicationException("单号不能为空");
            }
            if (StringUtils.isBlank(entity.getSerialNumber())) {
                throw new ApplicationException("序列号不能为空");
            }
            if (entity.getFormid() == null || entity.getFormid().intValue() == 0) {
                throw new ApplicationException("功能号不能为空");
            }
            if (entity.getFormType() == null || entity.getFormType().intValue() == 0) {
                throw new ApplicationException("功能类型不能为空");
            }
            if (StringUtils.isBlank(entity.getMatCode())) {
                throw new ApplicationException("物料编号不能为空");
            }
            Map map = apiServiceIfc.getMatCodeBySerialNumberIn(entity);
            if (GridUtils.prossRowSetDataType_Int(map, "state") == 0) {
                //表示序列号对应的物料存在于当前单据
                map.remove("state");
                callBackMessage.sendSuccessMessageByDefault();
                callBackMessage.setInfo(map);
            } else {
                //表示序列号已入库,弹出提示,不能录入
                throw new ApplicationException(String.format("该序列号【%s】已经存在,不允许重复入库", entity.getSerialNumber()));
            }
            return callBackMessage.toJSONObject();
        } catch (Exception e) {
            callBackMessage.sendErrorMessage(e.getMessage());
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
 
    }
 
    /**
     * 显示当前单据已扫的序列号列表
     */
    @RequestMapping(value = "/qr/showSerialNumberInfo.do")
    @ResponseBody
    public Object showSerialNumberInfo(@RequestBody SerialNumberEntity entity, HttpServletRequest request) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (StringUtils.isBlank(entity.getDocCode())) {
                throw new ApplicationException("单号不能为空");
            }
            if (entity.getFormid() == null || entity.getFormid().intValue() == 0) {
                throw new ApplicationException("功能号不能为空");
            }
            if (entity.getFormType() == null || entity.getFormType().intValue() == 0) {
                throw new ApplicationException("功能类型不能为空");
            }
            final List<T110503Entity> t110503Entities = apiServiceIfc.showSerialNumberList(entity);
            callBackMessage.setInfo(t110503Entities);
            callBackMessage.sendSuccessMessageByDefault();
            return callBackMessage.toJSONObject();
        } catch (Exception e) {
            callBackMessage.sendErrorMessage(e.getMessage());
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
 
    }
 
    /**
     * 取功能号在9801,9802的设置
     */
    @RequestMapping(value = "/formSetting.do", method = RequestMethod.GET)
    public void get9802Info(String formid, HttpServletRequest request, HttpServletResponse response) {
        String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        try {
            SpObserver.setDBtoInstance("_" + dbid);
            if (formid == null || "".equals(formid)) {
                CallBackMessage callBackMessage = new CallBackMessage();
                callBackMessage.sendErrorMessage("formid不能为空");
                this.printJson(response, callBackMessage.toString());
                return;
            }
 
            int int_formid = 0;
            int formType = 0;
            String[] content = formid.split(";");
            try {
                int_formid = Integer.parseInt(content[0]);
                if (content.length == 2) {
                    formType = Integer.parseInt(content[1]);
                }
            } catch (Exception e) {
                CallBackMessage callBackMessage = new CallBackMessage();
                callBackMessage.sendErrorMessage(e.getMessage());
                this.printJson(response, callBackMessage.toString());
                return;
            }
            Map<String, Object> map = new HashMap<String, Object>();
            if (formType == 0) {
                try {
                    formType = gridService.getWindowTypeByGform(int_formid);
                } catch (Exception e) {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage(int_formid + "在9810查找不到窗体类型信息" + e.getMessage());
                    this.printJson(response, callBackMessage.toString());
                    return;
                }
            }
            map.put("formType", formType);
            //主从表表名
            String hdTable = "";//主表
            String dtTable = "";//从表
            Map<String, Object> gform = gridService.getSimpleJdbcTemplate().queryForMap(gridService.getGET_GFORM().toLowerCase(), int_formid);
            map.put("9801", gform);
            hdTable = GridUtils.prossRowSetDataType_String(gform, "hdtable");
            dtTable = GridUtils.prossRowSetDataType_String(gform, "dttable");
 
            map.put("9802", gridService.getSimpleJdbcTemplate().queryForList("set nocount on ; select " + gridService.getGET_GFIELD().toLowerCase() + " from gfield where formid=?  order by statisid asc", int_formid));
 
            //自定义时间查询
            map.put("9816", gridService.getSimpleJdbcTemplate().queryForList("set nocount on \n select  datefield,begindatestr,enddatestr,docstate,ShowAllNopost,dateLimitYn,MonthRangeYN,selfdocYn,hidescrapYn from _sysdatefilter  where formid=? ", int_formid));
            //取不是表头的功能链接,到时前端需要把有权限表达式的都传回后台处理再显示
            map.put("9842", apiServiceIfc.getAllFuncLinks(int_formid, formType));
            map.put("9685", apiServiceIfc.get9685List(int_formid));
            if (formType == 497 || formType == 499 || formType == 15 || formType == 17 || formType == 9 || formType == 496 || formType == 498 || formType == 8 || formType == 16 || formType == 5) {
                //单据状态值
 
                map.put("9815", gridService.getSimpleJdbcTemplate().queryForList("set nocount on \n select dictvalue,interValue from _sysdict where dictid=(select DocStatusName from gform where formid=?)", int_formid));
 
                //单据表头过滤设置
 
                map.put("9743", gridService.getSimpleJdbcTemplate().queryForList("set nocount on \n select " + gformFilter + " from gformFilter where formid=? order by StatisID asc ", int_formid));
 
                //OA按钮设置
 
                map.put("9881", gridService.getSimpleJdbcTemplate().queryForList("set nocount on select " + table3 + " from gfieldApprovedButton a left join t111634 b on a.ButtonName=b.ButtonName where a.formid=? order by a.[docitem] asc", int_formid));
 
            }
 
 
            //3表设置
            if (formType == 15 || formType == 77) {
 
                map.put("9825", gridService.getSimpleJdbcTemplate().queryForList("set nocount on select " + sysmasterdetail + " from _sysmasterdetail where formid=?", int_formid));
            }
            //树设置
            if (formType == 2 || formType == 3 || formType == 4 || formType == 20 ||
                    formType == 301 || formType == 302 || formType == 304 || formType == 238 ||
                    formType == 30) {
                final List<Map<String, Object>> list = gridService.getSimpleJdbcTemplate().queryForList("set nocount on select " + systreeset + " from _systreeset where formid=?", int_formid);
                map.put("9824", list);
                if (list != null && list.size() > 0) {
                    //增加树过滤条件
                    final SqlFormatEntity sqlFormatByEntity = SqlFormatUtils.createSQLFormatByEntity(list.get(0), 9824);
                    map.put("treefilterstr", sqlFormatByEntity);
                }
            }
            //496多表设置
            if (formType == 497 || formType == 499 || formType == 496 || formType == 498) {
 
                map.put("9771", gridService.getSimpleJdbcTemplate().queryForList("set nocount on select " + TabPageFormid + " from _sys_TabPageFormid where mainformid=? and Actived=1 order by TabID asc ,SortBy asc ", int_formid));
 
            }
            //表字段的数据类型信息(int ,varchar....)
            if (formType != 18 && formType != 19 && formType != 38) {//18,19,38查询类型,不需要取数据类型
                if (!"".equals(hdTable))
                    map.put(hdTable, gridService.getSimpleJdbcTemplate().queryForList(getDataType, hdTable, hdTable));
                if (!"".equals(dtTable))
                    map.put(dtTable, gridService.getSimpleJdbcTemplate().queryForList(getDataType, dtTable, dtTable));
            }
            if (formType == 38) {
                final Type38action type38action = (Type38action) FactoryBean.getBean("type38action");
                map.put("queryList", type38action.get38TypeInfo(request, response, int_formid));
            }
            //---增加打开功能号是否需要弹出密码框
            int pwdType = GridUtils.prossRowSetDataType_Int(gform, "isOpenFuncShowPwdEdit");//打开当前功能号前,是否校验密码,0表示不需要
            int pwdFlag = 0;//
            ApprovingEntity approvingEntity = null;
            String userCode = (String) request.getSession().getAttribute(SessionKey.HRCODE);
            if (pwdType != 0) {
                approvingEntity = approvingPwdIfc.getApprovingExists(int_formid + "", userCode, pwdType);
                if (approvingEntity != null) {
                    pwdFlag = 1;//1表示需要弹出输入密码
                    String PWDDBIDFORMID = "PWD" + dbid + int_formid;//唯一标识,不过期就有效
                    if (pwdType == 2 && request.getSession().getAttribute(PWDDBIDFORMID) != null) {
                        //2,登录后打开功能号时只需录入一次密码
                        //处理在会话中存在之前已输过一次密码,则跳过,直接打开功能号
                        pwdFlag = 0;
                    }
                } else {
                    pwdFlag = 2;//2表示弹出设置密码
                }
            }
            Map result = new HashMap();
            result.put("flag", pwdFlag);
            result.put("ownerUserCode", (pwdType == 4 && approvingEntity != null) ? approvingEntity.getOwnerUserCode() : null);
            result.put("ownerUserName", (pwdType == 4 && approvingEntity != null) ? approvingEntity.getOwnerUserName() : null);
            map.put("openFuncShowPwdEdit", result);
            //-------
            this.printJson(response, GridUtils.toJson(map));
        } catch (Exception e) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(e) + "\"}");
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 获取流程跟踪信息
     */
    @RequestMapping(value = "/processTrack.do", method = RequestMethod.GET)
    public void getprocess(int formid, String doccode, HttpServletRequest request, HttpServletResponse response) {// 修改待办事宜为已读状
        List<?> list = null;
        String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        try {
            SpObserver.setDBtoInstance("_" + dbid);
 
            list = gridService.getSimpleJdbcTemplate().queryForList("set nocount on select doccode,id,username,inserttime,nextcheckercode,nextcheckername,curstatus,msg from spickorderlog with (nolock) where doccode=? and formid=? order by  doccode,inserttime asc", doccode.replace("'", ""), formid);
 
            this.printJson(response, GridUtils.toJson(list));
        } catch (Exception e) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(e) + "\"}");
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
    /**
     *
     * APP 用户注册
     */
//    @RequestMapping(value="/reg.do", method = RequestMethod.POST)
//    public @ResponseBody Map register(@RequestBody RegisterUser user, HttpServletRequest request, HttpServletResponse response) {//
//    //1验证手机
//
//    }
 
    /***
     *用在多表中取得子功能号的列表数据,用在点击功能链接时替换参数
     * @param info
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getFormList.do", method = RequestMethod.POST)
    public @ResponseBody
    List<Map<String, Object>> getFormList(@RequestBody FristForm info, HttpServletRequest request, HttpServletResponse response) {
        String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        try {
            SpObserver.setDBtoInstance("_" + dbid);
            //通过功能号和类型取得对应的表名
            TreeGridDTO dto = new TreeGridDTO();
            dto.dbid = dbid;
            this.getTableName(Integer.parseInt(info.getFormid()), info.getFormtype(), dto);
 
            String sql = "set nocount on select " + info.getFields() + " from " + dto.table + " where " + info.getWhere();
 
            return gridService.getJdbcTemplate().queryForList(sql);
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
        } finally {
            SpObserver.setDBtoInstance();
        }
        return null;
    }
 
    @RequestMapping(value = "/api/upPortraitV2.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    Object uploadPortraitV2(HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            AttachmentAction attachmentAction = (AttachmentAction) FactoryBean.getBean("attachmentAction");
            PostBeanInfo postBeanInfo = attachmentAction.prossParameter(request);
            SpObserver.setDBtoInstance("_" + postBeanInfo.getDbid());
            postBeanInfo.setFormid(0);
            postBeanInfo.setFieldid("");
            Object result = attachmentAction.doPostAttachmentV2(postBeanInfo, request, response);
            if (result instanceof Map) {
                //TODO 更新用户表相关字段
                ApiServiceIfc apiServiceIfc = (ApiServiceIfc) FactoryBean.getBean("apiService");
                int count = apiServiceIfc.uploadPortrait(postBeanInfo.getUsercode(), ((Map) result).get("uuid") + "");
                if (count > 0) {
                    return result;
                } else {
                    throw new ApplicationException("更新用户头像失败");
                }
            } else if (result instanceof JsonObject) {
                return result;
            }
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage;
        } finally {
            SpObserver.setDBtoInstance();
        }
        return null;
    }
 
    /***
     *上传用户头像
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/api/upPortrait.do", method = RequestMethod.POST)
    public @ResponseBody
    List<Map<String, Object>> uploadPortrait(HttpServletRequest request, HttpServletResponse response) {
        String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        try {
            SpObserver.setDBtoInstance("_" + dbid);
            AttachmentAction attachmentAction = (AttachmentAction) FactoryBean.getBean("attachmentAction");
            request.setAttribute("formid", 0);
            request.setAttribute("type", 0);
            Object result = attachmentAction.doPostAttachment(request, response);
            if (result instanceof Map) {
                //TODO 更新用户表相关字段
                String userCode = (String) request.getSession().getAttribute(SessionKey.HRCODE);
                ApiServiceIfc apiServiceIfc = (ApiServiceIfc) FactoryBean.getBean("apiService");
                int count = apiServiceIfc.uploadPortrait(userCode, ((Map) result).get("uuid") + "");
                if (count > 0) {
                    printJson(response, GridUtils.toJson(result));
                } else {
                    throw new ApplicationException("更新用户头像失败");
                }
            } else if (result instanceof JsonObject) {
                printJson(response, result.toString());
            }
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
        } finally {
            SpObserver.setDBtoInstance();
        }
        return null;
    }
 
    /***
     * Ionic APP更新调用接口,下载更新包,新版本用这个接口
     * @param json
     * @param request
     * @param response
     */
    @Deprecated
    @RequestMapping(value = "/app/getZip.do", method = RequestMethod.POST)
    public void chcpUpdateZip(@RequestBody ChcpInfo json, HttpServletRequest request, HttpServletResponse response) {
        //creatFileToZip(json, response);
    }
 
    /***
     * Ionic APP更新调用接口,下载更新包
     * @param json
     * @param request
     * @param response
     */
    @Deprecated
    @RequestMapping(value = "/v", method = RequestMethod.POST)
    public void chcpUpdate(@RequestBody ChcpInfo json, HttpServletRequest request, HttpServletResponse response) {
        //creatFileToZip(json, response);
 
    }
 
    public void creatFileToZip(@RequestBody ChcpInfo json, HttpServletResponse response) {
        //String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        //pc生成app页面所在的路径
        String webUrl = AttachmentConfig.get("Ionic.webUrl");
        //app下载更新包所在的路径
        String appUrl = AttachmentConfig.get("Ionic.PageUrl");
 
        try {
            //文件的根目录
            String webRoot = webUrl + json.dbname + File.separator + "ionic_chcp" + File.separator + "www" + File.separator;
            long timestamp = System.currentTimeMillis();
            String tempRoot = appUrl + json.dbname + File.separator + json.dbname + "_" + timestamp;
            List<String> others = json.other;
 
            //    第一次下载时直接下载已存在的;
            if (json.frist == 1) {
                //基础包
                String zip = appUrl + json.dbname + File.separator + json.dbname + ".zip";
                File file = new File(zip);
                //存在则直接下载
                if (file.exists()) {
                    FileUtil.downloadFile(file, response, false);
                } else {//生成基础包再下载
                    extracted(others, webRoot, tempRoot, json, timestamp, appUrl + json.dbname + File.separator, response);
                }
            } else {
                extracted(others, webRoot, tempRoot, json, timestamp, appUrl + json.dbname + File.separator, response);
            }
 
        } finally {
            //    SpObserver.setDBtoInstance();
        }
    }
 
    private void extracted(List<String> others, String webRoot, String appRoot, ChcpInfo json, long timestamp, String appBaseUrl, HttpServletResponse response) {
        try {
            if (json.frist == 0) {
                //1,处理other里面的文件
                for (String str : others) {
                    //copy单文件到对应目录的文件
                    FileUtils.copyFile(new File(webRoot + str), new File(appRoot + File.separator + str));
                }
                //----增加把chcp.json,chcp.manifest 二个文件也copy过去,保持当前的状态,而不是每次下载基础包都是
                //用最新的版本做比对,之前存在着取了最新的版本,丢失了中间更新的部分页面,导致需要更新的功能号页面,得不到更新,是旧的或是找不到页面的情况
                FileUtils.copyFile(new File(webRoot + "chcp.json"), new File(appRoot + File.separator + "chcp.json"));
                FileUtils.copyFile(new File(webRoot + "chcp.manifest"), new File(appRoot + File.separator + "chcp.manifest"));
                //----
                //2,处理formids,这里需要根据formid,dbid组装路径来copy目录下面的文件
                if (!"".equals(json.formids) && json.frist == 0) {
                    String[] formids = json.formids.split(";");
                    int total = formids.length;
                    String from = null;
                    String to = null;
                    System.out.println(json.dbname + "->" + timestamp + "--需要处理formids-:【" + json.formids.toString() + "】");
                    //-----把相关信息写到数据库,用作跟踪调试
//                BaseService baseService=(BaseService) FactoryBean.getBean("BaseService");
//                try {
//                    SpObserver.setDBtoDemo();
//                    baseService.getSimpleJdbcTemplate().queryForObject("set nocount on \n insert into appinfo(dbName,info,[timestamps],usercode) values (?,?,?,?);", Integer.class, json.dbname, GridUtils.toJson(json), timestamp,json.usercode);
//                }catch (Exception e){
//                    e.printStackTrace();
//                }finally {
//                    SpObserver.setDBtoInstance();
//                }
                    //------
                    for (int i = 0; i < total; i++) {
                        from = webRoot + "app" + File.separator + json.dbid + File.separator + formids[i];
                        to = appRoot + File.separator + "app" + File.separator + json.dbid + File.separator;
                        FileUtils.copyDirectoryToDirectory(new File(from), new File(to));
                    }
                }
                String zipName = json.dbname + "_" + timestamp + ".zip";
                String appPath = appBaseUrl + json.dbname + "_" + timestamp;
                zipAndDownload(appPath, appBaseUrl, zipName, response, true);
            } else {//新增全新下载,把整个目录copy过来生成zip包
                File[] files = new File(webRoot).listFiles();
                String appPath = appBaseUrl + json.dbname;
                if (files != null) {
                    for (File file : files) {
                        if (file.isDirectory()) {
                            FileUtils.copyDirectoryToDirectory(file, new File(appBaseUrl + File.separator + json.dbname));
                        } else {
                            FileUtils.copyFileToDirectory(file, new File(appPath));
                        }
                    }
                }
                String zipName = json.dbname + ".zip";
                zipAndDownload(appPath, appBaseUrl, zipName, response, false);
            }
 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void zipAndDownload(String appPath, String appRoot, String zip, HttpServletResponse response, boolean isDelete) {
        try {
 
            ZipUtil.zip(appPath, null, null);
            File file = new File(appRoot);
            if (file.exists()) {//存在则直接下载
                FileUtil.downloadFile(file, response, isDelete);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 清除个人格线cookie数据
     */
    @RequestMapping(value = "/grid/clearCookie.do")
    public @ResponseBody
    Object clearCookie(Integer formid, String cookieType, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        String userCode = request.getSession().getAttribute(SessionKey.USERCODE) + "";
        try {
            SpObserver.setDBtoInstance("_" + dbid);
            if (formid == null || formid == 0) {
                throw new ApplicationException("功能号不能为空");
            }
            apiServiceIfc.clearCookie(userCode, formid, cookieType);
            callBackMessage.sendSuccessMessageByDefault();
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 保存格线cookie
     */
    @RequestMapping(value = "/grid/cookie.do", method = RequestMethod.POST)
    public @ResponseBody
    WebAsyncTask GridCookie(CookieEntity cookieEntity, HttpServletRequest request, HttpServletResponse response) {
        String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        String userCode = request.getSession().getAttribute(SessionKey.USERCODE) + "";
        CallBackMessage callBackMessage = new CallBackMessage();
        if (StringUtils.isNotBlank(request.getParameter("_pop_json"))) {
            cookieEntity = JSON.parseObject(request.getParameter("_pop_json"), CookieEntity.class);
        }
        Callable<Object> callable = new GridCookiesCallable(cookieEntity, userCode, dbid, gridService);
        //定义超时15秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(15), threadPoolExecutor, callable);
        asyncTask.onCompletion(
                () -> log.info("执行成功")
        );
        asyncTask.onError(
                (Callable<Object>) () -> {
                    log.info("执行出错");
                    callBackMessage.sendErrorMessage("执行出错,请重新操作");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    log.info("执行超时");
                    callBackMessage.sendErrorMessage("执行超时,请重新操作");
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    /**
     * 取功能号对应的自动编号信息
     */
    @RequestMapping(value = "/autocodeInfo.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> getAutoCodeInfo(String formid, HttpServletRequest request, HttpServletResponse response) {
        String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        try {
            SpObserver.setDBtoInstance("_" + dbid);
 
            String sql = "set nocount on select g.formid,g.codelength,g.preFixcode,g.precodetype,c.Formtype,c.Curcode,c.Fieldid from gform g,_sysautocode c where g.formid=c.formid and g.formid=?";
 
            return gridService.getJdbcTemplate().queryForMap(sql, new Object[]{formid});
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
        } finally {
            SpObserver.setDBtoInstance();
        }
        return null;
    }
 
    /**
     * 取回符合条件的功能链接
     *
     * @param bean
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getFunLinksV2.do", method = RequestMethod.POST)
    public @ResponseBody
    Object getFunLinksV2(@RequestBody LinksBean bean, HttpServletRequest request,
                         HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Object object = this.getFunLinks(bean, request, response);
            //增加单号导航
            List<Map<String, Object>> docNavList = new ArrayList<Map<String, Object>>();
            //有单号才执行
            if (StringUtils.isNotBlank(bean.getDoccode()) && (bean.getFormtype() == 5 || bean.getFormtype() == 8 || (bean.getFormtype() == 16 && bean.getIsMutType() == 0) || bean.getFormtype() == 496 || bean.getFormtype() == 498)) {
                DocNavigation docNavigation = (DocNavigation) FactoryBean.getBean("docNavigation");
                docNavList = docNavigation.getDocNavigation(bean.getFormid(), bean.getDoccode(), request, response);
            }
            map.put("links", object);
            map.put("docNav", docNavList);
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
        }
        return map;
    }
 
    @PostMapping(value = "/newFunLinks.do")
    public @ResponseBody
    Object newFunLinks(@RequestBody FuncLinkEntity bean, HttpServletRequest request) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
            SpObserver.setDBtoInstance("_" + dbid);
            Map<String, String> env = this.initEnv(request, 0, null, false);
            List list = this.spellNewFunclinkSQL(bean, request, env);
            callBackMessage.setInfo(list);
            callBackMessage.sendSuccessMessageByDefault();
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 用户app登录设备列表
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/app/listEquipments.do")
    public @ResponseBody
    Object listEquipments(HttpServletRequest request) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            String tel = request.getSession().getAttribute(SessionKey.USER_TELE_PHONE) + "";
            SpObserver.setDBtoDemo();
            List list = loginEquipmentIfc.listLogonEquipmentInfo(tel);
            callBackMessage.setInfo(list);
            callBackMessage.sendSuccessMessageByDefault();
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 修改手机号
     *
     * @param oldTel
     * @param newTel
     * @return
     */
    @RequestMapping(value = "/app/updateUserTel.do")
    public @ResponseBody
    Object updateUserTel(String oldTel, String newTel,String code, HttpServletRequest request) {
        CallBackMessage callBackMessage = new CallBackMessage();
        Integer demoInt = 1;
        try {
            if (StringUtils.isBlank(oldTel)) {
                throw new ApplicationException("原手机号不能为空");
            }
            if (StringUtils.isBlank(newTel)) {
                throw new ApplicationException("新手机号不能为空");
            }
            if(newTel.equalsIgnoreCase(oldTel)){
                throw new ApplicationException("新旧手机号不能相同");
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(code)) {
                throw new ApplicationException("验证码不能为空");
            }
            String verifyCode = (String) redisTemplate.opsForValue().get(VerificationCodes.getCodeKey(newTel));
            if (verifyCode==null) {
                throw new ApplicationException("验证码已失效,请重新获取验证码。");
            }
            if (!code.equals(verifyCode)) {
                throw new ApplicationException("验证码错误,请输入正确的验证码");
            }
            redisTemplate.delete(VerificationCodes.getCodeKey(newTel));//删除
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        }
        String error = null;//错误信息
        String logonType = request.getSession().getAttribute(SessionKey.LOGIN_TYPE) == null ? null : request.getSession().getAttribute(SessionKey.LOGIN_TYPE) + "";//用户类型
        try {
            //------1 首先查询demo数据库是否已存在newTel的手机号,不存在才能更新
            SpObserver.setDBtoDemo();
            demoInt = baseDoIfc.doQueryForObject("set nocount on\n " +
                    "   declare @userId int\n" +
                    "  select  @userId=userid from gProfile where telephone=" + GridUtils.prossSqlParm(newTel) + " \n" +
                    " if @@rowcount=1 select 1 else select 0", Integer.class);
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
        if (demoInt!=null&&demoInt.intValue() == 0) {
            //----demo不存在有新手机号,再查实例数据库
            String dbList=null;//关联的数据源列表
 
                try {
                    SpObserver.setDBtoDemo();
                     dbList=apiServiceIfc.getDataBaseLists(oldTel);//更新及取出关联数据源列表
                    if(dbList!=null){
                        demoInt=1;
                    }
                } catch (Exception ex) {
                    callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
                    return callBackMessage.toJSONObject();
                } finally {
                    SpObserver.setDBtoInstance();
                }
                if (demoInt.intValue() == 1) {
                    //---全部查找一次,都通过才能执行更新手机号
                    String[] dbIds=dbList.split(",");
                    for(String id:dbIds){
                        try {
                            DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(id);
                            SpObserver.setDBtoInstance("_"+id);
                            if (logonType == null) {
                                throw new ApplicationException("查找不到当前用户类型信息[logonType]");
                            }
                            demoInt = getUserTelphone(newTel, Integer.parseInt(logonType));
                            if (demoInt != null && demoInt.intValue() == 1) {
                                //表明存在有相同的手机号,报错,直接退出
                                throw  new ApplicationException(String.format("%s系统中%s手机号码已存在,不能更换",dataSourceEntity.getSystemDescribe(),newTel));
                            }
                        } catch (Exception ex) {
                            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
                            return callBackMessage.toJSONObject();
                        } finally {
                            SpObserver.setDBtoInstance();
                        }
                    }
                    //---全部通过,更新实例数据库
                    //--1,更新demo
                    try {
                        SpObserver.setDBtoDemo();
                        baseDoIfc.doExecute(" update gProfile set telephone="+GridUtils.prossSqlParm(newTel)+" where Telephone="+GridUtils.prossSqlParm(oldTel));
                    } catch (Exception ex) {
                        callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
                        return callBackMessage.toJSONObject();
                    } finally {
                        SpObserver.setDBtoInstance();
                    }
                    //---2,更新实例数据源
                    UserAccountServiceIfc userAccountServiceIfc = (UserAccountServiceIfc) FactoryBean.getBean("UserAccountServiceImpl");
                    UserPwdEntity entity = new UserPwdEntity();
                    entity.setTel(oldTel);
                    entity.setNewTel(newTel);
                    String msg="修改成功,请用新手机号["+newTel+"]重新登录";
                    for(String id:dbIds){
                        try {
                            SpObserver.setDBtoInstance("_"+id);
                            final UserAccountEntity userInfoByTelephone = userAccountServiceIfc.getUserInfoByTelephone(entity.getTel());
                            if (userInfoByTelephone != null && StringUtils.isNotBlank(userInfoByTelephone.getUserCode())) {
                                if (userInfoByTelephone.isInActive()) {
                                    throw new ApplicationException(entity.getTel() + "已被停用,禁止更换手机号");
                                } else {
                                    userAccountServiceIfc.saveUserTelePhone(userInfoByTelephone.getUserCode(),entity);
                                }
                            }
                            //---清除各个tomcat中的会话信息
                            MessageInfo messageInfo = new MessageInfo();
                            messageInfo.setMsgType(MessageType.SWITCH_PHONE_NUMBER);
                            messageInfo.setDbId(Integer.parseInt(id));
                            messageInfo.setMsg(msg);
                            messageInfo.setUserCode(request.getSession().getAttribute(SessionKey.USERCODE)+"");
                            WebSocketMessageServer.publishMessageToRedis(messageInfo);
                        } catch (Exception ex) {
                            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
                            return callBackMessage.toJSONObject();
                        } finally {
                            SpObserver.setDBtoInstance();
                        }
                    }
                    callBackMessage.sendSuccessMessage(msg);
                    return callBackMessage.toJSONObject();
                } else {
                    error = String.format("查找不到%s手机号相关联的系统,禁止更换", oldTel);
                }
        } else {
            error = String.format("已存在手机号【%s】,不能更换", newTel);
        }
        callBackMessage.sendErrorMessage(error);
        return callBackMessage.toJSONObject();
    }
 
    private Integer getUserTelphone(String telPhone, Integer logonType) {
        //  logonType  : 0表示登录号用户 ,1 表示客户,2 表示工号, 3 表示供应商
        if (logonType == null) logonType = 0;
        String sql = "set nocount on ;\n" +
                " declare @userCode varchar(50),@tel varchar(20)=" + GridUtils.prossSqlParm(telPhone) + "\n";
        if (logonType == 0) {
            sql += "    select top 1 @userCode=userCode from _sysuser    where tel=@tel ; select @@rowcount ; ";
        } else if (logonType == 1) {
            sql += "  select top 1 @userCode=CltCode  from t110203   where tel=@tel ; select @@rowcount ; ";
        } else if (logonType == 2) {
            sql += " select top 1 @userCode=HrCode  from t180201  where  mobile=@tel ; select @@rowcount ; ";
        } else {
            sql += " select top 1 @userCode=VndCode from t110302 where  tel=@tel ; select @@rowcount ; ";
        }
        try {
            return baseDoIfc.doQueryForObject(sql, Integer.class);
        } catch (DataAccessException e) {
            if (e instanceof EmptyResultDataAccessException) {
                return null;
            } else {
                e.printStackTrace();
                throw e;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
 
    /**
     * 修改登录设备名称
     *
     * @param entry
     * @return
     */
    @PostMapping(value = "/app/updateEquipmentName.do")
    public @ResponseBody
    Object updateEquipmentName(@RequestBody EquipmentEntry entry) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoDemo();
            loginEquipmentIfc.updateLogonEquipmentName(entry);
            callBackMessage.sendSuccessMessage("修改成功");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 删除登录设备
     *
     * @param entry
     * @return
     */
    @PostMapping(value = "/app/deleteEquipment.do")
    public @ResponseBody
    Object deleteEquipment(@RequestBody EquipmentEntry entry) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoDemo();
            loginEquipmentIfc.deleteLogonEquipment(entry);
            callBackMessage.sendSuccessMessage("删除成功");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 拼接有权限表达的功能链接成sql,执行
     *
     * @param funcLinks
     * @return
     */
    public List spellNewFunclinkSQL(FuncLinkEntity funcLinks, HttpServletRequest request, Map<String, String> env) throws Exception {
        if (funcLinks == null || funcLinks.getItems() == null || funcLinks.getItems().size() == 0) {
            throw new ApplicationException("Items参数不能为空");
        }
        if (StringUtils.isBlank(funcLinks.getDtTable())) {
            throw new ApplicationException("dtTable参数不能为空");
        }
        if (StringUtils.isBlank(funcLinks.getPrimaryKeyValues())) {
            throw new ApplicationException("primaryKeyValues参数不能为空");
        }
        String table = funcLinks.getDtTable();
        if (StringUtils.isNotBlank(funcLinks.getPostParmBy18())) {
            //18类型
            String[] tableNameBy18 = table.split("\\|");
            GridServiceIfc gridServiceIfc = (GridServiceIfc) FactoryBean.getBean("gridServiceImpl");
            final String functionParm = gridServiceIfc.getFunctionParm(tableNameBy18[1], funcLinks.getPostParmBy18(), env);
            if (functionParm.length() > 0) {
                table = tableNameBy18[0] + "(" + functionParm + ")";
            } else {
                table = tableNameBy18[0] + "()";
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append("select ");
        int i = 0;
        for (ItemLinkEntity linkEntity : funcLinks.getItems()) {
            if (StringUtils.isBlank(linkEntity.getItemExpression())) {
                throw new ApplicationException("itemExpression参数不能为空");
            }
            String expression = EncodeUtil.base64Decode(linkEntity.getItemExpression());
            Pattern p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词,处理会话值
            java.util.regex.Matcher propsMatcher = p.matcher(expression);
            while (propsMatcher.find()) {
                expression = expression.replaceAll(propsMatcher.group(), request.getSession().getAttribute(propsMatcher.group().toLowerCase()) + "");
            }
            if (i <= funcLinks.getItems().size()) {
                if (i > 0) {
                    sb.append(",");
                }
            }
            sb.append(" case when ").append(expression).append(" then 1 else 0 end as ")
                    .append("'").append(linkEntity.getLinkformId())
                    .append("_").append(linkEntity.getSortid()).append("' ");
            i++;
        }
        String where = EncodeUtil.base64Decode(funcLinks.getPrimaryKeyValues());
        sb.append(" from ").append(table).append(" where ").append(where.replaceAll(";", " and "));
        BaseService baseService = (BaseService) FactoryBean.getBean("BaseService");
        return baseService.getSimpleJdbcTemplate().queryForList(sb.toString());
    }
 
    /**
     * 取回符合条件的功能链接
     *
     * @param bean
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getFunLinks.do", method = RequestMethod.POST)
    public @ResponseBody
    Object getFunLinks(@RequestBody LinksBean bean, HttpServletRequest request,
                       HttpServletResponse response) {
 
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            List<Map<String, Object>> list = null;//所有功能链接集合
            BaseService baseService = (BaseService) FactoryBean.getBean("BaseService");
            String sql = "set nocount on select  " + sysfunclink +
                    ",a.largImagePath from _sysfunclink b left join _sysMenu a on b.linkformid=cast(a.formid as varchar(20)) where b.origformid=? and b.origformtype=? order by b.sortid asc \n";
            //496多表
            if (bean.getFormtype() == 496 || bean.getFormtype() == 498) {
                sql = "set nocount on \n select  " + sysfunclink +
                        " ,c.largImagePath from _sysFuncLink b left join _sysMenu c on b.linkformid=cast(c.formid as varchar(20)) \n" +
                        "where exists(select 1 from _sys_TabPageFormid a where a.mainformid = ? \n" +
                        "   and a.formid = b.origformid \n" +
                        "   and ((a.mainformid = a.formid and b.origformtype = 496) \n" +
                        "   or (a.mainformid <> a.formid and  a.formtype = b.origformtype ))\n" +
                        "   )\n" +
                        " order by b.origformid asc ,b.sortid asc \n";
                list = baseService.getSimpleJdbcTemplate().queryForList(sql, bean.getFormid());
            } else {
                list = baseService.getSimpleJdbcTemplate().queryForList(sql, bean.getFormid(), bean.getFormtype());
 
            }
            List<Map<String, Object>> result = new ArrayList<>();
            BuildTopIfc buildTopIfc = (BuildTopIfc) FactoryBean.getBean("BuildTopImpl");
            String tempFormid = null;
            if (list != null && list.size() > 0) {
                for (int k = 0; k < list.size(); k++) {
                    Map<String, Object> tempMap = list.get(k);
                    String formid = tempMap.get("origformid") + "";
                    if (tempFormid != null) {
                        if (tempFormid.equalsIgnoreCase(formid))
                            continue;
                    }
                    tempFormid = formid;
                    final List<Map<String, Object>> tempList = list.stream().filter(x -> (x.get("origformid") != null && formid.equals(x.get("origformid") + ""))).collect(toList());//处理同一个功能号里所有表达式的数据
                    final List<Map<String, Object>> collectNotitemexpression = list.stream().filter(x ->
                            (x.get("origformid") != null && formid.equals(x.get("origformid") + ""))
                                    && (x.get("showitemexpression") == null || "".equals(x.get("showitemexpression")))
                                    && (//处理editstatus有值的情况
                                    StringUtils.isBlank(bean.getDoccode())//新单
                                            && (x.get("editstatus") != null && StringUtils.isNotBlank(x.get("editstatus") + "") ? ((";" + x.get("editstatus") + ";").contains(";0;")) : true)
                            )
                    ).collect(toList());//没有表达式的数据
 
                    Map<String, Object> map = buildTopIfc.buildFuncLinkExpression_APPV2(Integer.parseInt(formid), Integer.parseInt(tempMap.get("origformtype") + ""), bean.getDoccode(), request, request.getSession(), tempList);
                    if (map != null) {//有结果
                        for (Map.Entry<String, Object> entry : map.entrySet()) {
                            if ("1".equals(entry.getValue() + "")) {//取值为1,表示有权限,(没有表达式的也在里面设置为1)
                                String[] key = entry.getKey().split("_");
                                result.addAll(
                                        tempList.stream().filter(obj -> (obj.get("sortid") + "").equals(key[1] + "") && (obj.get("linkformid") + "").equals(key[0] + "")).collect(toList()
                                        ));
                            }
                        }
 
                    } else {//条件不成立,返回null,则取没有表达式的链接
                        result.addAll(collectNotitemexpression);
                    }
                }
            }
            return result;
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
        } finally {
            SpObserver.setDBtoInstance();
        }
        return null;
    }
 
    /**
     * 9802设置不感应,但可能数据库存在有字段
     * 获取表的字段和数据类型,因为存在,表示要在页面显示出来,但在新增,修改时需要过滤
     *
     * @param tablename
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/api/getColumnsInfo.do", method = RequestMethod.GET)
    public @ResponseBody
    Object getColumnsInfo(String tablename, HttpServletRequest request,
                          HttpServletResponse response) {
 
        List<Map<String, Object>> list = null;
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            list = gridService.getSimpleJdbcTemplate().queryForList("set nocount on ; select column_name ,data_type from INFORMATION_SCHEMA.columns  where table_name=?", tablename);
            return list;
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
        } finally {
            SpObserver.setDBtoInstance();
        }
        return null;
    }
 
    /**
     * 取22类型存储过程参数列表
     */
    @RequestMapping(value = "/get22ParamInfo.do", method = RequestMethod.POST)
    public @ResponseBody
    String getPrimKey(@RequestParam String formid,
                      HttpServletRequest request, HttpServletResponse response) {// 修改待办事宜为已读状态
        try {
            String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
            SpObserver.setDBtoInstance("_" + dbid);
            String cols = this.gridService.getSimpleJdbcTemplate().queryForObject(" select stuff((SELECT ',''' + CONVERT(VARCHAR,  isnull(b.fieldid,''))+'''' from gField b where   b.isload=1 and b.headflag=0 and  \n" +
                    "formid=? and isnull(DataLink,0)=1 order by StatisID asc  FOR XML PATH ('')),1,1,'')", String.class, formid);
            if (cols == null || "".equalsIgnoreCase(cols)) {
                throw new ApplicationException(formid + "在9802字段列表为空,请在9802添加参数字段定义或查看字段的【感应】参数是否选上");
            }
            return "[" + (cols == null ? "" : cols) + "]";
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
        } finally {
            SpObserver.setDBtoInstance();
        }
        return null;
    }
 
    /**
     * 修改密码,通过手机验证码和新密码修改密码
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/api/forgotPwd.do", method = RequestMethod.POST)
    public void changePwd(@RequestBody PwdBean json, HttpServletRequest request, HttpServletResponse response) {
        JsonObject rightJson = new JsonObject();
        JsonObject errJson = new JsonObject();
        if (json.getTel() == null || "null".equalsIgnoreCase(json.getTel()) || "".equalsIgnoreCase(json.getTel())) {
            errJson.addProperty("error", "手机号不能为空");
        }
        if (json.getNewPwd() == null || "null".equalsIgnoreCase(json.getNewPwd()) || "".equalsIgnoreCase(json.getNewPwd())) {
            errJson.addProperty("error", "新密码不能为空");
        }
        if (json.getCode() == null || "null".equalsIgnoreCase(json.getCode()) || "".equalsIgnoreCase(json.getCode())) {
            errJson.addProperty("error", "验证码不能为空");
        }
        if (errJson != null && errJson.has("error")) {
            this.printJson(response, errJson.toString());
            return;
        }
        String tel = EncodeUtil.replaceUrlChar(json.getTel());
        if (tel.length() > 20) {//表示已加密,需要解密
            try {
                tel = ChangePassword.getDecryptPassword(tel);
                json.setTel(tel);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //1,验证手机验证码
        InvitationCode invitationCode = (InvitationCode) FactoryBean.getBean("invitationCode");
        boolean flg =invitationCode.verificationCode(response, json.getTel(), json.getCode(), rightJson, errJson);
        if (!flg) {
            //2,执行修改密码功能
            rightJson=allInModifyUserPwd(json);
            this.printJson(response, rightJson.toString());
            return;
        }
    }
 
    /**
     * 执行更新所有系统及demo表的用户密码
     * @param json
     * @param tel
     * @return
     */
    public JsonObject allInModifyUserPwd(PwdBean json) {
        String result=null;
        String pwd_str=null;
        JsonObject rightJson = new JsonObject();
        JsonObject errJson = new JsonObject();
        try {
            SpObserver.setDBtoDemo();
             pwd_str = EncodeUtil.replaceUrlChar(json.getNewPwd());
            if (pwd_str.length() < 30) {//明文,需要加密密码保存
                pwd_str = ChangePassword.getEncryptPassword(pwd_str);
            }
             result = apiServiceIfc.doUpdateUserPwd(pwd_str, json.getTel());
            if(result==null) {
                throw new ApplicationException("没有相关联的系统,禁止修改密码");
            }
        } catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("info", this.getErrorMsg(e));
            rightJson.add("error", errJson);
        } finally {
            SpObserver.setDBtoInstance();
        }
        if (result != null) {
            redisTemplate.delete(VerificationCodes.getCodeKey(json.getTel()));
            UserPwdEntity entity = new UserPwdEntity();
            entity.setTel(json.getTel());
            entity.setNewPwd(pwd_str);
            try {
                String[] dbList=result.split(",");
                UserAccountServiceIfc userAccountServiceIfc = (UserAccountServiceIfc) FactoryBean.getBean("UserAccountServiceImpl");
                for(String id:dbList) {
                    DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(id);
                    SpObserver.setDBtoInstance("_" + id);
                    final UserAccountEntity userInfoByTelephone = userAccountServiceIfc.getUserInfoByTelephone(entity.getTel());
                    if (userInfoByTelephone != null && StringUtils.isNotBlank(userInfoByTelephone.getUserCode())) {
                        if (userInfoByTelephone.isInActive()) {
                            throw new ApplicationException(dataSourceEntity.getSystemDescribe()+"系统"+entity.getTel() + "已被停用,禁止修改密码");
                        } else {
                            userAccountServiceIfc.savePassword(userInfoByTelephone.getUserCode(), entity.getNewPwd(), userInfoByTelephone.getUserCode());
                        }
                    }
                }
                rightJson.addProperty("status", "密码修改成功!");
            } catch (Exception ex) {
                ex.printStackTrace();
                errJson.addProperty("info", this.getErrorMsg(ex));
                rightJson.add("error", errJson);
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
        return rightJson;
    }
 
    /**
     * 发手机验证码
     */
    @RequestMapping(value = "/api/sendSms.do", method = RequestMethod.GET)
    public void sendSms(String tel, HttpServletRequest request, HttpServletResponse response) {
        //发送验证码到对应手机号
        //TODO 暂定用标准版的短信账号来发送,以后再转第三方做验证调用时就可以用第三方的短信账号
        request.setAttribute(SessionKey.SHOPPING_DBID, "82");
        VerificationCodes verificationCodes = (VerificationCodes) FactoryBean.getBean("verificationCodes");
        verificationCodes.GenRandomVcode(tel, request, response);
    }
 
    /**
     * 取功能号对应的主键,多个是以;号分隔
     */
    @RequestMapping(value = "/forminfo.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, String> getPrimKey(@RequestBody FormInfo json, HttpServletRequest request, HttpServletResponse response) {
        String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
        try {
            //Gson gson = new Gson();
            Map<String, String> map = new HashMap<String, String>();
            // FormInfo  json=gson.fromJson(request.getParameter("_pop_json"), new com.google.gson.reflect.TypeToken<FormInfo>() {}.getType());
            //SpObserver.setDBtoInstance("_" + dbid);
            // 取到对应功能号的表名
            //wintype 格式:9@p@1
            TreeGridDTO dto = new TreeGridDTO();
            dto.dbid = dbid;
            this.getTableName(json.getFormid(), json.getWintype(), dto);
            dto.b497 = json.isB497();
            dto.b499 = json.isB499();
            this.setOrderName(dto);
            dto.orderFiled = json.getFiled();
            this.getFirstField(dto);//取主键
            this.setOrderFiled(dto);
            this.setOrderBy(dto);
 
            map.put("primeKey", dto.primeKey);
            map.put("sortCols", dto.sortCols);
            map.put("sortTypes", dto.sortTypes);
            map.put("tableName", dto.table);
            int isView = 0;
            //多表才执行
            if (dto.b497 || dto.b499) {
                try {
                    SpObserver.setDBtoInstance("_" + dto.dbid);
                    String tableType = this.gridService.getSimpleJdbcTemplate().queryForObject("select TABLE_TYPE from information_schema.TABLES where table_name=?", String.class, dto.table);
                    if ("VIEW".equals(tableType)) {
                        //针对496多表子功能号是视图,新增提交时需要把action修改为add
                        isView = 1;
                    }
                } finally {
                    SpObserver.setDBtoInstance();
                }
            }
            map.put("isView", isView + "");
            return map;
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
        }
        return null;
    }
 
    private void setOrderFiled(TreeGridDTO dto) {
 
    }
 
    private void getFirstField(TreeGridDTO dto) {
        //1先读表关键功能,如果没有相关的再读表结构
        List<String> keys = null;
        try {
            SpObserver.setDBtoInstance("_" + dto.dbid);
            String taleName = dto.table;
            if (dto.winType == 18 || dto.winType == 19) {
                taleName = dto.table.split("\\|")[0];
            }
            keys = gridService.getPrimaryKey(taleName);
            if (keys != null) {
                for (String str : keys) {
                    if ("".equals(dto.field))
                        dto.field += str;
                    else
                        dto.field += ";" + str;
                }
            }
            dto.primeKey = dto.field;
        } catch (SQLException e) {
            throw new ApplicationException(e.getMessage());
        } finally {
            SpObserver.setDBtoInstance();
        }
 
    }
 
    public void getTableName(int formid, String winType, TreeGridDTO dto) {
        SqlRowSet gform = null;
        try {
            SpObserver.setDBtoInstance("_" + dto.dbid);
            gform = gridService.getGformByFormID(formid);
        } finally {
            SpObserver.setDBtoInstance();
        }
        String[] temp = winType.split("@p@");
        dto.winType = Integer.parseInt(temp[0]);
        dto.conNum = temp.length > 1 ? Integer.parseInt(temp[1]) : 0;
        if (!gform.wasNull()) {
            gform.first();
            dto.HDTable = gform.getString("hdtable");
            //dto.dataformid=(gform.getString("dataformid")==null||gform.getString("dataformid").length()==0||gform.getString("dataformid").equalsIgnoreCase("0"))?"":(gform.getString("dataformid")+(!this.isDanJun(dto)?"":"|"+gform.getInt("predocstatus")));
            //dto.tranformid=(gform.getString("dataformid")==null||gform.getString("dataformid").length()==0||gform.getString("dataformid").equalsIgnoreCase("0"))?"":(gform.getString("dataformid"));
            dto.DTtable = gform.getString("dttable");
//        dto.frozencols=gform.getInt("frozencols");
//        dto.formname=gform.getString("formname");
//        dto.gantt=gform.getBoolean("isGantt");//是否为甘特图类型的功能号
//        dto.predocstatus=gform.getInt("predocstatus");//确认前状态,为了给格线在确认后不能再修改(新增,修改,删除) by 2013-02-01
//        dto.rowcopyfields=gform.getString("rowcopyfields");//行复制时排除字段
//        dto.pageSize=gform.getInt("pageSize");//页记录数
//        dto.autopaging=gform.getInt("autopaging");//是否分页
//        dto.optype=gform.getInt("optype");//功能号权限
//        dto.lockGridSort=gform.getInt("LockGridSort");//冻结列排序
//         dto.colset=gform.getInt("isShowCell");//是否显示列过滤
//         dto.mainCol=gform.getString("byGroup");//树分组显示字段
//         dto.isFilter=gform.getInt("isFilter");//是否打开过滤功能
//         boolean blactions=gform.getBoolean("addNewRow");//直接增行
//         try {
//         dto.postStatusAddNew=gform.getInt("PostStatusGridAddNew");//根据状态值是否可以显示增行按钮,用在OA审核中
//         }catch(Exception e) {
//             dto.postStatusAddNew=0;
//         }
            // if(blactions) dto.actions="<Actions OnClickButtonAdd=\"AddRowEnd\" />";
            // dto.defaultRowCount=gform.getInt("DefaultRowCount");//格线默认加载时显示行数
//        if(!"".equalsIgnoreCase(dto.tolkey)&&(dto.b497||dto.b499)&&dto.PriFormID>0){//是多表的情况 且是第一个子功能号
//            
//            SqlRowSet f=null;
//            try{
//                SpObserver.setDBtoInstance("_"+dto.dbid);
//                    f=gridService.getGformByFormID(dto.PriFormID);
//            }finally{
//            SpObserver.setDBtoInstance();
//            }
//            if(!f.wasNull()){
//                f.first();
//                dto.rowcopyformids=f.getString("rowcopyformids");//复单时排除功能号        
//            }
//            
//        }else{
//            dto.rowcopyformids=gform.getString("rowcopyformids");//复单时排除功能号
//        }
//        if(dto.gridHeight==0) dto.gridHeight=gform.getInt("GridHeight");//表格高度
//        dto.glcodefield=gform.getString("glcodefield");//会计科目需要的字段
//        if(!this.isNullOrEmptry(dto.glcodefield)){//格式:主表汇总,明细表汇总|平衡字段|平衡值公式字段
//            List<Map<String ,Object>> map=null;
//             try{
//                    SpObserver.setDBtoInstance("_"+dto.dbid);
//                    map=gridService.getSimpleJdbcTemplate().queryForList("select MasterSumFields,DetailSumFields from _sysmasterdetail where FormID=?", dto.formID);
//             }finally{
//                SpObserver.setDBtoInstance();
//                }
//            if(map.size()>0){
//                Map<String ,Object> m=map.get(0);
//                dto.gltotal=m.get("MasterSumFields")+","+m.get("DetailSumFields")+"|"+gform.getString("checkblncfields")+"|"+gform.getString("chkFormula"); 
//            m=null;
//            }
//            map=null;
//            }
            dto.index1 = gform.getString("index1");//列表的排序字段-9类型
            dto.index2 = gform.getString("index2");//明细表的排序字段-5类型
//        dto.formdatafilters=gform.getString("formdatafilters")==null?"":this.replaceBlank(gform.getString("formdatafilters"));
//        dto.ProcGroupafterSavedoc=gform.getString("ProcGroupafterSavedoc")==null?"":this.replaceBlank(gform.getString("ProcGroupafterSavedoc"));
//        dto.trangroup=gform.getString("transgroupcode")==null?"":gform.getString("transgroupcode");
//        dto.DealAfterDocSave=gform.getString("DealAfterDocSave")==null?"":this.replaceBlank(gform.getString("DealAfterDocSave"));
//        
//        dto.cancelProc=gform.getString("CancelBtnProcName")==null?"":this.replaceBlank(gform.getString("CancelBtnProcName"));
//        
//        dto.revokeProc=gform.getString("RevokeBtnProcName")==null?"":this.replaceBlank(gform.getString("RevokeBtnProcName"));
//        
//        dto.cancelisSave=gform.getBoolean("CancelIsSave")?1:0;
 
            if (dto.winType == 0 || (dto.winType == 7 && dto.conNum == 0) || dto.winType == 1 || dto.winType == 5 || (dto.winType == 9 && dto.conNum == 0) || dto.winType == 3 || dto.winType == 4 ||
                    dto.winType == 17 || (dto.winType == 302 && dto.conNum == 0) || dto.winType == 19 ||
                    (dto.winType == 499 && dto.conNum == 0) || (dto.winType == 10 && dto.conNum == 0) ||//dto.winType == 10 &&dto.conNum == 1 修改为dto.conNum == 0  by danaus 2020/1/11 13:53
                    (dto.winType == 497 && dto.conNum == 0) || (dto.winType == 2 && dto.conNum == 0) ||
                    (dto.winType == 20 && dto.conNum == 0) || (dto.winType == 301 && dto.conNum == 0) ||
                    (dto.winType == 30 && dto.conNum == 0) ||
                    (dto.winType == 303 && dto.conNum == 0) || (dto.winType == 304 && dto.conNum == 0) ||
                    (dto.winType == 238 && dto.conNum == 0) || (dto.winType == 302) ||
                    (dto.winType == 15 && (dto.conNum == 0 || dto.conNum == 2))) {
                dto.table = dto.HDTable;
                dto.isList = true;
            } else {
                dto.table = dto.DTtable;
            }
 
            gform = null;
 
        }
 
    }
 
    /**
     * 根据不同类型决定不同的排序规则
     * //1,读取9801设置,
     * //2,根据不同类型再进行不同的设置(单据清单desc,明细 以docitem asc,)
     * //3,对于不是上面的二种情况不用排序
     */
    private void setOrderBy(TreeGridDTO dto) {
        String temp = "";
        if (dto.order == 1 && dto.index1 != null && !dto.index1.isEmpty()) { //9801 主表
            temp = setSqlOrderBy(dto.index1, " asc");
        } else if (dto.order == 2 && dto.index2 != null && !dto.index2.isEmpty()) {//明细表
            temp = setSqlOrderBy(dto.index2, " asc");
        } else {
            if (dto.field.isEmpty())
                temp = dto.orderFiled;
            else
                temp = setSqlOrderBy(dto.field, (dto.order == 1 && dto.winType != 2 && dto.winType != 20) ? " desc" : " asc");
        }
        dto.field = "";
        if (!"".equalsIgnoreCase(temp)) {
            String[] s = temp.replaceAll(",", " ").split("\\s+");//
            StringBuilder cols = new StringBuilder();
            StringBuilder types = new StringBuilder();
 
            for (int j = 0; j < s.length; j += 2) {
                if (s.length < 2) throw new ApplicationException("【" + temp + "】内容格式不正确【filed1,1,filed2,0....】");
                if (j > 0) {
                    cols.append(",");
                    types.append(",");
                }
                cols.append(s[j].equalsIgnoreCase("_ycid_") ? "id" : s[j]);
                types.append("asc".equalsIgnoreCase(s[j + 1]) ? "0" : "1");
            }
            dto.sortCols = cols.toString();
            dto.sortTypes = types.toString();
 
        }
 
    }
 
    private String setSqlOrderBy(String index22, String x) {//x为desc,asc
        StringBuilder temp = new StringBuilder();
        index22 = index22.replaceAll(";", ",");
        String[] sorts = index22.split(",");
        int index = 0;
        for (String s : sorts) {
            String[] str = s.split("\\s");
            if (str.length == 2) {
                if (index > 0)
                    temp.append(",").append(str[0]).append(" " + str[1]);
                else
                    temp.append(str[0]).append(" " + str[1]);
            } else {
                if (index > 0)
                    temp.append(",").append(str[0]).append(" " + x);
                else
                    temp.append(str[0]).append(" " + x);
            }
            index++;
        }
        return temp.toString();
    }
 
    /**
     * 根据类型选用不同的字段作为排序
     *
     * @return 1表示清单,2表示明细
     **/
    private void setOrderName(TreeGridDTO dto) {
 
        switch (dto.winType) {
            case 9:
            case 15:
            case 17:
            case 499:
            case 497:
                //case 10:
                if (dto.conNum == 0) {
                    //isList=t
                    dto.order = 1;
                } else
                    dto.order = 2;
                dto.isBill = true;
                break;
            case 1:
                if (dto.b497 || dto.b499) {
                    dto.order = 2;
                    dto.isBill = true;
                } else
                    dto.order = 1;
                break;
            default:
                dto.order = 1;
        }
    }
}