xinyb
2024-07-09 b179883e53a86d5e8044729ba928326d64623b13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
package com.yc.api.controller;
 
import com.alibaba.fastjson.JSON;
import com.yc.action.BaseAction;
import com.yc.action.grid.GTGrid;
import com.yc.action.grid.GridUtils;
import com.yc.api.bean.CartEntity;
import com.yc.api.bean.MatGroupEntity;
import com.yc.api.bean.*;
import com.yc.api.service.QrServiceIfc;
import com.yc.entity.DataSourceEntity;
import com.yc.exception.ApplicationException;
import com.yc.exception.CallBackMessage;
import com.yc.factory.FactoryBean;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.open.mutual.controller.MutualController;
import com.yc.sdk.jedis.RedisKey;
import com.yc.sdk.shopping.action.api.ShopCcCode;
import com.yc.sdk.shopping.entity.*;
import com.yc.sdk.shopping.service.*;
import com.yc.sdk.shopping.service.PrepaidDeposit.PrepaidDepositIfc;
import com.yc.sdk.shopping.service.imagedata.ShoppingImageDataIfc;
import com.yc.sdk.shopping.service.register.AccountIfc;
import com.yc.sdk.shopping.service.share.ShareIfc;
import com.yc.sdk.shopping.util.HtmlUtil;
import com.yc.sdk.shopping.util.SettingKey;
import com.yc.service.BaseService;
import com.yc.service.grid.GridServiceIfc;
import com.yc.utils.SessionKey;
import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.Transactional;
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 javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
 
/**
 * 扫码
 */
@RestController
public class QrCodeController extends BaseAction {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    CartIfc cartIfc;
    @Autowired
    QrServiceIfc qrServiceIfc;
    @Autowired
    ShoppingImageDataIfc imgData;
    @Autowired
    SettingIfc settingIfc;
 
    // 价格
    @Autowired
    MatPriceIfc matPriceIfc;
 
    // 货币
    @Autowired
    CurrencyIfc currencyIfc;
 
    // 商品资料
    @Autowired
    MatCodeIfc matCodeIfc;
 
    // 商品附加图片信息
    @Autowired
    MatCodeImageIfc matCodeImageIfc;
 
    // 商品选项
    @Autowired
    MatOptionIfc matOptionIfc;
 
 
    // 消费积份
    @Autowired
    MatPointsIfc matPointsIfc;
 
    // 商品促销活动关联表
    @Autowired
    MatDiscountIfc matDiscountIfc;
 
    // 选项
    @Autowired
    MatComponentIfc matComponentIfc;
 
    // 显示分享信息
    @Autowired
    ShareIfc shareIfc;
 
    // 选项属性
    @Autowired
    MatAttrIfc matAttrIfc;
    //优惠劵
    @Autowired
    CouponIfc couponIfc;
 
    //预付订金分组
    @Autowired
    PrepaidDepositIfc prepaidDepositIfc;
 
    @Autowired
    AccountIfc accountIfc;
    @Autowired
    private GridServiceIfc gridService;
    @Autowired
    ThreadPoolTaskExecutor threadPoolExecutor;
    @Autowired
    ShoppingImageDataIfc shoppingImageDataIfc;
 
    /**
     * 获取清单
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/cartList.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object getCartList(String docCode, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            String dbid=request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"";
            SpObserver.setDBtoInstance("_" +dbid );
            String hostUrl = SettingKey.getHostUrlForImage(request);
            final List<com.yc.api.bean.CartEntity> cartList = qrServiceIfc.getCartList(request.getSession().getAttribute(SessionKey.USERCODE) + "", docCode);
//            cartList.stream().map(x -> {
//                x.setPhotoPath(imgData.getImageUrl(x.getPhotoPath(), 120,
//                        120, false,
//                        false, request));
//                return x;
//            }).collect(Collectors.toList());
            cartList.stream().forEach(x -> {
                x.setPhotoPath(SettingKey.getUrl(hostUrl, x.getPhotoPathUrl(), dbid+"",null));
                x.setPhotoPathUrl(SettingKey.getUrl(hostUrl, x.getPhotoPathUrl(), dbid+"",null));
            });
            //合并相同商品,输出一个
            final   List<com.yc.api.bean.CartEntity> newCartList = new ArrayList<>();
            String matCode="";
            Iterator<CartEntity> iterator = cartList.iterator();
            while (iterator.hasNext()) {
                CartEntity cartEntity = iterator.next();
                com.yc.api.bean.CartEntity cart=new com.yc.api.bean.CartEntity();
                BeanUtils.copyProperties(cartEntity,cart);
                double totalAmount=StringUtils.isNotBlank(cart.getAmount())?Double.parseDouble(cart.getAmount()):0;//合并总价
                double totalQuantity=cart.getQuantity();//合并数量
                iterator.remove();
                if(!matCode.equalsIgnoreCase(cart.getMatCode())) {
                    matCode=cart.getMatCode();
                    Iterator<CartEntity> iterator2 = cartList.iterator();
                    while (iterator2.hasNext()) {
                        CartEntity cartEntity2 = iterator2.next();
                        if (cart.getMatCode().equalsIgnoreCase(cartEntity2.getMatCode())) {
                            totalAmount += Double.parseDouble(cartEntity2.getAmount());
                            totalQuantity += cartEntity2.getQuantity();
                        }
                    }
                    cart.setAmount(totalAmount + "");
                    cart.setQuantity(totalQuantity);
                    newCartList.add(cart);
                }
            }
            //List<Gfrom> refFormIdList = getRefFormIdList(request, refFormid);
            Map map = new HashMap();
            map.put("carts", newCartList);
            //map.put("refFormids", refFormIdList);
 
            callBackMessage.setInfo(map);
            callBackMessage.sendSuccessMessage("成功");
            return callBackMessage.toJSONObject();
 
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 删除
     *
     * @param request
     * @param response
     */
    @Transactional
    @RequestMapping(value = "/qr/delCart.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask delCart(String idList, HttpServletRequest request, HttpServletResponse response) {
        String userCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        String userName = request.getSession().getAttribute(SessionKey.HRNAME) + "";
        Callable<Object> callable = new CartCallable(null, null, idList, userCode, userName, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", qrServiceIfc, 3);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
        asyncTask.onCompletion(
                () -> log.info("执行成功")
        );
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行出错");
                    callBackMessage.sendErrorMessage("操作出错");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行超时");
                    callBackMessage.sendErrorMessage("服务器繁忙,正在排队处理,请不要重复提交,稍后请在购物车查看结果", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    /**
     * 立即下单
     *
     * @param request
     * @param response
     */
    @Transactional
    @RequestMapping(value = "/qr/postCarts.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask postCarts(@RequestBody PostCartEntity postCartEntity, HttpServletRequest request, HttpServletResponse response) {
        String userCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        String userName = request.getSession().getAttribute(SessionKey.HRNAME) + "";
        log.info("---------------------start:" + userCode + "-----------------");
        Callable<Object> callable = new T120201Callable(postCartEntity, userCode, userName, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", qrServiceIfc, 1);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
        asyncTask.onCompletion(
                () -> log.info("执行成功")
        );
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行出错");
                    callBackMessage.sendErrorMessage("执行出错,请重新下单");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行超时");
                    callBackMessage.sendErrorMessage("服务器繁忙,正在排队处理,请不要重复提交,稍后请在【销售管理】-【销售订单】-【查询订单进度表】中查看结果", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    /**
     * 在购物车通过多选物料生成单据
     *
     * @param postCartEntity 用;分隔的多个cartid
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/createPost.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask cartPost(@RequestBody PostCartEntity postCartEntity, HttpServletRequest request, HttpServletResponse response) {
        String userCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        String userName = request.getSession().getAttribute(SessionKey.HRNAME) + "";
        log.info("---------------------start:" + userCode + "-----------------");
        Callable<Object> callable = new T120201Callable(postCartEntity, userCode, userName, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", qrServiceIfc, 0);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
        asyncTask.onCompletion(
                () -> log.info("执行成功")
        );
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行出错");
                    callBackMessage.sendErrorMessage("执行出错,请重新下单");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行超时");
                    callBackMessage.sendErrorMessage("服务器繁忙,正在排队处理,请不要重复提交,稍后请在【销售管理】-【销售订单】-【查询订单进度表】中查看结果", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    private class T120201Callable implements Callable<Object> {
        PostCartEntity postCartEntity;
        String userCode;
        String dbid;
        QrServiceIfc qrServiceIfc;
        int actionType = 0;//0 表示从购物车下单,1 表示立即下单
        String userName;
 
        public T120201Callable(PostCartEntity postCartEntity, String userCode, String userName, String dbid, QrServiceIfc qrServiceIfc, int actionType) {
            this.postCartEntity = postCartEntity;
            this.userCode = userCode;
            this.dbid = dbid;
            this.qrServiceIfc = qrServiceIfc;
            this.actionType = actionType;
            this.userName = userName;
        }
 
        private String joinCartSql() {
            final List<CartEntity> carts = postCartEntity.getCarts();
            StrBuilder sb = new StrBuilder();
            if (carts != null && carts.size() > 0) {
                //声明变量
                sb.append("   declare @CartId varchar(800) \n");
                if (postCartEntity.getIsSaveAll() == 1) {
                    //先清空购物车
                    sb.append(" delete from t710205 where UserCode =" + GridUtils.prossSqlParm(postCartEntity.getUserCode()));
                }
                for (CartEntity cartEntity : carts) {
                    sb.append("    insert into t710205 (UserCode,UserName,CltCode,CltName,MatCode,MatName,Special,PhotoPath, \n")
                            .append("      Quantity,Price,Amount,WeightUom,DateAdded,VoucherDocCode,\n")
                            .append("      refDocCode,refFormId,refFormType,refRowId,isSelected,MatGroupStatus,SalesPrice,Discount,ManualPrice,skuId1,skuName1,skuId2,skuName2,skuId3,skuName3,skuId4,skuName4,skuId5,skuName5,skuId6,skuName6,skuId7,skuName7,skuId8,skuName8,skuId9,skuName9,skuId10,skuName10)  \n")
                            .append("    values(" + GridUtils.prossSqlParm(postCartEntity.getUserCode()) + "," + GridUtils.prossSqlParm(userName) + "," + GridUtils.prossSqlParm(postCartEntity.getCltCode()) + "," + GridUtils.prossSqlParm(postCartEntity.getCltName()) + "," + GridUtils.prossSqlParm(cartEntity.getMatCode()) + "," + GridUtils.prossSqlParm(cartEntity.getMatName()) + "," + GridUtils.prossSqlParm(cartEntity.getSpecial()) + " ," + GridUtils.prossSqlParm(cartEntity.getPhotoPath()) + "," + cartEntity.getQuantity() + "," + cartEntity.getPrice() + ",round(isnull("+cartEntity.getQuantity()+",0) * isnull("+cartEntity.getManualPrice()+",0),2),null,getdate(),null," + GridUtils.prossSqlParm(postCartEntity.getRefDocCode()) + "," + postCartEntity.getRefFormId() + "," + postCartEntity.getRefFormType() + "," + GridUtils.prossSqlParm(postCartEntity.getRefRowId()) + ",1,1," + cartEntity.getSalesPrice() + "," + cartEntity.getDiscount()  +"," + cartEntity.getManualPrice()+"," + cartEntity.getSkuId1()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName1())+"," + cartEntity.getSkuId2()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName2())+"," + cartEntity.getSkuId3()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName3())+"," + cartEntity.getSkuId4()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName4())+"," + cartEntity.getSkuId5()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName5())+"," + cartEntity.getSkuId6()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName6())+"," + cartEntity.getSkuId7()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName7())+"," + cartEntity.getSkuId8()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName8())+"," + cartEntity.getSkuId9()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName9())+"," + cartEntity.getSkuId10()+"," +GridUtils.prossSqlParm(cartEntity.getSkuName10())  + ")\n")
                            .append("    SELECT @CartId =isnull(@CartId,'')+cast(@@IDENTITY as varchar) +','; \n");
                }
                sb.append(" select @CartId=left(@cartId,len(@cartId)-1) \n");
            }
            return sb.toString();
        }
 
        @Override
        public Object call() throws Exception {
            CallBackMessage callBackMessage = new CallBackMessage();
            long startTime = System.currentTimeMillis();
            try {
                SpObserver.setDBtoInstance("_" + dbid);
                String cartids = null;
                String cartSql = null;
                postCartEntity.setUserCode(userCode);
                Map map = null;
                if (dbid.equals("530")) {
                    //卤江南专用
                    map = qrServiceIfc.save120201(postCartEntity, userCode);
                } else {
                    if (actionType == 1) {
                        if (postCartEntity == null || postCartEntity.getCarts() == null || postCartEntity.getCarts().size() == 0) {
                            throw new ApplicationException("没有商品,不能下单");
                        }
                        if (postCartEntity.getFormId() == null) {
                            throw new ApplicationException("生成单据所对应目标功能号不能为空");
                        }
                        cartSql = joinCartSql();
                    } else {
                        //在购物车下单,直接取carid
                        cartids = postCartEntity.getCartids();
                    }
                    map = qrServiceIfc.savePost(postCartEntity, cartids, userCode, cartSql);
                    if (map != null) {
                        postCartEntity.setCartids(map.get("cartIds") + "");
                        final Integer result = qrServiceIfc.delCart(postCartEntity);
                        map.remove("cartIds");
                        map.put("delable", result == -1 ? 1 : 0);
                    }
                }
                if (map == null || StringUtils.isBlank(GridUtils.prossRowSetDataType_String(map, "docCode"))) {
                    throw new ApplicationException(postCartEntity.getFormId() + "生成单据出错:单号为空");
                }
                log.info("cltCode:" + userCode + "-客户:" + userCode + "下单花费:" + (System.currentTimeMillis() - startTime));
                callBackMessage.setInfo(map);
                callBackMessage.sendSuccessMessageByDefault();
                return callBackMessage.toJSONObject();
            } catch (Exception ex) {
                log.info("cltCode:" + userCode + "-客户下单出错:" + userCode + "花费:" + (System.currentTimeMillis() - startTime));
                callBackMessage.sendErrorMessage(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                return callBackMessage.toJSONObject();
            } finally {
                SpObserver.setDBtoInstance();
                log.info("---------------------end:" + userCode + "-----------------");
            }
        }
    }
 
    /**
     * 新增
     *
     * @param request
     * @param response
     */
 
    @RequestMapping(value = "/qr/addCart.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask addCart(@RequestBody PostCartEntity postCartEntity, HttpServletRequest request, HttpServletResponse response) {
 
        String userCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        String userName = request.getSession().getAttribute(SessionKey.HRNAME) + "";
        postCartEntity.setUserCode(userCode);
        Callable<Object> callable = new CartCallable(postCartEntity, null, null, userCode, userName, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", qrServiceIfc, 1);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
        asyncTask.onCompletion(
                () -> log.info("执行成功")
        );
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行出错");
                    callBackMessage.sendErrorMessage("操作出错");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行超时");
                    callBackMessage.sendErrorMessage("服务器繁忙,正在排队处理,请不要重复提交,稍后请在购物车查看结果", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    /**
     * 保存购物车商品
     *
     * @param request
     * @param response
     */
 
    @RequestMapping(value = "/qr/saveAllCart.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask saveAllCart(@RequestBody PostCartEntity postCartEntity, HttpServletRequest request, HttpServletResponse response) {
 
        String userCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        String userName = request.getSession().getAttribute(SessionKey.HRNAME) + "";
        postCartEntity.setUserCode(userCode);
        postCartEntity.setIsSaveAll(1);
        Callable<Object> callable = new CartCallable(postCartEntity, null, null, userCode, userName, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", qrServiceIfc, 4);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
        asyncTask.onCompletion(
                () -> log.info("执行成功")
        );
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行出错");
                    callBackMessage.sendErrorMessage("操作出错");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行超时");
                    callBackMessage.sendErrorMessage("服务器繁忙,正在排队处理,请不要重复提交,稍后请在购物车查看结果", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    private class CartCallable implements Callable<Object> {
        PostCartEntity postCartEntity;
        String userCode;
        String userName;
        String dbid;
        QrServiceIfc qrServiceIfc;
        int actionType = 0;//1,新增(保存相同商品只更新数量) 2,修改 3,删除,4 保存购物车商品(覆盖原有商品)
        CartEntity cartEntity;
        String idList;
 
        public CartCallable(PostCartEntity postCartEntity, CartEntity cartEntity, String idList, String userCode, String userName, String dbid, QrServiceIfc qrServiceIfc, int actionType) {
            this.postCartEntity = postCartEntity;
            this.userCode = userCode;
            this.userName = userName;
            this.dbid = dbid;
            this.qrServiceIfc = qrServiceIfc;
            this.actionType = actionType;
            this.cartEntity = cartEntity;
            this.idList = idList;
        }
 
        @Override
        public Object call() throws Exception {
            CallBackMessage callBackMessage = new CallBackMessage();
            try {
                SpObserver.setDBtoInstance("_" + dbid);
 
                Map map = new HashMap();
                switch (actionType) {
                    case 1:
                    case 4:
                        if (postCartEntity == null || postCartEntity.getCarts() == null || postCartEntity.getCarts().size() == 0) {
                            throw new ApplicationException("商品不能为空,新增失败");
                        }
                        final List<Map<String, Integer>> result = qrServiceIfc.saveCart(postCartEntity, userName);
                        if (result != null) {
                            //--增加返回购物车商品总数
                            Integer count = qrServiceIfc.getCartListCount(userCode, userName, postCartEntity.getRefDocCode());
                            map.put("data", result);
                            map.put("count", count);
                        }
                        break;
                    case 2:
                        if (cartEntity == null) {
                            throw new ApplicationException("商品不能为空,修改商品数量失败");
                        }
                        qrServiceIfc.updateCart(cartEntity);
                        break;
                    case 3:
                        if (idList == null) {
                            throw new ApplicationException("商品不能为空,删除商品失败");
                        }
                        cartIfc.delCart(idList);
                        break;
 
                }
                callBackMessage.setInfo(map);
                callBackMessage.sendSuccessMessageByDefault();
                return callBackMessage.toJSONObject();
            } catch (Exception ex) {
                callBackMessage.sendErrorMessage(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                return callBackMessage.toJSONObject();
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
    }
 
    /**
     * 更新
     *
     * @param request
     * @param response
     */
 
    @RequestMapping(value = "/qr/updateCart.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask updateCart(@RequestBody CartEntity cartEntity, HttpServletRequest request, HttpServletResponse response) {
        String userCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        String userName = request.getSession().getAttribute(SessionKey.HRNAME) + "";
        Callable<Object> callable = new CartCallable(null, cartEntity, null, userCode, userName, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", qrServiceIfc, 2);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
        asyncTask.onCompletion(
                () -> log.info("执行成功")
        );
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行出错");
                    callBackMessage.sendErrorMessage("操作出错");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    log.info("执行超时");
                    callBackMessage.sendErrorMessage("服务器繁忙,正在排队处理,请不要重复提交,稍后请在购物车查看结果", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    /**
     * 新增客户资料
     *
     * @param request
     * @param response
     */
 
    @RequestMapping(value = "/qr/save170001.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    Object save170001(@RequestBody CustomerEntity customerEntity, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            checkFormPerssion(request, 170001);
            String dbid = request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "";
            SpObserver.setDBtoInstance("_" + dbid);
            customerEntity.setAddress(customerEntity.getFullAddress());
            CustomerEntity customer = null;
            Integer result = null;
            if (StringUtils.isBlank(customerEntity.getCltName())) {
                throw new ApplicationException("客户名称不能为空");
            }
            if (StringUtils.isBlank(customerEntity.getTel())) {
                throw new ApplicationException("客户电话不能为空");
            }
            if (customerEntity.getCltCode() == null || StringUtils.isBlank(customerEntity.getCltCode())) {
                //新增
                customer = accountIfc.saveNewCustomer(customerEntity, request.getSession().getAttribute(SessionKey.USERCODE) + "");
            } else {
                //修改
                result = qrServiceIfc.update170001(customerEntity);
            }
            List<Map<String, Object>> meta = new ArrayList<>();
            String sql = this.procssSQLPersion(request, meta);
            final Map map = qrServiceIfc.get170001(customerEntity.getCltCode(), sql);
            String docCode = map.get("docCode") + "";
            //--生成二维码
            QrCodeForAppEntity qrCodeForAppEntity = new QrCodeForAppEntity();
            qrCodeForAppEntity.setAction(QrCodeForAppEntity.ViewDocument);  //设置行为 Action
            qrCodeForAppEntity.setAuthorCode((String) request.getSession().getAttribute(SessionKey.HRCODE));
            qrCodeForAppEntity.setAuthorName((String) request.getSession().getAttribute(SessionKey.HRNAME));
            qrCodeForAppEntity.setRefFormId(170001);
            qrCodeForAppEntity.setRefDocCode(docCode);
            qrCodeForAppEntity.setRefFormType(16);
            qrCodeForAppEntity = qrServiceIfc.createQrCode(qrCodeForAppEntity);
            if (qrCodeForAppEntity == null || StringUtils.isBlank(qrCodeForAppEntity.getQrCode())) {
                throw new ApplicationException("请检查" + qrCodeForAppEntity.getRefFormId() + "在9801是否勾选上【生成单据二维码】参数设置");
            } else {
                map.put("qrCode", qrCodeForAppEntity.getQrCode());
            }
 
            //---与购物车中还没有关联的物料进行关联处理
            final Integer updateresult = qrServiceIfc.updateRefBy170001(map.get("doccode") + "", map.get("formId") + "", map.get("formtype") + "", request.getSession().getAttribute(SessionKey.USERCODE) + "");
            if (customer != null) {
                callBackMessage.sendSuccessMessage("新建成功");
            } else {
                //修改
                if (result == 0) {
                    throw new ApplicationException("更新客户资料出错");
                } else {
                    callBackMessage.sendSuccessMessage("更新成功");
                }
            }
            callBackMessage.setInfo(map);
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            ex.printStackTrace();
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 检查指定功能号是否有权限
     *
     * @param request
     * @param formid
     */
    public void checkFormPerssion(HttpServletRequest request, int formid) {
        //---检查权限
        if (Integer.parseInt(request.getSession().getAttribute(SessionKey.SUPPER_USER) + "") == 0) {
            final Map attribute = (Map) request.getSession().getAttribute(SessionKey.PERSSION);
            if (!attribute.containsKey(formid+"")) {// TODO key为String类型,containsKey传的参数类型也要强制转换成String类型 ,不然会出现本来是存在,又找不到的情况,特别注意
                //不存在于权限集合表示不需要输出
                throw new ApplicationException("没有新增客户资料的权限");
            }
        }
    }
 
    /**
     * 搜索客户资料
     *
     * @param request
     * @param response
     */
 
    @RequestMapping(value = "/qr/list170001.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    Object list170001(@RequestBody ProducParmBean producParmBean, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            this.checkFormPerssion(request, 170001);
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            //--处理权限,读取9802设置
            List<Map<String, Object>> meta = new ArrayList<>();
            String sql = this.procssSQLPersion(request, meta);
            GTGrid gtGrid =(GTGrid) FactoryBean.getBean("GTGrid");
            final String dataGroupInfo = gtGrid.getDataGroupInfo(170001, request.getSession().getAttribute(SessionKey.USERCODE) + "", 0, request.getSession());
            final List list = qrServiceIfc.list170001(producParmBean, sql,dataGroupInfo);
 
            //if (list !=null&&list.size()>0) {
            callBackMessage.sendSuccessMessage("成功");
            callBackMessage.setInfo(list);
            return callBackMessage.toJSONObject();
            //  }
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 显示客户资料明细
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/get170001.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object get170001(String cltCode, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            this.checkFormPerssion(request, 170001);
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            Map map = new HashMap();
            //--处理权限,读取9802设置
            List<Map<String, Object>> meta = new ArrayList<>();
            String sql = this.procssSQLPersion(request, meta);
            if (StringUtils.isNotBlank(cltCode)) {
                map.put("customer", qrServiceIfc.get170001(cltCode, sql));
            }
            callBackMessage.sendSuccessMessage("成功");
            map.put("9802", meta);
            final BaseService baseService = (BaseService) FactoryBean.getBean("BaseService");
            map.put("cltType", baseService.getSimpleJdbcTemplate().queryForList("select a.CltType as fieldId,a.CltType as fieldName from t110201 a order by a.CltType asc"));
            callBackMessage.setInfo(map);
            return callBackMessage.toJSONObject();
 
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 根据电话查询客户资料
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/get170001ByTel.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object get170001ByTel(String tel, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            this.checkFormPerssion(request, 170001);
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            Map map = new HashMap();
            //--处理权限,读取9802设置
            List<Map<String, Object>> meta = new ArrayList<>();
            String sql = this.procssSQLPersion(request, meta);
 
            if (StringUtils.isBlank(tel)) {
                throw new ApplicationException("电话不能为空");
            }
            T110203 t110203 = qrServiceIfc.get170001ByTel(tel, sql);
            callBackMessage.sendSuccessMessage("成功");
            callBackMessage.setInfo(t110203);
            return callBackMessage.toJSONObject();
 
        } catch (EmptyResultDataAccessException e) {
            callBackMessage.sendSuccessMessage("成功");
            callBackMessage.setInfo(new T110203());
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    private String procssSQLPersion(HttpServletRequest request, List<Map<String, Object>> meta) {
        final List<Map<String, Object>> list = gridService.getSimpleJdbcTemplate().queryForList("set nocount on ; select " + gridService.getGET_GFIELD().toLowerCase() + " from gfield where formid=170001 and headflag=0 order by statisid asc");
        String sql = "";
        List<String> valueExp = new ArrayList<>();//字段(id,权限,css,tips)
        String fieldNames = ";cltcode;cltname;tel;tel2;fulladdress;clttype;linkman;";//需要显示的字段
        for (Map<String, Object> map : list) {
            String fieldId = GridUtils.prossRowSetDataType_String(map, "fieldid");
            if (fieldNames.contains(";" + fieldId.toLowerCase() + ";")) {
                Map<String, Object> met = new HashMap<>();
                met.put("fieldId", fieldId.toLowerCase());
 
                //--权限表达式
                if (!"".equalsIgnoreCase(GridUtils.prossRowSetDataType_String(map, "ShowFieldValueExpression"))) {
                    String expr = " case when (" + map.get("ShowFieldValueExpression") + ") =1 then 1   when (" + map.get("ShowFieldValueExpression") + ") =2 then 2 else 0 end as [" + fieldId.toLowerCase() + "_expr]";
                    String value = " case  (" + map.get("ShowFieldValueExpression") + ") when  0  then '******' else " + fieldId.toLowerCase() + " end as [" + fieldId.toLowerCase() + "]";
                    valueExp.add(value);
                    valueExp.add(expr);
                } else {
                    valueExp.add("[" + fieldId.toLowerCase() + "]");
                }
                //只读
                met.put("readOnly", GridUtils.prossRowSetDataType_Integer(map, "ReadOnly"));
                //初始值
                met.put("initValue", GridUtils.prossRowSetDataType_String(map, "initValue"));
                meta.add(met);
            }
        }
 
        sql = String.join(",", valueExp);
        //替换会话参数
        Pattern p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
        java.util.regex.Matcher propsMatcher = p.matcher(sql);
        while (propsMatcher.find()) {
            sql = sql.replaceAll(propsMatcher.group(), request.getSession().getAttribute(propsMatcher.group().toLowerCase()) + "");
        }
        return sql;
    }
 
    /**
     * 保存扫码显示方式
     *
     * @param request
     * @param response
     */
 
    @RequestMapping(value = "/qr/qrScanType.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object saveQrSanType(int type, int isRelatingMaterialWhenNewCustomer, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
 
            final Integer result = qrServiceIfc.saveQrScanType(request.getSession().getAttribute(SessionKey.USERCODE) + "",
                    request.getSession().getAttribute(SessionKey.USER_NAME) + "",
                    type, isRelatingMaterialWhenNewCustomer);
            if (result > 0) {
                callBackMessage.sendSuccessMessage("提交成功");
                return callBackMessage.toJSONObject();
            } else {
                callBackMessage.sendErrorMessage("提交出错");
                return callBackMessage.toJSONObject();
            }
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 扫码取数
     *
     * @param refPostCartEntity 引用的原始单据功能号实体
     * @param response
     */
    @RequestMapping(value = "/qr/qrScan.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    Object qrScan(@RequestBody PostCartEntity refPostCartEntity, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            String dbid=request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"";
            SpObserver.setDBtoInstance("_" + dbid);
            T112002 t112002 = new T112002();
            if (refPostCartEntity.getQrCode().startsWith("2003")) {
                //API对接认证二维码
                RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
                final Object object = redisTemplate.opsForValue().get(RedisKey.MUTUAL_QRCODE + ":" + refPostCartEntity.getQrCode());
                if (object != null) {
                    t112002.setAction(QrCodeForAppEntity.AUTH);
                    //增加当前用户的companyName,logo。输出到前端
                    String companyName = request.getSession().getAttribute(SessionKey.COMPANY_NAME) + "";
                    String domain = request.getSession().getAttribute(SessionKey.DOMAIN) + "";
                    MutualController mutualController=(MutualController)FactoryBean.getBean("mutualController");
                    String logo =mutualController.getLogo(dbid);
                    Map ownMap =JSON.parseObject(String.valueOf(object),HashMap.class);
                    Map qrCodeDate=(Map)ownMap.get("qrCodeData");
                    qrCodeDate.put("ownCompanyName",companyName);
                    qrCodeDate.put("ownLogo",domain+logo);
                    t112002.setQueryString(GridUtils.toJson(ownMap));
                    Map map = new HashMap();
                    map.put("qrCodeInfo", t112002);
                    callBackMessage.setInfo(map);
                } else {
                    throw new ApplicationException("二维码已过期");
                }
            } else {
                t112002 = qrServiceIfc.getT112002(refPostCartEntity.getQrCode());
                callBackMessage.setInfo(getProductInfo(t112002, refPostCartEntity, request, response));
            }
 
            callBackMessage.sendSuccessMessage("成功");
            return callBackMessage.toJSONObject();
        } catch (EmptyResultDataAccessException e) {
            callBackMessage.sendErrorMessage(refPostCartEntity.getQrCode() + "码不存在");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 通过原始单据取得引用物料列表
     *
     * @param refPostCartEntity 引用的原始单据功能号实体
     * @param response
     */
    @RequestMapping(value = "/qr/getRefMatCodes.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    Object getRefMatCodes(@RequestBody PostCartEntity refPostCartEntity, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
 
 
            callBackMessage.setInfo(getRefMatCodeList(refPostCartEntity, request));
 
            callBackMessage.sendSuccessMessage("成功");
            return callBackMessage.toJSONObject();
        } catch (EmptyResultDataAccessException e) {
            callBackMessage.sendErrorMessage(refPostCartEntity.getQrCode() + "码不存在");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    private Map getRefMatCodeList(PostCartEntity refPostCartEntity, HttpServletRequest request) {
        Integer formid = refPostCartEntity.getFormId();
        if (formid != null && formid != 0) {
            //需要通过formid查找9802设置的QrCodeSqlScript,执行sql返回相关联的物料,返回给前端
            final QrCodeRefEntity refProduct = qrServiceIfc.getRefProduct(formid);
            if (refProduct != null) {
                if (StringUtils.isNotBlank(refProduct.getQrCodeSqlScript())) {
                    Map qrMap = new HashMap();
                    if (StringUtils.isBlank(refProduct.getQrCodeRefRowId())) {
                        throw new ApplicationException("请在9802中为【" + refProduct.getFieldid() + "】字段设置参数【APP扫码|引用外表RowId字段名】");
                    }
                    qrMap.put("refRowid", refProduct.getQrCodeRefRowId());
                    if (StringUtils.isBlank(refProduct.getQrCodeRefDigit())) {
                        throw new ApplicationException("请在9802中为【" + refProduct.getFieldid() + "】字段设置参数【APP扫码|引用外表数量字段名】");
                    }
                    qrMap.put("refDigit", refProduct.getQrCodeRefDigit());
                    String sql = refProduct.getQrCodeSqlScript();
                    //&..&替换
                    Pattern p = Pattern.compile("&.*?&");
                    Matcher m = p.matcher(sql);
                    while (m.find()) {
                        String field = m.group().replaceAll("&", "");
                        if (field.equalsIgnoreCase("matcode")) {
 
                            sql = sql.replaceAll(m.group(), refPostCartEntity.getMatCode());
                        } else if (field.equalsIgnoreCase("refformid")) {
                            sql = sql.replaceAll(m.group(), refPostCartEntity.getRefFormId() + "");
                        } else if (field.equalsIgnoreCase("refdoccode")) {
                            sql = sql.replaceAll(m.group(), refPostCartEntity.getRefDocCode() + "");
                        } else if (field.equalsIgnoreCase("refformtype")) {
                            sql = sql.replaceAll(m.group(), refPostCartEntity.getRefFormType() + "");
                        }
                    }
                    //会话替换
                    sql = filterSession(sql, request);
                    List<Map<String, Object>> qrCodeSqlScriptMatCode = null;
                    try {
                        qrCodeSqlScriptMatCode = qrServiceIfc.getQrCodeSqlScriptMatCode(sql);
                        if (qrCodeSqlScriptMatCode != null && qrCodeSqlScriptMatCode.size() == 0) {
                            throw new ApplicationException("当前引用" + refPostCartEntity.getRefDocCode() + "单据不存在" + refPostCartEntity.getMatCode() + "物料,请重新确认");
                        }
                    } catch (EmptyResultDataAccessException e) {
                        throw new ApplicationException("当前引用" + refPostCartEntity.getRefDocCode() + "单据不存在" + refPostCartEntity.getMatCode() + "物料,请重新确认");
                    }
 
                    qrMap.put("refProduct", qrCodeSqlScriptMatCode);
                    return qrMap;
                }
                return null;
            }
        }
        return null;
    }
 
    /**
     * 显示单据二维码
     *
     * @param qrCode   二维码
     * @param response
     */
    @RequestMapping(value = "/qr/showQrCode.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object showQrCode(String qrCode, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            T112002 t112002 = qrServiceIfc.getT112002(qrCode);
            callBackMessage.setInfo(imgData.getImageUrl(t112002.getQrCodeUnid(), null,
                    null, true,
                    false, request));
            callBackMessage.sendSuccessMessage("成功");
            return callBackMessage.toJSONObject();
        } catch (EmptyResultDataAccessException e) {
            callBackMessage.sendErrorMessage(qrCode + "码不存在");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    private Map getProductInfo(T112002 t112002, PostCartEntity refPostCartEntity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        map.put("qrCodeInfo", t112002);
        if (QrCodeForAppEntity.ViewMaterial.equalsIgnoreCase(t112002.getAction())) {
            //扫物料
            Integer formid = refPostCartEntity.getFormId();
            final Map matCodeMap = this.getMatCode(t112002.getMatCode(), request, response);
            map.put("product", matCodeMap);
            if (formid != null && formid != 0) {
                refPostCartEntity.setMatCode(matCodeMap.get("MatCode") + "");
                map.put("refData", this.getRefMatCodeList(refPostCartEntity, request));
            }
 
        } else if (QrCodeForAppEntity.ViewDocument.equalsIgnoreCase(t112002.getAction())) {
            //扫单据
            // refFormIdList = getRefFormIdList(request, t112002.getRefFormId());
            //map.put("reFormids", refFormIdList);
        }
        return map;
    }
 
    private String filterSession(String filter, HttpServletRequest request) {
        if ("".equals(filter)) return filter;
        Pattern p = Pattern.compile("@.*?\\w+");
        Matcher m = p.matcher(filter);
        while (m.find()) {//存在
            filter = filter.replaceAll(m.group(), request.getSession().getAttribute(m.group()) + "");
        }
        return filter;
    }
 
    /**
     * 查看商品明细
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/product.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object product(String matCode, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            callBackMessage.setInfo(this.getMatCode(matCode, request, response));
            callBackMessage.sendSuccessMessage("成功");
            return callBackMessage.toJSONObject();
        } catch (EmptyResultDataAccessException e) {
            callBackMessage.sendErrorMessage(matCode + "不存在");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 更新购物车里没有关联的物料到指定引用单据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/updateRef.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    Object product(@RequestBody PostCartEntity postCartEntity, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            Integer result = qrServiceIfc.updateRef(postCartEntity);
            if (result > 0) {
                callBackMessage.sendSuccessMessageByDefault();
                return callBackMessage.toJSONObject();
            } else {
                throw new ApplicationException("更新出错,请重试");
            }
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 商品分类显示
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/matGroups.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object matGroups(HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        String dbid=request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"";
        try {
            SpObserver.setDBtoInstance("_" +dbid );
            GTGrid gtGrid =(GTGrid)FactoryBean.getBean("GTGrid");
            final HttpSession session = request.getSession();
            final String dataGroupInfo = gtGrid.getDataGroupInfo(110501, session.getAttribute(SessionKey.USERCODE) + "", 0, session);
            final List<MatGroupEntity> groups = qrServiceIfc.getMatGroups(dataGroupInfo);
            List<Map> groupList = new ArrayList();
            String matgourpId = null;
            String hostUrl = SettingKey.getHostUrlForImage(request);
            List<MatGroupEntity> mainGroup=groups.stream().filter(x->(
                x.getParentRowid()==null||x.getParentRowid().equals(""))
            ).collect(Collectors.toList());
            if(mainGroup!=null&&mainGroup.size()>0) {
                for (MatGroupEntity matGroupEntity : mainGroup) {
                    Map matGroup = new HashMap();
                    //1级分类
                    matGroup.put("MatGroupName", matGroupEntity.getMatGroupName());
                    matGroup.put("MatGroup", matGroupEntity.getMatGroup());
                    if (matgourpId == null) {
                        matgourpId = matGroupEntity.getMatGroup();
                    }
                    //2级分类
                    List<MatGroupEntity> subMatGroupList = groups.stream().filter(x -> (
                            x.getParentRowid().equals(matGroupEntity.getRowid())
                    )).collect(Collectors.toList());//qrServiceIfc.getMatGroupsByParentRowId(matGroupEntity.getRowid());
                    List<Map> subList = new ArrayList<>();
                    if(subMatGroupList!=null&&subMatGroupList.size()>0) {
                        subMatGroupList.stream().forEach(x -> {
                            Map subMap = new HashMap();
                            subMap.put("SubMatGroupName", x.getMatGroupName());
                            subMap.put("SubMatGroup", x.getMatGroup());
                            subList.add(subMap);
                        });
                    }
                    matGroup.put("subList", subList);
                    groupList.add(matGroup);
                }
                final List<MatCodeEntity> matCodeEntityList = qrServiceIfc.getMatCodesByMatGroup(matgourpId, 50, 1);
//                matCodeEntityList.stream().map(x -> {
//                    x.setPhotoPath(imgData.getImageUrl(x.getPhotoPath(), 120,
//                            120, false,
//                            false, request));
//                    return x;
//                }).collect(Collectors.toList());
                matCodeEntityList.stream().forEach(x -> {
                    x.setPhotoPath(SettingKey.getUrl(hostUrl, x.getPhotoPathUrl(), dbid+"",null));
                    x.setPhotoPathUrl(SettingKey.getUrl(hostUrl, x.getPhotoPathUrl(), dbid+"",null));
                });
                Map nodes = new HashMap();
                nodes.put("nodes", groupList);
                nodes.put("data", matCodeEntityList);
                nodes.put("appSalesOrderStyle", request.getSession().getAttribute(SessionKey.APP_SALESORDER_STYLE));
                callBackMessage.setInfo(nodes);
            }
            callBackMessage.sendSuccessMessage("成功");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 商品列表显示
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/productList.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    Object productList(@RequestBody ProducParmBean producParmBean, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            String dbid=request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"";
            String hostUrl = SettingKey.getHostUrlForImage(request);
            SpObserver.setDBtoInstance("_" +dbid );
            final List<MatCodeEntity> matCodeEntityList = qrServiceIfc.getMatCodesByMatGroup(producParmBean.getValue(), producParmBean.getLimit(), producParmBean.getPage());
 
//            matCodeEntityList.stream().map(x -> {
//                x.setPhotoPath(imgData.getImageUrl(x.getPhotoPath(), 120,
//                        120, false,
//                        false, request));
//                return x;
//            }).collect(Collectors.toList());
            matCodeEntityList.stream().forEach(x -> {
                x.setPhotoPath(SettingKey.getUrl(hostUrl, x.getPhotoPathUrl(), dbid+"",null));
                x.setPhotoPathUrl(SettingKey.getUrl(hostUrl, x.getPhotoPathUrl(), dbid+"",null));
            });
            callBackMessage.setInfo(matCodeEntityList);
            callBackMessage.sendSuccessMessage("成功");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 商品搜索
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/searchProduct.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    Object searchProduct(@RequestBody ProducParmBean producParmBean, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            String dbid=request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"";
            SpObserver.setDBtoInstance("_" + dbid);
            String hostUrl = SettingKey.getHostUrlForImage(request);
            final List<MatCodeEntity> matCodeEntityList = qrServiceIfc.getMatCodesByMatGroupBySearch(producParmBean.getValue(), producParmBean.getLimit(), producParmBean.getPage());
//            matCodeEntityList.stream().map(x -> {
//                x.setPhotoPath(imgData.getImageUrl(x.getPhotoPath(), 120,
//                        120, false,
//                        false, request));
//                return x;
//            }).collect(Collectors.toList());
            matCodeEntityList.stream().forEach(x -> {
                x.setPhotoPath(SettingKey.getUrl(hostUrl, x.getPhotoPathUrl(), dbid+"",null));
                x.setPhotoPathUrl(SettingKey.getUrl(hostUrl, x.getPhotoPathUrl(), dbid+"",null));
            });
            callBackMessage.setInfo(matCodeEntityList);
            callBackMessage.sendSuccessMessage("成功");
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 保存2002类型的二维码单据信息
     *
     * @param targetFormId   生成目标功能号
     * @param targetFormName 生成目标功能名称
     */
    @RequestMapping(value = "/qr/save112005.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object save112005(String qrCode, String targetFormId, String targetFormName, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            T112002 t112002 = qrServiceIfc.getT112002(qrCode);
            if (t112002 != null && StringUtils.isNotBlank(t112002.getQueryString())) {
                Map map = GridUtils.fromJson(t112002.getQueryString());
                if (map != null) {
                    T112005 t112005 = new T112005();
                    t112005.setUserCode(request.getSession().getAttribute(SessionKey.USERCODE) + "");
                    t112005.setRefFormId(GridUtils.prossRowSetDataType_Int(map, "FormId"));
                    t112005.setRefFormType(GridUtils.prossRowSetDataType_Int(map, "FormType"));
                    t112005.setRefDocCode(GridUtils.prossRowSetDataType_String(map, "DocCode"));
                    t112005.setTargetFormId(targetFormId);
                    t112005.setTargetFormName(targetFormName);
                    t112005.setQrCode(qrCode);
                    t112005.setQrCodeUnid(t112002.getQrCodeUnid());
                    t112005.setQueryString(t112002.getQueryString());
                    Integer result = qrServiceIfc.save112005(t112005);
                    Map rst = new HashMap(2);
                    rst.put("qrCodeInfo", t112002);
                    rst.put("count", result);
                    callBackMessage.setInfo(rst);
                    callBackMessage.sendSuccessMessage("成功");
                }
            } else {
                callBackMessage.sendErrorMessage(qrCode + "码查找不到相关数据");
            }
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 删除2002类型的二维码单据信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/del112005.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object del112005(String docCode, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            T112005 t112005 = new T112005();
            t112005.setUserCode(request.getSession().getAttribute(SessionKey.USERCODE) + "");
 
            t112005.setRefDocCode(docCode);
 
            Integer result = qrServiceIfc.del112005(t112005);
            if (result > 0) {
                callBackMessage.sendSuccessMessage("成功");
            } else {
                callBackMessage.sendErrorMessage("删除出错");
            }
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 2002类型的二维码单据信息列表
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/list112005.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object list112005(HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
 
 
            List<T112005> list112005 = qrServiceIfc.list112005(request.getSession().getAttribute(SessionKey.USERCODE) + "");
            if (list112005 != null && list112005.size() > 0) {
                callBackMessage.sendSuccessMessage("成功");
                callBackMessage.setInfo(list112005);
            }
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 取得关联功能号
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/qr/getRefFormIds.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    Object getRefFormIds(Integer refFormid,Integer targetFormid, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            final List<Gfrom> refFormIdList = this.getRefFormIdList(request, refFormid,targetFormid);
            if (refFormIdList == null || refFormIdList.size() == 0) {
                if (refFormid != null) {
                    //针对扫码方式,refFormid是有值
                    throw new ApplicationException("请设置要生成的目标单据功能号,在9802中为扫码字段设置【APP扫码|引用外表功能号【多值用分号隔开】】参数");
                } else {
                    //针对下单方式,refFormid是没有值,也就是没有关联
                    throw new ApplicationException("在下单方式下请确保要生成的目标单据功能号,在9802中为扫码字段设置【APP扫码|引用外表功能号【多值用分号隔开】】参数要为空");
                }
            } else {
                callBackMessage.sendSuccessMessage("成功");
                callBackMessage.setInfo(refFormIdList);
                return callBackMessage.toJSONObject();
            }
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(this.getErrorMsg(ex));
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    public List<Gfrom> getRefFormIdList(HttpServletRequest request, Integer refFormid,Integer targetFormid) {
        //---二维码关联的功能号
        List<Gfrom> refFormIdList = qrServiceIfc.getRefFormIdList(refFormid);
        if (refFormIdList == null || refFormIdList.size() == 0) {
            throw new ApplicationException("未找到可生成的目标功能号");
        }
        return procFormLimitV2(request, refFormIdList,targetFormid);
    }
 
    public List<Gfrom> procFormLimit(HttpServletRequest request, List<Gfrom> refFormIdList) {
        if (Integer.parseInt(request.getSession().getAttribute(SessionKey.SUPPER_USER) + "") == 0) {
            //---取出当前用户的功能号权限集合
            final Map attribute = (Map) request.getSession().getAttribute(SessionKey.PERSSION);
            Iterator<Gfrom> iterator = refFormIdList.iterator();
            while (iterator.hasNext()) {
                Gfrom gfrom = iterator.next();
                if (!attribute.containsKey(gfrom.getFormid() + "")) {
                    //不存在于权限集合表示不需要输出
                    iterator.remove();
                }
            }
        }
        return refFormIdList;
    }
 
    /**
     * 增加对下单,采购订单下单的分别处理
     * @param request
     * @param refFormIdList
     * @param targetFormid
     * @return
     */
    public List<Gfrom> procFormLimitV2(HttpServletRequest request, List<Gfrom> refFormIdList,Integer targetFormid) {
            //---取出当前用户的功能号权限集合
            final Map attribute = (Map) request.getSession().getAttribute(SessionKey.PERSSION);
            Iterator<Gfrom> iterator = refFormIdList.iterator();
            boolean isAdmin=false;//是否管理员
            String supperUser= (String) request.getSession().getAttribute(SessionKey.SUPPER_USER);
            if(StringUtils.isNotBlank(supperUser)){
                if(Integer.parseInt(supperUser)==1){
                    isAdmin=true;
                }
            }
            while (iterator.hasNext()) {
                Gfrom gfrom = iterator.next();
                if(targetFormid==null) {
                    //表示调用不是采购下单的另一个下单功能,则就算有生成130301权限也需要排除
                    if (130301==gfrom.getFormid().intValue()||(!isAdmin&&!attribute.containsKey(gfrom.getFormid() + ""))
                            ) {
                        //不存在于权限集合表示不需要输出
                        iterator.remove();
                    }
                }else{
                    //执行是采购订单下单,则除了自己(采购订单),其他的都要排除
                    if(gfrom.getFormid()==null||gfrom.getFormid().intValue()!=targetFormid.intValue()){
                        iterator.remove();
                    }
                }
            }
        return refFormIdList;
    }
    public Map getMatCode(String matCode, HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String userCode = (session.getAttribute(SessionKey.USERCODE) == null ? ""
                : (String) session.getAttribute(SessionKey.USERCODE));
        String openId = (session.getAttribute(SessionKey.WEIXIN_OPENID) == null ? "" : (String) session.getAttribute(SessionKey.WEIXIN_OPENID));
        //String wx = (session.getAttribute(SessionKey.WEIXIN_FROM) == null ? "" : (String) session.getAttribute(SessionKey.WEIXIN_FROM));
 
        boolean isMoblieBrowser = SettingKey.isMoblieBrowser(request);
 
        //depositDocCode 和 depositRowId 表示取 维护抢购订金分组 710170 里的明细
        String depositDocCode = request.getParameter("DepositDocCode");
        String depositRowId = request.getParameter("DepositRowId");
 
 
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SettingEntity settingEntity = null;
 
 
        try {
            DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(request);
            SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());// 切换数据源
            settingEntity = settingIfc.getSettingEntity(request);
 
            // 取网店 shopcccode
            ShopCcCodeEntity shopCcCodeEntity = ShopCcCode.getShopCcCode(settingEntity, request);
 
 
            String hostUrl = SettingKey.getHostUrl(request);
            // 将微信corpid组装成url
            String wxQueryString = SettingKey.getQueryStringByWx(request);
 
            // 商品编号信息
            MatCodeEntity matCodeEntity = qrServiceIfc.getMatCodeForAPP(matCode, shopCcCodeEntity.getShopCcCode());
            if (matCodeEntity == null) {
                throw new ApplicationException("商品编号【" + matCode + "】不存在");
 
            }
            // 商品附加图片信息
            List<MatCodeImageEntity> matImageList = matCodeImageIfc.getMatCodeImage(matCode);
 
            // 商品评价条数
            Integer matReviewCount = 0;
            matReviewCount = matCodeEntity.getRatingCount();
 
            // 消费积份
            Integer points = matPointsIfc.getMatPoints(matCode, null);
 
            // 商品促销活动关联表
            List<MatDiscountEntity> matDisList = matDiscountIfc.getMatDiscount(matCode, null);
 
            // 取处理过的商品描述
            String matDmatDescription = imgData.getDescriptionByNewImgLink(matCodeEntity.getDescription(), request);
 
            // 购物车
            // cartList = cartIfc.getCarts(userCode, sessionId,openId,cltCode);
 
            // 关注商品资料
            // matCodeList =
            // matCodeIfc.getMatCodesByWishList(userCode,sessionId,openId,cltCode,shopCcCode);
            // List<MatCodeEntity> matCodeCompareList =
            // matCodeIfc.getMatCodesByCompare(userCode,sessionId,openId,cltCode,shopCcCode);
 
            // 显示分享信息
            // ShareEntity shareEntity=shareIfc.getShareEntity();
 
            // 是否有选项要显示
            boolean hasMatAttr = true;// matAttrIfc.hasMatAttr(matCode);
 
            Map jsonObject = new HashMap();
 
            String url = "", externalURL = "";
            String imageHostUrl = shoppingImageDataIfc.getImageHostUrl(hostUrl);
            if (matCodeEntity.getExternalURL() != null && !"".equals(matCodeEntity.getExternalURL())) {
                externalURL = matCodeEntity.getExternalURL();
                if (!externalURL.startsWith("http")) externalURL = imageHostUrl + externalURL;
                String separator = "?";
                int pos = externalURL.indexOf("?");
                if (pos > 0) separator = "&";
                externalURL = externalURL + (wxQueryString == null || "".equals(wxQueryString) ? "" : separator + wxQueryString);
            } else {
                url = imageHostUrl + SettingKey.getMatCodeUrl("", matCodeEntity.getMatCode(), isMoblieBrowser)
                        + (wxQueryString == null || "".equals(wxQueryString) ? "" : "&" + wxQueryString);
            }
 
            jsonObject.put("ExternalUrl", externalURL);
            //jsonObject.addProperty("url", url);
            jsonObject.put("MatCodeUrl", url);
            //主图片
            jsonObject.put("PhotoPath",
                    SettingKey.getUrl(imageHostUrl, matCodeEntity.getPhotoPathUrl(), dataSourceEntity.getDbId() + "", null)
                    //+ (wxQueryString == null || "".equals(wxQueryString) ? "" : "?" + wxQueryString)
            );
            jsonObject.put("PhotoUnid", matCodeEntity.getPhotoPath());
            // 主图片与多图片合并
            List<String> subImageListArray = new ArrayList<>();
            if (matCodeEntity.getPhotoPath() != null && !matCodeEntity.getPhotoPath().equals("")) {
                subImageListArray.add(SettingKey.getUrl(imageHostUrl, matCodeEntity.getPhotoPathUrl(), dataSourceEntity.getDbId() + "", null));
                //               subImageListArray.add(imgData.getImageUrl(matCodeEntity.getPhotoPath(), settingEntity.getImageProductWidth(),
//                        settingEntity.getImageProductHeight(), settingEntity.isShowProductOrgImage(),
//                        settingEntity.isFromCached(), request)
//                        //+ (wxQueryString == null || "".equals(wxQueryString) ? "" : "?" + wxQueryString)
//                );
            }
            //主图片与多图片合并
//            for (int k = 0; matImageList != null && k < matImageList.size(); k++) {
//                MatCodeImageEntity matImage = matImageList.get(k);
//                subImageListArray.add(imgData.getImageUrl(matImage.getImage(), settingEntity.getImagePopupWidth(),
//                        settingEntity.getImagePopupHeight(), settingEntity.isShowPopupOrgImage(),
//                        settingEntity.isFromCached(), request)
//                        //+ (wxQueryString == null || "".equals(wxQueryString) ? "" : "?" + wxQueryString)
//                );
//            }
 
            if (matCodeEntity.getImagesUrl() != null && !matCodeEntity.getImagesUrl().equals("")) {
                String images[] = matCodeEntity.getImagesUrl().split(";");
                for (int j = 0; j < images.length; j++) {
                    subImageListArray.add(SettingKey.getUrl(imageHostUrl, images[j], dataSourceEntity.getDbId() + "", null));
                }
            }
 
            jsonObject.put("images", subImageListArray);
            String cltCode = (String) session.getAttribute(SettingKey.CLTCODE);
 
            //是否显示评价
            jsonObject.put("isShowReviewStatus", settingEntity.getReviewStatus());
            // 商品评价
            if (settingEntity.getReviewStatus()) {
 
            }
 
            if (settingEntity.isShowBrand()) {
                jsonObject.put("Brand", matCodeEntity.getBrand());
            }
 
            jsonObject.put("MatName", matCodeEntity.getMatName());
            jsonObject.put("MatCode", matCodeEntity.getMatCode());
            jsonObject.put("startupSkuParameters", matCodeEntity.isStartupSkuParameters());
            jsonObject.put("ShopMatCode", matCodeEntity.getShopMatCode());
            jsonObject.put("isShowMatCode", settingEntity.isShowMatCode());
            jsonObject.put("isShowMatName", settingEntity.isShowMatName());
            jsonObject.put("isShowSpecial", settingEntity.isShowSpecial());
            jsonObject.put("isShowPrice", settingEntity.isShowPrice());
            jsonObject.put("isShowPoints", settingEntity.isShowPoints());
            jsonObject.put("isShowBrand", settingEntity.isShowBrand());
            jsonObject.put("StockDisplay", settingEntity.getStockDisplay());
 
            jsonObject.put("isStartupMatName2", settingEntity.isStartupMatName2());
            jsonObject.put("isStartupMatName3", settingEntity.isStartupMatName3());
            jsonObject.put("isStartupMatName4", settingEntity.isStartupMatName4());
 
            if (settingEntity.isShowSpecial()) {
                jsonObject.put("Special", matCodeEntity.getSpecial());
            }
 
            if (settingEntity.isStartupMatName2()) {
                jsonObject.put("MatName2Label", settingEntity.getMatName2Label());
                jsonObject.put("MatName2", matCodeEntity.getMatName2());
            }
 
            if (settingEntity.isStartupMatName3()) {
                jsonObject.put("MatName3Label", settingEntity.getMatName3Label());
                jsonObject.put("MatName3", matCodeEntity.getMatName3());
            }
 
            if (settingEntity.isStartupMatName4()) {
                jsonObject.put("MatName4Label", settingEntity.getMatName4Label());
                jsonObject.put("MatName4", matCodeEntity.getMatName4());
            }
 
            if (settingEntity.isShowPoints()) {
                jsonObject.put("Points", matCodeEntity.getPoints()); // 奖励积分
                jsonObject.put("SalesPoints", points + ""); // 消费积分
            }
 
            if (matCodeEntity.getStockStatusName() != null && !"".equals(matCodeEntity.getStockStatusName())) {
                jsonObject.put("StockStatusName", matCodeEntity.getStockStatusName());
            }
 
            if (settingEntity.isShowPrice()) {
 
                MatPriceEntity matPriceEntity = matPriceIfc.getMatPrice(matCodeEntity.getMatCode(), cltCode, null);
                Double price = matPriceEntity.getPrice();
                jsonObject.put("Price", price); // 实际价格,此价格可能低于“标价”
                jsonObject.put("SalesPrice", matCodeEntity.getSalesPrice()); // 标价
                jsonObject.put("purchasePrice", matCodeEntity.getPurchasePrice()); // 采购单价
 
                CurrencyEntity currencyEntity = new CurrencyEntity(request);
                jsonObject.put("Currency", currencyEntity == null ? "" : currencyEntity.getCurrency());
                jsonObject.put("CurrencySign", currencyEntity == null ? "" : currencyEntity.getCurrencySign());
            }
            jsonObject.put("Quantity", matCodeEntity.getQuantity());
 
            List<Map> matDisListJsonArray = new ArrayList<>();
            // 商品促销活动关联表
            for (int i = 0; matDisList != null && i < matDisList.size(); i++) {
                Map subJsonObject = new HashMap();
                subJsonObject.put("digit", matDisList.get(i).getDigit());
                subJsonObject.put("price", matDisList.get(i).getPrice());
                matDisListJsonArray.add(subJsonObject);
            }
 
            jsonObject.put("matdiscount", matDisListJsonArray);
 
            // 获取商品选项(如:数量,日期。。。)
            // matComponentIfc.getMatComponent(matCodeEntity, matCode,
            // currencyEntityProd.getMemo(),isMoblieBrowser,false) ;
 
            // 评星级分
            if (settingEntity.isShowRatingOnHomePage()) {
                jsonObject.put("RatingAvg", matCodeEntity.getRatingAvg() + "");
            }
 
            // 评价条数
            if (settingEntity.getReviewStatus()) {
                jsonObject.put("ReviewCount", (matReviewCount == null ? 0 : matReviewCount) + "");
            }
 
            // 商品描述
            jsonObject.put("Description", matDmatDescription);
            //是否显示属性
            jsonObject.put("isShowMatAttr", hasMatAttr);
            //最小起订数量
            jsonObject.put("Mininum", matCodeEntity.getMininum());
 
            //商品属性
            List<Map> matAttrGroupJsonArray = new ArrayList<>();
            if (hasMatAttr) {
                List<MatAttrGroupEntity> matAttrGroupList = matAttrIfc.getMatAttrGroupByMatCode(matCode);
                for (int j = 0; matAttrGroupList != null && j < matAttrGroupList.size(); j++) {
                    MatAttrGroupEntity matAttrGroupEntity = matAttrGroupList.get(j);
                    Map matAttrGroupJsonObject = new HashMap();
                    matAttrGroupJsonObject.put("AttrGroupName", matAttrGroupEntity.getAttrGroupName());
 
                    List<Map> matAttrJsonArray = new ArrayList<>();
                    List<MatAttrEntity> matAttrList = matAttrIfc.getMatAttr(matCode, matAttrGroupEntity.getAttrGroupId());
                    for (int i = 0; matAttrList != null && i < matAttrList.size(); i++) {
                        MatAttrEntity matAttr = matAttrList.get(i);
                        Map matAttrJsonObject = new HashMap();
                        matAttrJsonObject.put("AttrName", matAttr == null ? "" : matAttr.getAttrName());
                        matAttrJsonObject.put("Text", matAttr == null ? "" : matAttr.getText());
 
                        matAttrJsonArray.add(matAttrJsonObject);
                    }
                    matAttrGroupJsonObject.put("Attrs", matAttrJsonArray);
                    matAttrGroupJsonArray.add(matAttrGroupJsonObject);
                }
 
            }
            jsonObject.put("matattr", matAttrGroupJsonArray);
            // 相关商品资料集合 调用也可实现,只是要多发一次请求:
            // http://mp.onbus.cn/shopping/getMatCodeList.do?matcode=xxx&fromdata=3
            // 获取相关商品资料集合
            List<MatCodeEntity> matRelList = matCodeIfc.getMatCodesByRelMat(matCode, shopCcCodeEntity.getShopCcCode(), cltCode,openId,0);
            List<Map> relMatJsonArray = new ArrayList<>();
            for (int i = 0; matRelList != null && i < matRelList.size(); i++) {
                MatCodeEntity relMatCodeEntity = matRelList.get(i);
                Map subJsonObject = new HashMap();
                String relMatCodeUrl = "";
                if (relMatCodeEntity.getExternalURL() != null && !"".equals(relMatCodeEntity.getExternalURL())) {
                    relMatCodeUrl = relMatCodeEntity.getExternalURL();
                } else {
                    relMatCodeUrl = hostUrl
                            + SettingKey.getMatCodeUrl("", relMatCodeEntity.getMatCode(), isMoblieBrowser)
                            + (wxQueryString == null || "".equals(wxQueryString) ? "" : "&" + wxQueryString);
                }
                subJsonObject.put("url", relMatCodeUrl);
                subJsonObject.put("PhotoPath",
                        SettingKey.getUrl(imageHostUrl, relMatCodeEntity.getPhotoPathUrl(), dataSourceEntity.getDbId() + "", null)
                        //    + (wxQueryString == null || "".equals(wxQueryString) ? "" : "?" + wxQueryString)
                );
 
                subJsonObject.put("MatCode", relMatCodeEntity.getMatCode());
                subJsonObject.put("isShowMatCode", settingEntity.isShowMatCode());
                subJsonObject.put("isShowMatName", settingEntity.isShowMatName());
                subJsonObject.put("isShowSpecial", settingEntity.isShowSpecial());
                subJsonObject.put("isShowPrice", settingEntity.isShowPrice());
                subJsonObject.put("isShowPoints", settingEntity.isShowPoints());
                subJsonObject.put("isShowBrand", settingEntity.isShowBrand());
                subJsonObject.put("StockDisplay", settingEntity.getStockDisplay());
 
                if (settingEntity.isShowMatName()) {
                    subJsonObject.put("MatName", relMatCodeEntity.getMatName());
                }
                if (settingEntity.isShowDescription()) {
                    subJsonObject.put("Description", HtmlUtil.getShortDescription(
                            settingEntity.getProductDescriptionLength(), relMatCodeEntity.getDescription()));
                }
                if (settingEntity.isShowRatingOnHomePage()) {
                    subJsonObject.put("RatingAvg", matCodeEntity.getRatingAvg() + "");
                }
                if (settingEntity.isShowPrice()) {
 
                    MatPriceEntity matPriceEntity = matPriceIfc.getMatPrice(relMatCodeEntity.getMatCode(), cltCode, null);
                    Double price = matPriceEntity.getPrice();
                    subJsonObject.put("Price", price); // 实际价格,此价格可能低于“标价”
                    subJsonObject.put("SalesPrice", relMatCodeEntity.getSalesPrice()); // 标价
                    subJsonObject.put("purchasePrice", relMatCodeEntity.getPurchasePrice()); // 采购单价
 
                    CurrencyEntity currencyEntity = new CurrencyEntity(request);
                    subJsonObject.put("Currency", currencyEntity == null ? "" : currencyEntity.getCurrency());
                    subJsonObject.put("CurrencySign", currencyEntity == null ? "" : currencyEntity.getCurrencySign());
                }
                relMatJsonArray.add(subJsonObject);
            }
            jsonObject.put("relmatcode", relMatJsonArray);
 
            //取 维护抢购订金分组 明细
            if (depositDocCode != null && !"".equals(depositDocCode) && depositRowId != null && !"".equals(depositRowId)) {
                PrepaidDepositDetailEntity prepaidDepositDetailEntity = prepaidDepositIfc.getPrepaidDepositDetail(depositDocCode, depositRowId, cltCode);
                jsonObject.put("DepositAmount", prepaidDepositDetailEntity != null ? prepaidDepositDetailEntity.getDepositAmount() : 0);
                jsonObject.put("ItemMemo", prepaidDepositDetailEntity != null ? prepaidDepositDetailEntity.getItemMemo() : "");
                jsonObject.put("DepositDescription",
                        imgData.getImageUrl(prepaidDepositDetailEntity != null ? prepaidDepositDetailEntity.getDepositDescription() : "", settingEntity.getImageProductWidth(),
                                settingEntity.getImageProductHeight(), settingEntity.isShowProductOrgImage(),
                                settingEntity.isFromCached(), request)
                );
                jsonObject.put("isPaidDeposit", prepaidDepositDetailEntity != null && prepaidDepositDetailEntity.isPaidDeposit());   //抢购订金分组 里的  rowid ,功能号 710170
            }
/*
            //未使用的优惠卷
            List<CouponEntity> couponList = couponIfc.getCouponList(cltCode, openId, matCode, false, wx, shopCcCodeEntity.getShopCcCode());
            JsonArray couponListJsonArray = new JsonArray();
            for (int i = 0; couponList != null && i < couponList.size(); i++) {
                CouponEntity couponEntity = couponList.get(i);
                JsonObject couponEntityJsonObject = new JsonObject();
                couponEntityJsonObject.addProperty("CouponName", couponEntity.getCouponName());  //使用范围
                couponEntityJsonObject.addProperty("CouponDocCode", couponEntity.getCouponDocCode());  //优惠券单号
                couponEntityJsonObject.addProperty("CouponCode", couponEntity.getCouponCode());   //优惠券代码
                couponEntityJsonObject.addProperty("Type", couponEntity.getType());   //优惠劵类型: 1 折扣(%) , 2 固定金额
                couponEntityJsonObject.addProperty("Discount", couponEntity.getDiscount());   //优惠折扣(%)
                couponEntityJsonObject.addProperty("SufficeAmount", couponEntity.getSufficeAmount());   //满多少金额可用
                couponEntityJsonObject.addProperty("Total", couponEntity.getTotal());   //优惠金额
                //couponStatus :  //0 正常:可以抢 ;  1 已经抢完 ;  2 未开抢 ; 3 已经抢过了,不能重复抢 ; 4 已经提醒(微信模板消息提醒)
                couponEntityJsonObject.addProperty("Status", couponEntity.getCouponStatus());
                couponEntityJsonObject.addProperty("UsesTotal", couponEntity.getUsesTotal());   //本优惠卷总张数
                couponEntityJsonObject.addProperty("UsedTimes", couponEntity.getUsedTimes());   //本优惠卷已抢的数量
 
                couponEntityJsonObject.addProperty("BalanceSecond", couponEntity.getBalanceSecond());   //抢券开始时间余下的秒数,负数表示倒计时早已结束
                couponEntityJsonObject.addProperty("DateStart", couponEntity.getDateStart() == null ? "" : sdf2.format(couponEntity.getDateStart()));  //抢券开始时间
                couponEntityJsonObject.addProperty("DateEnd", couponEntity.getDateEnd() == null ? "" : sdf2.format(couponEntity.getDateEnd()));  //抢券结束时间
 
                couponEntityJsonObject.addProperty("EffectiveDateStart", couponEntity.getEffectiveDateStart() == null ? "" : sdf.format(couponEntity.getEffectiveDateStart()));  //有效使用开始期
                couponEntityJsonObject.addProperty("EffectiveDateEnd", couponEntity.getEffectiveDateEnd() == null ? "" : sdf.format(couponEntity.getEffectiveDateEnd()));  //有效使用结束期
                couponEntityJsonObject.addProperty("Photo", imgData.getImageUrl(couponEntity.getPhoto(), 120, 120, settingEntity.isShowPopupOrgImage(), settingEntity.isFromCached(), request));
                couponEntityJsonObject.addProperty("BannerImage", imgData.getImageUrl(couponEntity.getBannerImage(), settingEntity.getImageBannerWidth(), settingEntity.getImageBannerHeight(), settingEntity.isShowBannerOrgImage(), settingEntity.isFromCached(), request));
 
                //已抢%
                int progressRate = (couponEntity.getUsesTotal() == 0 ? 0 : couponEntity.getUsedTimes() * 100 / couponEntity.getUsesTotal());
                couponEntityJsonObject.addProperty("ProgressRate", progressRate);   //已抢进度%
                couponListJsonArray.add(couponEntityJsonObject);
            }
            json.add("CouponList", couponListJsonArray);
 
*/
 
            //----------获取 sku 参数,用于“加入购物车” 或“立即购买” 时弹出选择,Added by Johns Wang,2021-01-30
            List<Map> skuMatCodeJsonArray = new ArrayList<>();
            SkuMatCodeEntity skuMatCodeEntity=null;
            List<Map> skuParameterJsonArray = new ArrayList<>();
            if(matCodeEntity.isStartupSkuParameters()) {
                List<SkuParameterEntity> skuParameterList = matCodeIfc.getSkuParameter(matCodeEntity.getMatCode(), shopCcCodeEntity.getShopCcCode(),
                        null, null, null, null, null, null, null, null, null, null);
                skuMatCodeEntity = matCodeIfc.getSkuMatCodeByMatCode(matCodeEntity.getMatCode(), openId);
 
 
                // 根据skuSetId去重,并按 SkuSetSort 排序输出
                List<SkuParameterEntity> skuSetList = skuParameterList.stream().collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SkuParameterEntity::getSkuSetId))), ArrayList::new)
                );
                for (int i = 0; skuSetList != null && i < skuSetList.size(); i++) {
                    Map skuSetEntityJsonObject = new HashMap();
                    Integer skuSetId = skuSetList.get(i).getSkuSetId();
                    skuSetEntityJsonObject.put("skuSetSort", skuSetList.get(i).getSkuSetSort());
                    skuSetEntityJsonObject.put("skuSetId", skuSetId);
                    skuSetEntityJsonObject.put("skuSetName", skuSetList.get(i).getSkuSetName());
                    List<SkuParameterEntity> skuList = skuParameterList.stream().filter(s -> s.getSkuSetId().intValue() == skuSetId.intValue()).collect(Collectors.toList());
                    List<Map> skuListJsonArray = new ArrayList<>();
                    for (int j = 0; skuList != null && j < skuList.size(); j++) {
                        Map skuEntityJsonObject = new HashMap();
                        //skuEntityJsonObject.addProperty("skuSetId", skuList.get(j).getSkuSetId());
                        skuEntityJsonObject.put("skuSort", skuList.get(j).getSkuSort());
                        skuEntityJsonObject.put("skuId", skuList.get(j).getSkuId());
                        skuEntityJsonObject.put("skuName", skuList.get(j).getSkuName());
                        skuEntityJsonObject.put("isEnableSelection", skuList.get(j).isEnableSelection());
                        skuListJsonArray.add(skuEntityJsonObject);
                    }
                    skuSetEntityJsonObject.put("skuList", skuListJsonArray);
                    skuParameterJsonArray.add(skuSetEntityJsonObject);
                }
            }
                jsonObject.put("SkuParameterList", skuParameterJsonArray);
 
                if (skuMatCodeEntity != null) {
                    Map skuEntityJsonObject = new HashMap();
                    skuEntityJsonObject.put("skuId1", skuMatCodeEntity.getSkuId1());
                    skuEntityJsonObject.put("skuName1", skuMatCodeEntity.getSkuName1());
                    skuEntityJsonObject.put("skuId2", skuMatCodeEntity.getSkuId2());
                    skuEntityJsonObject.put("skuName2", skuMatCodeEntity.getSkuName2());
                    skuEntityJsonObject.put("skuId3", skuMatCodeEntity.getSkuId3());
                    skuEntityJsonObject.put("skuName3", skuMatCodeEntity.getSkuName3());
                    skuEntityJsonObject.put("skuId4", skuMatCodeEntity.getSkuId4());
                    skuEntityJsonObject.put("skuName4", skuMatCodeEntity.getSkuName4());
                    skuEntityJsonObject.put("skuId5", skuMatCodeEntity.getSkuId5());
                    skuEntityJsonObject.put("skuName5", skuMatCodeEntity.getSkuName5());
                    skuEntityJsonObject.put("skuId6", skuMatCodeEntity.getSkuId6());
                    skuEntityJsonObject.put("skuName6", skuMatCodeEntity.getSkuName6());
                    skuEntityJsonObject.put("skuId7", skuMatCodeEntity.getSkuId7());
                    skuEntityJsonObject.put("skuName7", skuMatCodeEntity.getSkuName7());
                    skuEntityJsonObject.put("skuId8", skuMatCodeEntity.getSkuId8());
                    skuEntityJsonObject.put("skuName8", skuMatCodeEntity.getSkuName8());
                    skuEntityJsonObject.put("skuId9", skuMatCodeEntity.getSkuId9());
                    skuEntityJsonObject.put("skuName9", skuMatCodeEntity.getSkuName9());
                    skuEntityJsonObject.put("skuId10", skuMatCodeEntity.getSkuId10());
                    skuEntityJsonObject.put("skuName10", skuMatCodeEntity.getSkuName10());
                    skuEntityJsonObject.put("MatCode", skuMatCodeEntity.getMatCode());
                    skuEntityJsonObject.put("MatName", skuMatCodeEntity.getMatName());
                    skuEntityJsonObject.put("Special", skuMatCodeEntity.getSpecial());
                    skuEntityJsonObject.put("PhotoPath", skuMatCodeEntity.getPhotoPath());
                    skuMatCodeJsonArray.add(skuEntityJsonObject);
                }
                jsonObject.put("SkuMatCodeList", skuMatCodeJsonArray);
 
 
            return jsonObject;
 
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApplicationException(this.getErrorMsg(e));
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
}