fs-danaus
2023-02-01 b1f69bc0eb0561f307220da3176807ae591c3586
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
package com.yc.api.controller;
 
import com.abc.pay.client.Base64;
import com.abc.pay.client.Constants;
import com.abc.pay.client.JSON;
import com.abc.pay.client.ebus.PaymentRequest;
import com.abc.pay.client.ebus.PaymentResult;
import com.abc.pay.client.ebus.QueryOrderRequest;
import com.yc.abc.utils.AbcMerchantConfig;
import com.yc.action.BaseAction;
import com.yc.action.grid.GTGrid;
import com.yc.action.panval.PanelCommitAction;
import com.yc.api.bean.MatGroupEntity;
import com.yc.api.bean.ProducParmBean;
import com.yc.api.bean.T120330;
import com.yc.api.service.LuJiangNanServiceIfc;
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.sdk.shopping.entity.MatCodeEntity;
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.share.ShareIfc;
import com.yc.sdk.shopping.util.SettingKey;
import com.yc.service.build.type.T_22_Ifc;
import com.yc.utils.SessionKey;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
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.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
 
/**
 * 卤江南
 */
@RestController
public class LuJiangNanController extends BaseAction {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
 
    @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
    T_22_Ifc t22ifc;
    @Autowired
    LuJiangNanServiceIfc luJiangNanServiceIfc;
    @Autowired
    QrServiceIfc qrServiceIfc;
    @Autowired
    ThreadPoolTaskExecutor threadPoolExecutor;
//---------------下单模块-------------------------------
private class ProductCallable implements Callable<Object> {
    ProducParmBean producParmBean;
    HttpServletRequest request;
    String dbid;
    LuJiangNanServiceIfc luJiangNanServiceIfc;
    ShoppingImageDataIfc imgData;
    int actionType=0;//1,取分类 2,取列表
 
 
    public ProductCallable(HttpServletRequest request,ProducParmBean producParmBean,String dbid, LuJiangNanServiceIfc luJiangNanServiceIfc,ShoppingImageDataIfc imgData,int actionType) {
        this.producParmBean = producParmBean;
        this.dbid = dbid;
        this.luJiangNanServiceIfc = luJiangNanServiceIfc;
        this.actionType=actionType;
        this.request=request;
        this.imgData=imgData;
    }
 
    @Override
    public Object call() throws Exception {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            SpObserver.setDBtoInstance("_" + dbid);
 
            Map nodes = new HashMap();
            List<MatCodeEntity> matCodeEntityList=new ArrayList<>();
            GTGrid gtGrid =(GTGrid)FactoryBean.getBean("GTGrid");
            final HttpSession session = request.getSession();
            String hostUrl = SettingKey.getHostUrlForImage(request);
 
            //数据组权限
            switch (actionType) {
                case 1:
                    final String dataGroupInfo = gtGrid.getDataGroupInfo(110501, session.getAttribute(SessionKey.USERCODE) + "", 0, session);
                    final List<MatGroupEntity> groups = luJiangNanServiceIfc.getMatGroups(dataGroupInfo);
                    List<Map> groupList = new ArrayList();
                    String matgourpId = null;
                    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 -> (
                                    matGroupEntity.getRowid().equals(x.getParentRowid())
                            )).collect(Collectors.toList());
                            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);
                        }
                        ProducParmBean parmBean = new ProducParmBean();
                        parmBean.setMatGroup(matgourpId);
//                    final String dataGroupInfoByMatGroup = gtGrid.getDataGroupInfo(110503, session.getAttribute(SessionKey.USERCODE) + "", 0, session);
                        parmBean.setAppSalesOrderMatCodeList(Integer.parseInt(String.valueOf(request.getSession().getAttribute(SessionKey.APP_SALESORDER_MATCODE_LIST))));
                        matCodeEntityList = luJiangNanServiceIfc.getMatCodesByMatGroup(parmBean, request.getSession().getAttribute(SessionKey.USERCODE) + "", dataGroupInfo);
                        //用PhotoPathUrl代替PhotoPath输出图片Url
//                    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));
                        });
                        nodes.put("nodes", groupList);
                        nodes.put("data", matCodeEntityList);
                        //控制 下单列表 的“样式”  , AppSalesOrderStyle  :  0.商城图文式,  1.表格式(卤江南样式)
                        nodes.put("appSalesOrderStyle", request.getSession().getAttribute(SessionKey.APP_SALESORDER_STYLE));
                        callBackMessage.setInfo(nodes);
                    }
                        break;
                        case 2:
                            final String dataGroupInfoByMatGroup2 = gtGrid.getDataGroupInfo(110503, session.getAttribute(SessionKey.USERCODE) + "", 0, session);
                            final Object appSalesorderMatcodeList = session.getAttribute(SessionKey.APP_SALESORDER_MATCODE_LIST);
                            int appSalesorderMatcodeInt = 0;
                            if (appSalesorderMatcodeList != null) {
                                appSalesorderMatcodeInt = Integer.parseInt(String.valueOf(appSalesorderMatcodeList));
                            }
                            producParmBean.setAppSalesOrderMatCodeList(appSalesorderMatcodeInt);
                            matCodeEntityList = luJiangNanServiceIfc.getMatCodesByMatGroup(this.producParmBean, session.getAttribute(SessionKey.USERCODE) + "", dataGroupInfoByMatGroup2);
                            //用PhotoPathUrl代替PhotoPath输出图片Url
                    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);
                            break;
                    }
 
            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 = "/lujn/matGroups.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask matGroups(HttpServletRequest request, HttpServletResponse response) {
        Callable<Object> callable = new ProductCallable(request, null, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "",luJiangNanServiceIfc,imgData,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 = "/lujn/productList.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask productList(@RequestBody ProducParmBean producParmBean, HttpServletRequest request, HttpServletResponse response) {
        Callable<Object> callable = new ProductCallable(request, producParmBean, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "",luJiangNanServiceIfc,imgData,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;
    }
 
    private class T120201Callable implements Callable<Object> {
        List<MatCodeEntity> matCodeEntities;
        String cltCode;
        String dbid;
        LuJiangNanServiceIfc luJiangNanServiceIfc;
 
        public T120201Callable(List<MatCodeEntity> matCodeEntities, String cltCode, String dbid, LuJiangNanServiceIfc luJiangNanServiceIfc) {
            this.matCodeEntities = matCodeEntities;
            this.cltCode = cltCode;
            this.dbid = dbid;
            this.luJiangNanServiceIfc = luJiangNanServiceIfc;
        }
 
        @Override
        public Object call() throws Exception {
            CallBackMessage callBackMessage = new CallBackMessage();
            long startTime = System.currentTimeMillis();
            try {
                SpObserver.setDBtoInstance("_" + dbid);
                if (matCodeEntities == null || matCodeEntities.size() == 0) {
                    throw new ApplicationException("没有商品,不能下单");
                }
                Map map = luJiangNanServiceIfc.save120201(matCodeEntities, cltCode);
                log.info("cltCode:" + cltCode + "-客户:" + cltCode + "下单花费:" + (System.currentTimeMillis() - startTime));
                callBackMessage.setInfo(map);
                callBackMessage.sendSuccessMessageByDefault();
                return callBackMessage.toJSONObject();
            } catch (Exception ex) {
                log.info("cltCode:" + cltCode + "-客户下单出错:" + cltCode + "花费:" + (System.currentTimeMillis() - startTime));
                callBackMessage.sendErrorMessage(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                return callBackMessage.toJSONObject();
            } finally {
                SpObserver.setDBtoInstance();
                log.info("---------------------end:" + cltCode + "-----------------");
            }
        }
    }
 
    /**
     * 异步模式,保存订单
     *
     * @param request
     */
    @RequestMapping(value = "/lujn/save120201.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask save120201(@RequestBody List<MatCodeEntity> matCodeEntities, HttpServletRequest request) {
        String cltCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        log.info("---------------------start:" + cltCode + "-----------------");
        Callable<Object> callable = new T120201Callable(matCodeEntities, cltCode, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", luJiangNanServiceIfc);
        //定义超时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;
    }
 
 
    //-----------------支付模块------------------
 
    /**
     * 单笔支付查询
     * 查询120330
     *
     * @param request
     */
    @RequestMapping(value = "/lujn/queryOrder.do")
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask queryOrder(String docCode, HttpServletRequest request,HttpServletResponse response) {
        boolean isAppPost=request.getHeader("x-app-type")==null?false:true;
        //---web端调用
        if (!isAppPost) {
            CallBackMessage callBackMessage = new CallBackMessage();
            try {
                DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(request);
                SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());//切换数据源
                //获取 参数集 map
                Map<String, String>  map = t22ifc.getParamMap(request);
                docCode=map.get("docCode");
            } catch (Exception e) {
                e.printStackTrace();
                this.print(response, callBackMessage.sendErrorMessage(e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
                return null;
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
        Callable<Object> callable = new QueryOrderCallable(docCode, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", luJiangNanServiceIfc,isAppPost);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
 
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage("执行出错,请重新提交");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage("服务器繁忙,请稍候查询", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    private class QueryOrderCallable implements Callable<Object> {
 
        String orderNo;
        String dbid;
        LuJiangNanServiceIfc luJiangNanServiceIfc;
boolean isAppCall;
        public QueryOrderCallable(String orderNo, String dbid, LuJiangNanServiceIfc luJiangNanServiceIfc,boolean isAppCall) {
            this.orderNo = orderNo;
            this.dbid = dbid;
            this.luJiangNanServiceIfc = luJiangNanServiceIfc;
            this.isAppCall=isAppCall;
        }
 
        @Override
        public Object call() throws Exception {
            CallBackMessage callBackMessage = new CallBackMessage();
            try {
                SpObserver.setDBtoInstance("_" + dbid);
                QueryOrderRequest tQueryRequest = new QueryOrderRequest();
                tQueryRequest.queryRequest.put("PayTypeID", Constants.PAY_TYPE_DIRECTPAY);    //设定交易类型
                tQueryRequest.queryRequest.put("OrderNo", orderNo);    //设定订单编号 (必要信息)
                tQueryRequest.queryRequest.put("QueryDetail", "1");//设定查询方式
                JSON json = tQueryRequest.postRequest();
                String ReturnCode = json.GetKeyValue("ReturnCode");
                String ErrorMessage = json.GetKeyValue("ErrorMessage");
                //成功
                if (ReturnCode.equals("0000")) {
                    String orderInfo = json.GetKeyValue("Order");
                    Base64 tBase64 = new Base64();
                    String orderDetail = new String(tBase64.decode(orderInfo));
                    json.setJsonString(orderDetail);
                    //支付成功才写执行
                    if ("04".equalsIgnoreCase(json.GetKeyValue("Status"))) {
                        //--插入日志表
                        luJiangNanServiceIfc.save150172LogByQuery(json);
                        luJiangNanServiceIfc.save150171ByQueryOrder(json);
                    }
                    Map info = new HashMap();
                    info.put("code", json.GetKeyValue("Status"));
                    info.put("status", getOrderStatus(json.GetKeyValue("Status")));
                    callBackMessage.setInfo(info);
                    callBackMessage.sendSuccessMessageByDefault();
                    if(isAppCall) {
                        return callBackMessage.toJSONObject();
                    }else {
                        return callBackMessage.print();
                    }
                } else {
                    throw new ApplicationException(ReturnCode + "-" + ErrorMessage);
                }
            } catch (Exception ex) {
                callBackMessage.sendErrorMessage(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                if(isAppCall) {
                    return callBackMessage.toJSONObject();
                }else {
                    return callBackMessage.print();
                }
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
    }
 
    /**
     * 01:未支付
     * 02:无回应
     * 03:微信和支付宝支付成功
     * 04:选择微信、支付宝支付时,表示农行清算成功;
     * 选择我行支付通道支付时,表示农行支付成功
     * 05:已退款
     * 07:授权确认成功
     * 00:授权已取消
     * 99:失败
     */
    private String getOrderStatus(String status) {
        switch (status) {
            case "01":
                return "未支付";
            case "02":
                return "无回应";
            case "03":
                return "微信和支付宝支付成功";
            case "04":
                return "支付成功";
            case "05":
                return "已退款";
            case "07":
                return "授权确认成功";
            case "00":
                return "授权已取消";
            default:
                return "失败";
        }
 
    }
 
    /**
     * 支付通知结果
     *
     * @param request
     */
    @RequestMapping(value = "/lujn/orderPayCallback.do")
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask orderPayCallback(HttpServletRequest request) {
        Callable<Object> callable = new OrderPayCallable(request.getParameter("MSG"), luJiangNanServiceIfc);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
 
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage("执行出错,请重新提交");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage("服务器繁忙,请不要重复提交,稍候在支付结果中查询结果", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    private class OrderPayCallable implements Callable<Object> {
 
        String msg;
        LuJiangNanServiceIfc luJiangNanServiceIfc;
 
        public OrderPayCallable(String msg, LuJiangNanServiceIfc luJiangNanServiceIfc) {
            this.msg = msg;
            this.luJiangNanServiceIfc = luJiangNanServiceIfc;
        }
 
        @Override
        public Object call() throws Exception {
            CallBackMessage callBackMessage = new CallBackMessage();
            PaymentResult paymentResult = null;
            try {
                log.info("msg:" + msg);
                paymentResult = new PaymentResult(msg);
                log.info("orderNo:" + paymentResult.getValue("OrderNo"));
                log.info("ResponseMessage:" + paymentResult.getResponseMessage());
            } catch (Exception e) {
                e.printStackTrace();
                log.info("PaymentResultErrorMessage:" + e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
                throw new ApplicationException(e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
            }
            try {
                SpObserver.setDBtoInstance("_" + paymentResult.getValue("MerchantRemarks"));
                //--插入日志表
                luJiangNanServiceIfc.save150172Log(paymentResult);
                //保存支付结果日志及执行150171确认过账
                luJiangNanServiceIfc.save150171ByCallBack(paymentResult);
                log.info("执行完成150171过账");
                callBackMessage.sendSuccessMessageByDefault();
                return callBackMessage.toJSONObject();
            } catch (Exception ex) {
                ex.printStackTrace();
                log.info("ErrorMessage:" + ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                throw ex;
                // callBackMessage.sendErrorMessage(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                //return callBackMessage.toJSONObject();
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
    }
 
    /**
     * 未支付提示
     * 查询120330
     *
     * @param request
     */
    @RequestMapping(value = "/lujn/nodify120330.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask nodify120330(HttpServletRequest request) {
        String cltCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        Callable<Object> callable = new Notify120330ListCallable(cltCode, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", luJiangNanServiceIfc);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
 
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage("执行出错,请重新提交");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage("服务器繁忙,请稍候再查询", -1003);
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    private class Notify120330ListCallable implements Callable<Object> {
 
        String cltCode;
        String dbid;
        LuJiangNanServiceIfc luJiangNanServiceIfc;
 
        public Notify120330ListCallable(String cltCode, String dbid, LuJiangNanServiceIfc luJiangNanServiceIfc) {
            this.cltCode = cltCode;
            this.dbid = dbid;
            this.luJiangNanServiceIfc = luJiangNanServiceIfc;
        }
 
        @Override
        public Object call() throws Exception {
            CallBackMessage callBackMessage = new CallBackMessage();
            try {
                SpObserver.setDBtoInstance("_" + dbid);
 
                String msg = luJiangNanServiceIfc.notify120330(cltCode);
                Map info = new HashMap();
                info.put("msg", msg);
                callBackMessage.setInfo(info);
                callBackMessage.sendSuccessMessageByDefault();
                return callBackMessage.toJSONObject();
            } catch (Exception ex) {
                callBackMessage.sendErrorMessage(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                return callBackMessage.toJSONObject();
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
    }
 
    /**
     * 询结单列表
     * 查询120330
     *
     * @param request
     */
    @RequestMapping(value = "/lujn/get120330List.do", method = RequestMethod.GET)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask get120330List(Integer pageIndex, Integer pageSize, Integer isPay, HttpServletRequest request) {
        String cltCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        Callable<Object> callable = new Get120330ListCallable(isPay, pageIndex, pageSize, cltCode, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", luJiangNanServiceIfc);
        //定义超时45秒
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(45), threadPoolExecutor, callable);
 
        asyncTask.onError(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage("执行出错,请重新提交");
                    return callBackMessage.toJSONObject();
                }
        );
        asyncTask.onTimeout(
                (Callable<Object>) () -> {
                    CallBackMessage callBackMessage = new CallBackMessage();
                    callBackMessage.sendErrorMessage("执行超时,请重新提交");
                    return callBackMessage.toJSONObject();
                }
        );
        return asyncTask;
    }
 
    private class Get120330ListCallable implements Callable<Object> {
        Integer pageIndex;
        Integer isPay;
        Integer pageSize;
        String cltCode;
        String dbid;
        LuJiangNanServiceIfc luJiangNanServiceIfc;
 
        public Get120330ListCallable(Integer isPay, Integer pageIndex, Integer pageSize, String cltCode, String dbid, LuJiangNanServiceIfc luJiangNanServiceIfc) {
            this.pageIndex = pageIndex;
            this.isPay = isPay;
            this.pageSize = pageSize;
            this.cltCode = cltCode;
            this.dbid = dbid;
            this.luJiangNanServiceIfc = luJiangNanServiceIfc;
        }
 
        @Override
        public Object call() throws Exception {
            CallBackMessage callBackMessage = new CallBackMessage();
            try {
                SpObserver.setDBtoInstance("_" + dbid);
 
                List<Map<String, Object>> list = null;
                if (isPay != null && isPay == 1) {
                    //已支付
                    list = luJiangNanServiceIfc.get120330ListByPaid(pageIndex, pageSize, cltCode);
                } else {
                    //未支付
                    list = luJiangNanServiceIfc.get120330List(pageIndex, pageSize, cltCode);
                }
                callBackMessage.setInfo(list);
                callBackMessage.sendSuccessMessageByDefault();
                return callBackMessage.toJSONObject();
            } catch (Exception ex) {
                callBackMessage.sendErrorMessage(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                return callBackMessage.toJSONObject();
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
    }
 
    /**
     * app下单
     * 查询120330取得支付金额,发送订单请求到农行支付平台,返回支付信息返回给app,以便app发起支付请求
     *
     * @param request
     */
    @RequestMapping(value = "/lujn/post120330.do", method = RequestMethod.POST)
    @CrossOrigin
    public @ResponseBody
    WebAsyncTask post120330(@RequestBody List<T120330> list, HttpServletRequest request) {
        String cltCode = request.getSession().getAttribute(SessionKey.HRCODE) + "";
        String userName = request.getSession().getAttribute(SessionKey.USER_NAME) + "";
        Map<String, String> env = this.initEnv(request, 150171, null, false);
        Callable<Object> callable = new T150171Callable(list, cltCode, request.getSession().getAttribute(SessionKey.DATA_BASE_ID) + "", luJiangNanServiceIfc, userName, env);
        //定义超时45秒, 改为600秒,Modified by Johns Wang,2021-02-10
        WebAsyncTask asyncTask = new WebAsyncTask(TimeUnit.SECONDS.toMillis(600), 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 T150171Callable implements Callable<Object> {
        List<T120330> list;
        String cltCode;
        String userName;
        String dbid;
        Map<String, String> env;
        LuJiangNanServiceIfc luJiangNanServiceIfc;
 
        public T150171Callable(List<T120330> list, String cltCode, String dbid, LuJiangNanServiceIfc luJiangNanServiceIfc, String userName, Map<String, String> env) {
            this.list = list;
            this.cltCode = cltCode;
            this.dbid = dbid;
            this.userName = userName;
            this.env = env;
            this.luJiangNanServiceIfc = luJiangNanServiceIfc;
        }
 
        @Override
        public Object call() throws Exception {
            CallBackMessage callBackMessage = new CallBackMessage();
            T120330 t120330 = new T120330();
            try {
                SpObserver.setDBtoInstance("_" + dbid);
                if (list == null || list.size() == 0) {
                    throw new ApplicationException("没有需要支付的订单");
                }
                //1-------------------生成门店付款单 150171
                Map map = luJiangNanServiceIfc.save150171(list, cltCode);
                t120330.setDocCode(map.get("docCode") + "");
                if (map.get("amount") == null || "".equals(map.get("amount"))) {
                    throw new ApplicationException(map.get("docCode") + "-订单金额不能为空");
                }
                t120330.setAmount(new BigDecimal(map.get("amount") + ""));
                t120330.setDbid(Integer.parseInt(dbid));
                t120330.setMerchantID(map.get("merchantID") + "");
                //2--------------------生成支付平台需要的请求对象
                //log.info("t120330:"+ com.alibaba.fastjson.JSON.toJSONString(t120330));
                JSON json = postOrder(t120330);
                String ReturnCode = json.GetKeyValue("ReturnCode");
                String ErrorMessage = json.GetKeyValue("ErrorMessage");
                String paymentURL = json.GetKeyValue("PaymentURL");
                log.info("ReturnCode   = [" + ReturnCode + "]");
                log.info("ErrorMessage = [" + ErrorMessage + "]");
                log.info("PaymentURL-->" + json.GetKeyValue("PaymentURL"));
                //成功
                if ("0000".equals(ReturnCode)) {
                    //3---------------------把返回的信息返回给app端,发起支付请求
                    //---解析PaymentURL,获得支付token
                    Map info = new HashMap();
                    info.put("token", paymentURL.split("TOKEN=")[1]);
                    info.put("orderNo", json.GetKeyValue("OrderNo"));
                    info.put("amount", t120330.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
                    callBackMessage.setInfo(info);
                    callBackMessage.sendSuccessMessageByDefault();
                    return callBackMessage.toJSONObject();
                } else {
                    //出错
                    throw new ApplicationException(ReturnCode + "-" + ErrorMessage);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                //删除新建的单
                if (StringUtils.isNotBlank(t120330.getDocCode())) {
                    env.put("@doccode", t120330.getDocCode());
                    PanelCommitAction panelCommitAction = (PanelCommitAction) FactoryBean.getBean("panelCommitAction");
                    panelCommitAction.PostDeleteDocSql("150171", t120330.getDocCode(), "0", dbid, "5", userName, cltCode, null, env);
                }
                callBackMessage.sendErrorMessage(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
                return callBackMessage.toJSONObject();
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
    }
 
    /**
     * 向农行发送订单请求,把订单提交到网上支付平台,成功后导向支付界面,然后发起支付操作
     *
     * @return
     */
    private JSON postOrder(T120330 t120330) {
 
        //订单日期和时间
        LocalDate localDate = LocalDate.now();
        String date = localDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        LocalTime localTime = LocalTime.now();
        String time = localTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        String docCode = t120330.getDocCode();
        //todo 订单金额
        BigDecimal orderAmount = t120330.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
        //1、生成订单对象
        PaymentRequest tPaymentRequest = new PaymentRequest();
 
        tPaymentRequest.dicOrder.put("PayTypeID", Constants.PAY_TYPE_DIRECTPAY);                   //设定交易类型
        tPaymentRequest.dicOrder.put("OrderDate", date);                  //设定订单日期 (必要信息 - YYYY/MM/DD)
        tPaymentRequest.dicOrder.put("OrderTime", time);                   //设定订单时间 (必要信息 - HH:MM:SS)
        tPaymentRequest.dicOrder.put("OrderNo", docCode);                       //设定订单编号 (必要信息)
        tPaymentRequest.dicOrder.put("CurrencyCode", "156");             //设定交易币种
        tPaymentRequest.dicOrder.put("OrderAmount", orderAmount.toString());      //设定交易金额
        tPaymentRequest.dicOrder.put("InstallmentMark", "0");       // 分期标识
        tPaymentRequest.dicOrder.put("CommodityType", "0202");           // 设置商品种类
//2、订单明细
        LinkedHashMap orderitem = new LinkedHashMap();
        orderitem.put("ProductName", docCode);//商品名称
        tPaymentRequest.orderitems.put(1, orderitem);
//3、生成支付请求对象
        tPaymentRequest.dicRequest.put("PaymentType", Constants.PAY_TYPE_ALL);            //设定支付类型
        tPaymentRequest.dicRequest.put("PaymentLinkType", Constants.PAY_LINK_TYPE_MOBILE);    //设定支付接入方式
        tPaymentRequest.dicRequest.put("NotifyType", Constants.NOTIFY_TYPE_SERVER);              //设定通知方式
        tPaymentRequest.dicRequest.put("MerchantRemarks", t120330.getDbid());           // 附言,这里保存数据源id,方便回调支付结果通知时获得对应的数据源id
        //--测试环境
        //tPaymentRequest.dicRequest.put("ResultNotifyURL", "http://ljn.onbus.cn:9010/lujn/orderPayCallback.do");    //设定通知URL地址
        tPaymentRequest.dicRequest.put("ResultNotifyURL", "https://ljn.onbus.cn/lujn/orderPayCallback.do");    //设定通知URL地址
        tPaymentRequest.dicRequest.put("IsBreakAccount", Constants.IsBreakAccount_NO);      //设定交易是否分账、交易是否支持向二级商户入账
        // System.out.println(GridUtils.toJson(tPaymentRequest));
        //---根据MerchantID取得配置文件TrustMerchant.properties中所在的index位置,传给农行执行
        JSON json = tPaymentRequest.extendPostRequest(getMerchantIDIndex(t120330.getDbid(), t120330.getMerchantID()));
        return json;
    }
 
    /**
     * 根据商户号查找在配置文件所有的位置index
     * @param merchantID
     * @return
     */
    private  int getMerchantIDIndex(Integer dbid,String merchantID){
    //商户证书列表
    String merchantStr = AbcMerchantConfig.get("MerchantID");
    if(StringUtils.isBlank(merchantStr)){
        throw new ApplicationException("TrustMerchant.properties中商户号MerchantID配置项不能为空");
    }
    final String[] merchantList = merchantStr.split(",");
    int index=0;//商户号的位置
        if(merchantList!=null&&merchantList.length>0) {
            for (int i = 0; i < merchantList.length; i++) {
                //根据商户id定位对应的位置
                if (merchantList[i].trim().equalsIgnoreCase(merchantID)) {
                    index = i + 1;
                    break;
                }
            }
        }
    if(index==0){
        final DataSourceEntity dataSourceMap = MultiDataSource.getDataSourceMap(dbid + "");
        throw new ApplicationException(dataSourceMap.getSystemID()+"-商户证书找不到,请检查配置文件");
    }
    return index;
}
 
}