sunshine
2024-11-05 0d71954001d47e92683a508f43ea31c3bf822ffb
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
package com.nova.sankuai.service.impl;
 
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nova.sankuai.domain.api.baofu.BaofuRecordPayInfo;
import com.nova.sankuai.domain.api.baofu.RecordDto;
import com.nova.sankuai.domain.api.liexiong.*;
import com.nova.sankuai.domain.api.shantai.GetOrderStatusVo;
import com.nova.sankuai.domain.api.shantai.ShanTaiPayDto;
import com.nova.sankuai.domain.api.shantai.ShanTaiPayInfo;
import com.nova.sankuai.domain.api.shantai.ShanTaiSureTypeEnum;
import com.nova.sankuai.domain.api.weiyaquanyi.*;
import com.nova.sankuai.domain.api.yinsheng.SerialGenerator;
import com.nova.sankuai.domain.api.yinsheng.YinShengOrderEnum;
import com.nova.sankuai.domain.api.yinsheng.YinShengUtil;
import com.nova.sankuai.domain.dto.PaymentCheckDto;
import com.nova.sankuai.domain.entity.*;
import com.nova.sankuai.domain.enums.CustomerInfoStatusEnum;
import com.nova.sankuai.domain.enums.vipservice.PayTypeEnum;
import com.nova.sankuai.domain.enums.vipservice.QueueVipTypeEnum;
import com.nova.sankuai.domain.enums.vipservice.VipCardOrderEnum;
import com.nova.sankuai.domain.enums.vipservice.VipCardTypeEnum;
import com.nova.sankuai.domain.vo.*;
import com.nova.sankuai.domain.vo.huifubao.HuiFuBaoPayInfo;
import com.nova.sankuai.domain.vo.huifubao.HuiFuBaoPayVo;
import com.nova.sankuai.domain.vo.huifubao.HuiFuBaoSendPayInfo;
import com.nova.sankuai.domain.vo.vipcard.VipCardVo;
import com.nova.sankuai.domain.vo.vipcard.VipUserStatusVo;
import com.nova.sankuai.infra.config.AlipayConfigProperties;
import com.nova.sankuai.infra.config.CommonException;
import com.nova.sankuai.infra.mapper.*;
import com.nova.sankuai.infra.utils.ConstantsUtil;
import com.nova.sankuai.infra.utils.UserUtil;
import com.nova.sankuai.security.UserDetail;
import com.nova.sankuai.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
 
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * @author weikangdi 2021/12/23
 */
@Service
@AllArgsConstructor
@Slf4j
public class VipCardOrderServiceImpl extends ServiceImpl<VipCardOrderMapper, VipCardOrder> implements IVipCardOrderService {
 
    private final LieXiongUtil lieXiongUtil;
 
    private final IChannelInfoService channelInfoService;
 
    private final CustomerUserMapper customerUserMapper;
 
    private final ICustomerUserService customerUserService;
 
    private final VipCardOrderMapper vipCardOrderMapper;
 
    private final CustomerMapper customerMapper;
 
    private final SystemParamMapper systemParamMapper;
 
    private final YinShengUtil yinShengUtil;
 
    private final WeiYaUtil weiYaUtil;
 
    private final IVipCardService vipCardService;
 
    private final AlipayConfigProperties alipayConf;
 
    private final SysAlipayAccountMapper alipayAccountMapper;
 
    private final SysAlipayAccountUsageMapper alipayAccountUsageMapper;
 
    private static final Logger logger = LoggerFactory.getLogger("payLogger");
 
    private final WeiYaConfigProperties weiyaConf;
 
    private final IAlipayPlatformService alipayPlatformService;
 
    private final VipCardMapper vipCardMapper;
 
    private final IYinShengService yinShengService;
 
    private final IShanTaiService shanTaiService;
 
    private final ShanTaiSignRecordMapper shanTaiSignRecordMapper;
 
    private final HuifubaoSignRecordMapper huifubaoSignRecordMapper;
 
    // 于2022-12-05
    private final IBaofuService baofuService;
    private final BaofuSignRecordMapper baofuSignRecordMapper;
    private final SerialGenerator serialGenerator;
    private final IRosterService rosterService;
    private final IHuiFuBaoSignService huiFuBaoSignService;
    private final IHuiFuBaoPayService huiFuBaoPayService;
 
 
    @Override
    public List<VipCardVo> getVipCardList(String appId, String phone) {
        List<VipCardVo> result = new ArrayList<>();
        SystemParam systemParam = systemParamMapper.getDefaultParam();
        ChannelVipConfigVo channelVipConfig = channelInfoService.getChannelVipConfig(appId, phone);
        if (PayTypeEnum.LIE_XIONG.getCode().equals(systemParam.getPaymentMethod())) {
            String accessToken = lieXiongUtil.getAccessToken();
            List<LieXiongCard> cardList = lieXiongUtil.getCardList(accessToken);
            for (LieXiongCard lieXiongCard : cardList) {
                VipCardVo vipCardVo = new VipCardVo();
                vipCardVo.setCardId(lieXiongCard.getId());
                vipCardVo.setName(lieXiongCard.getName());
                vipCardVo.setSellingPrice(lieXiongCard.getSellingPrice());
                vipCardVo.setMemberDiscount(channelVipConfig.getMemberDiscount());
                vipCardVo.setMarkedPrice(channelVipConfig.getMemberDiscount() + lieXiongCard.getSellingPrice());
                result.add(vipCardVo);
            }
        } else if (PayTypeEnum.WEI_YA.getCode().equals(systemParam.getPaymentMethod())) {
            return getVipCardListFromWeiYa();
        } else {
            //获取系统自定义会员卡列表
            result = vipCardService.getVipCardList(channelVipConfig.getMemberDiscount(), VipCardTypeEnum.MEMBER_SERVICE.getCode());
        }
        return result;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BuyCardParamVo buyCard(VipCardVo cardVo, String phone) {
        String accessToken = lieXiongUtil.getAccessToken();
        CustomerUser customerUser = getUser(phone);
        String userToken = lieXiongUtil.getUserToken(phone, customerUser.getId().toString(), accessToken);
        LieXiongParam lieXiongParam = lieXiongUtil.buyCard(cardVo, accessToken, userToken);
        VipCardOrder cardOrder = lambdaQuery().eq(VipCardOrder::getOrderId, lieXiongParam.getOrderId()).one();
        if (cardOrder == null) {
            VipCardOrder vipCardOrder = initVipCardOrder(lieXiongParam.getOrderId(), lieXiongParam.getPartnerThirdOrderId(),
                    PayTypeEnum.LIE_XIONG.getCode(), customerUser.getId(), cardVo);
            save(vipCardOrder);
            lieXiongParam.setStatus(VipCardOrderEnum.STATUS_INIT.getCode());
        } else {
            lieXiongParam.setStatus(cardOrder.getStatus());
            if (!VipCardOrderEnum.STATUS_INIT.getCode().equals(cardOrder.getStatus())) {
                logger.error("订单重复提交,且状态不是初始化" + cardOrder);
            }
        }
        BuyCardParamVo paramVo = new BuyCardParamVo();
        paramVo.setPayType(PayTypeEnum.LIE_XIONG.getCode());
        paramVo.setLieXiongParam(lieXiongParam);
        paramVo.setPartnerThirdOrderId(lieXiongParam.getPartnerThirdOrderId());
 
        return paramVo;
    }
 
    /**
     * 初始化会员订单信息
     */
    private VipCardOrder initVipCardOrder(String orderId, String partnerThirdOrderId, Integer payType, Long userId, VipCardVo cardVo) {
        VipCardOrder vipCardOrder = new VipCardOrder();
        vipCardOrder.setOrderId(orderId);
        vipCardOrder.setPartnerThirdOrderId(partnerThirdOrderId);
        vipCardOrder.setUserId(userId);
        vipCardOrder.setStatus(VipCardOrderEnum.STATUS_INIT.getCode());
        vipCardOrder.setCreationDate(new Date());
        vipCardOrder.setPayType(payType);
        vipCardOrder.setPrice(cardVo.getSellingPrice());
        vipCardOrder.setCardId(cardVo.getCardId());
        vipCardOrder.setVipType(cardVo.getVipType());
        return vipCardOrder;
    }
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notifyOrder(Map<String, String[]> parameterMap) {
        logger.info("烈熊支付回调开始,打印支付参数");
        MultiValueMap<String, String> stringMultiValueMap = new LinkedMultiValueMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            if (entry.getValue() != null) {
                List<String> value = Arrays.asList(entry.getValue());
                logger.info("烈熊支付回调参数名:" + entry.getKey() + "  值:" + value);
                stringMultiValueMap.put(entry.getKey(), new ArrayList<>(value));
            } else {
                logger.info("烈熊支付回调参数名:" + entry.getKey() + "  值:" + null);
                stringMultiValueMap.put(entry.getKey(), null);
            }
        }
        logger.info("打印支付参数结束");
        boolean result = lieXiongUtil.checkNotifySign(stringMultiValueMap);
        if (result) {
            String orderId = Objects.requireNonNull(stringMultiValueMap.get("orderId")).get(0);
            String type = Objects.requireNonNull(stringMultiValueMap.get("type")).get(0);
            String startDate = Objects.requireNonNull(stringMultiValueMap.get("startDate")).get(0);
            String endDate = Objects.requireNonNull(stringMultiValueMap.get("endDate")).get(0);
            VipCardOrder vipCardOrder = lambdaQuery().eq(VipCardOrder::getOrderId, orderId).one();
            String systemStatus = LieXiongOrderEnum.parseSystemStatus(type);
            if (VipCardOrderEnum.STATUS_INVALID.getCode().equals(systemStatus)) {
                logger.error("烈熊订单回调类型非法,回调类型" + type);
            }
            if (vipCardOrder != null) {
                if (!systemStatus.equals(vipCardOrder.getStatus())) {
                    update(Wrappers.<VipCardOrder>lambdaUpdate()
                            .set(VipCardOrder::getStatus, systemStatus)
                            .eq(VipCardOrder::getOrderId, orderId));
                    if (VipCardOrderEnum.STATUS_END.getCode().equals(systemStatus)) {
                        //更新会员有效期
                        DateTime start = DateUtil.parse(startDate);
                        DateTime end = DateUtil.parse(endDate);
                        VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(vipCardOrder.getUserId(), null, start, end);
                        customerUserService.updateVipEffectiveTime(vipCardOrder, vipEffectiveTimeVo);
                    }
                }
            } else {
                logger.error("订单不存在");
            }
        } else {
            logger.error("支付回调参数错误,校验签名失败");
            throw new CommonException("支付回调参数错误,校验签名失败");
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getOrderStatus(String partnerThirdOrderId) {
        SystemParam systemParam = systemParamMapper.getDefaultParam();
        VipCardOrder vipCardOrder = vipCardOrderMapper.getOrderByThirdId(partnerThirdOrderId);
        if (vipCardOrder == null) {
            throw new CommonException("该订单不存在");
        }
        String status = vipCardOrder.getStatus();
        if (!VipCardOrderEnum.STATUS_INIT.getCode().equals(status)) {
            return vipCardOrder.getStatus();
        }
        if (PayTypeEnum.LIE_XIONG.getCode().equals(systemParam.getPaymentMethod())) {
            String accessToken = lieXiongUtil.getAccessToken();
            OrderVo orderVo = lieXiongUtil.getOrderStatus(vipCardOrder.getPartnerThirdOrderId(), accessToken);
            String newStatus = orderVo.getStatus();
            String systemStatus = LieXiongOrderEnum.parseSystemStatus(newStatus);
            if (!systemStatus.equals(vipCardOrder.getStatus())) {
                vipCardOrder.setStatus(systemStatus);
 
                // 于2022-12-11新增:用于跟踪为什么partnerThirdOrderId为空
                logger.info("getOrderStatus LIE_XIONG partnerThirdOrderId:{}", partnerThirdOrderId);
                // 完
 
                update(Wrappers.<VipCardOrder>lambdaUpdate()
                        .set(VipCardOrder::getStatus, systemStatus)
                        .eq(VipCardOrder::getPartnerThirdOrderId, vipCardOrder.getPartnerThirdOrderId()));
                if (VipCardOrderEnum.STATUS_END.getCode().equals(systemStatus)) {
                    DateTime start = DateUtil.parse(orderVo.getStartDate());
                    DateTime end = DateUtil.parse(orderVo.getEndDate());
                    VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(vipCardOrder.getUserId(), null, start, end);
                    customerUserService.updateVipEffectiveTime(vipCardOrder, vipEffectiveTimeVo);
                }
            }
            return vipCardOrder.getStatus();
        } else if (PayTypeEnum.YIN_SHENG.getCode().equals(systemParam.getPaymentMethod())) {
            VipCardOrder order = getOne(Wrappers.<VipCardOrder>lambdaQuery()
                    .eq(VipCardOrder::getPartnerThirdOrderId, partnerThirdOrderId));
            JSONObject response = yinShengUtil.getOrderStatus(order);
            if (response != null) {
                String yinShengStatus = response.getString("trade_status");
                String yinshengOrderId = response.getString("trade_no");
                String systemStatus = YinShengOrderEnum.parseSystemStatus(yinShengStatus);
                String oldStatus = vipCardOrder.getStatus();
                vipCardOrder.setStatus(systemStatus);
                vipCardOrder.setOrderId(yinshengOrderId);
 
                // 于2022-12-11新增:用于跟踪为什么partnerThirdOrderId为空
                logger.info("getOrderStatus YIN_SHENG partnerThirdOrderId:{}", partnerThirdOrderId);
                // 完
                //2022-12-12 bug fix
                if (StringUtils.isNotBlank(partnerThirdOrderId)) {
                    update(Wrappers.lambdaUpdate(VipCardOrder.class)
                            .set(VipCardOrder::getStatus, systemStatus)
                            .set(VipCardOrder::getOrderId, yinshengOrderId)
                            .eq(VipCardOrder::getPartnerThirdOrderId, partnerThirdOrderId));
                }
                if (!systemStatus.equals(oldStatus) && VipCardOrderEnum.STATUS_END.getCode().equals(systemStatus)) {
                    VipCard card = vipCardMapper.selectOne(Wrappers.<VipCard>lambdaQuery()
                            .eq(VipCard::getCardId, vipCardOrder.getCardId()));
                    if (card == null) {
                        logger.error("更新用户会员到期时间失败,会员卡不存在,原始数据" + vipCardOrder);
                        throw new CommonException("查询银盛订单状态出错:对应会员卡不存在");
                    }
                    VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(vipCardOrder.getUserId(), card.getValidDate(), null, null);
                    customerUserService.updateVipEffectiveTime(vipCardOrder, vipEffectiveTimeVo);
                }
                return vipCardOrder.getStatus();
            } else {
                throw new CommonException("查询银盛订单状态出错");
            }
        } else if (PayTypeEnum.ALIPAY_SDK.getCode().equals(systemParam.getPaymentMethod()) || PayTypeEnum.ALIPAY_H5.getCode().equals(systemParam.getPaymentMethod())) {
            // 查询订单状态并返回就O了
            return vipCardOrder.getStatus();
        } else if (PayTypeEnum.WEI_YA.getCode().equals(systemParam.getPaymentMethod())) {
            String stat = vipCardOrder.getStatus();
            if (VipCardOrderEnum.STATUS_INIT.getCode().equals(stat)) {
                // 额外添加一次主动查询
                log.info("纬雅支付状态查询:order={}", vipCardOrder);
                WeiYaUserGetRespVO user = weiYaUtil.userGet(vipCardOrder);
                if (user == null) {
                    return stat;
                }
                if (Objects.equals(user.getType(), 2)) {
                    // 会员开通成功
                    // 支付成功,更新会员订单状态与支付宝订单号
 
                    // 于2022-12-11新增:用于跟踪为什么partnerThirdOrderId为空
                    logger.info("getOrderStatus WEI_YA partnerThirdOrderId:{}", partnerThirdOrderId);
                    // 完
 
                    update(Wrappers.<VipCardOrder>lambdaUpdate()
                            .set(VipCardOrder::getStatus, VipCardOrderEnum.STATUS_END.getCode())
                            .eq(VipCardOrder::getPartnerThirdOrderId, vipCardOrder.getPartnerThirdOrderId()));
 
                    // 更新用户会员到期时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date from, to;
                    try {
                        from = sdf.parse(Objects.requireNonNull(user.getStartTime(), "纬雅支付USER_GET接口查询返回startTime为null"));
                        to = sdf.parse(Objects.requireNonNull(user.getEndTime(), "纬雅支付USER_GET接口查询返回endTime为null"));
                    } catch (ParseException e) {
                        throw new CommonException("纬雅支付USER_GET接口返回日期格式化失败!", e);
                    }
                    customerUserService.updateVipEffectiveTime(vipCardOrder, new VipEffectiveTimeVo(from, to));
                    stat = VipCardOrderEnum.STATUS_END.getCode();
                    log.info("纬雅支付主动查询状态并更新数据成功");
                }
            }
            return stat;
        } else if (PayTypeEnum.SHAN_TAI_FAST_PROTOCOL.getCode().equals(systemParam.getPaymentMethod())) {
            VipCardOrder order = getOne(Wrappers.<VipCardOrder>lambdaQuery()
                    .eq(VipCardOrder::getPartnerThirdOrderId, partnerThirdOrderId));
            return getStatus(partnerThirdOrderId, vipCardOrder, order);
        }
        logger.error("未找到该订单匹配的支付方式");
        throw new CommonException("未找到该订单匹配的支付方式");
    }
 
    private String getStatus(String partnerThirdOrderId, VipCardOrder vipCardOrder, VipCardOrder order) {
        GetOrderStatusVo orderStatus = shanTaiService.getOrderStatus(order.getOrderId());
        if (orderStatus != null) {
            String value = orderStatus.getValue();
            String systemStatus = ShanTaiServiceImpl.parseSelectSystemStatus(value);
            String oldStatus = vipCardOrder.getStatus();
            vipCardOrder.setStatus(systemStatus);
            if (!systemStatus.equals(oldStatus) && !VipCardOrderEnum.STATUS_END.getCode().equalsIgnoreCase(oldStatus)) {
 
                // 于2022-12-11新增:用于跟踪为什么partnerThirdOrderId为空
                logger.info("getStatus partnerThirdOrderId:{}", partnerThirdOrderId);
                // 完
 
                update(Wrappers.<VipCardOrder>lambdaUpdate()
                        .set(VipCardOrder::getStatus, systemStatus)
                        .eq(VipCardOrder::getPartnerThirdOrderId, partnerThirdOrderId));
            }
            if (!systemStatus.equals(oldStatus) && VipCardOrderEnum.STATUS_END.getCode().equals(systemStatus)) {
                VipCard card = vipCardMapper.selectOne(Wrappers.<VipCard>lambdaQuery()
                        .eq(VipCard::getCardId, vipCardOrder.getCardId()));
                if (card == null) {
                    logger.error("更新用户会员到期时间失败,会员卡不存在,原始数据" + vipCardOrder);
                    throw new CommonException("查询闪态订单状态出错:对应会员卡不存在");
                }
                VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(vipCardOrder.getUserId(), card.getValidDate(), null, null);
                customerUserService.updateVipEffectiveTime(vipCardOrder, vipEffectiveTimeVo);
            }
            return vipCardOrder.getStatus();
        } else {
            throw new CommonException("查询闪态订单状态出错");
        }
    }
 
 
    @Override
    public VipUserStatusVo checkUserStatus(UserDetail userDetail, String appId) {
        VipUserStatusVo vipUserStatusVo = new VipUserStatusVo();
        CustomerUser customerUser = getUser(userDetail.getPhone());
        vipUserStatusVo.setUserId(customerUser.getId());
        vipUserStatusVo.setPhone(customerUser.getPhone());
        vipUserStatusVo.setBusinessType(customerUser.getBusinessType());
        //判断改手机号是否已经进入黑名单
        Roster roster = rosterService.getOne(Wrappers.lambdaQuery(Roster.class).eq(Roster::getPhone, userDetail.getPhone()));
        if (Objects.nonNull(roster)) {
            vipUserStatusVo.setIsRoster(1);
        } else {
            vipUserStatusVo.setIsRoster(0);
        }
        //判断用户是否是测试账户
        boolean userIsTest = checkUserIsTest(customerUser);
        vipUserStatusVo.setHasTestUser(userIsTest);
        //判断用户是否已购买会员服务
        boolean memberVipStatus = checkUserVipStatus(customerUser.getVipEndDate());
        vipUserStatusVo.setHasVipCard(memberVipStatus);
        //判断用户是否已购买高级会员服务
        boolean seniorVipStatus = checkUserSeniorVipStatus(customerUser.getSeniorVipEndDate());
        vipUserStatusVo.setHasSeniorVip(seniorVipStatus);
        //判断用户是否已达到下次申请时间
        boolean dateValid = customerUser.getNextApplyTime() == null || !customerUser.getNextApplyTime().before(new Date());
        //判断用户是否已购买贷超会员
        boolean loanMarketVipStatus = checkUserVipStatus(customerUser.getLoanVipEndDate());
        vipUserStatusVo.setHasLoanMarketVip(loanMarketVipStatus);
        //读取用户最新一条申请记录,判断是否已有历史记录
        Customer customer = customerMapper.getLatestCustomerRecord(customerUser.getPhone());
        DateTime checkDate = DateUtil.offsetDay(new Date(), -Customer.VALID_DAY);
        if (customer != null && customer.getApplyDate().before(checkDate)) {
            customer = null;
        }
        vipUserStatusVo.setFirstQuota(customerUser.getFirstQuota());
        //初始化用户信息
        if (!dateValid) {
            customerUser.setQueueVipCode(QueueVipTypeEnum.NONE.getCode());
            customerUserService.update(Wrappers.<CustomerUser>lambdaUpdate()
                    .set(CustomerUser::getQueueVipCode, customerUser.getQueueVipCode())
                    .set(CustomerUser::getCreditNo, null)
                    .set(CustomerUser::getCommonQueue, null)
                    .eq(CustomerUser::getId, customerUser.getId()));
        }
        vipUserStatusVo.setQueueVipCode(customerUser.getQueueVipCode());
        if (customer == null || !dateValid) {
            //无历史记录或已到下次申请时间
            vipUserStatusVo.setHasRecord(false);
            vipUserStatusVo.setVipQuota(null);
        } else {
            //有历史记录信息
            vipUserStatusVo.setHasRecord(true);
            vipUserStatusVo.setCustomerId(customer.getId());
            vipUserStatusVo.setInfoStatus(customer.getStatus());
            vipUserStatusVo.setBankName(customer.getBankName());
            vipUserStatusVo.setCardNo(customer.getCardNo());
            vipUserStatusVo.setRepayApplyDate(customer.getRepayApplyDate());
            vipUserStatusVo.setHasRepayPlan(customer.getHasRepayPlan());
            vipUserStatusVo.setRepayAmount(customer.getRepayAmount());
            vipUserStatusVo.setRepayTerm(customer.getRepayTerm());
            vipUserStatusVo.setVipQuota(customerUser.getVipQuota());
            vipUserStatusVo.setNextApplyTime(customerUser.getNextApplyTime());
            vipUserStatusVo.setApprovalTime(customerUser.getApprovalTime());
            vipUserStatusVo.setPassApproval(customer.getPassApproval());
            vipUserStatusVo.setAssetFromBrowser(customer.getAssetFromBrowser());
            if (customer.getRepayTerm() == null) {
                vipUserStatusVo.setRepayTerm(customer.getLoanTerm());
            }
            if (customerUser.getShowActivationPage() != null) {
                vipUserStatusVo.setShowActivationPage(customerUser.getShowActivationPage());
            }
        }
        SystemParam defaultParam = systemParamMapper.getDefaultParam();
        vipUserStatusVo.setQueuePayType(defaultParam.getQueuePayType());
 
        ChannelInfo channelInfo = channelInfoService.getOne(new LambdaQueryWrapper<ChannelInfo>().eq(ChannelInfo::getCode, customerUser.getSourceChannel()));
        if (1 == channelInfo.getVersion4IsOpen()) {
            if (customer != null) {
                if (CustomerInfoStatusEnum.BANKCARD_INFO.getCode().equals(customer.getStatus()) ||
                        CustomerInfoStatusEnum.COMPANY_INFO.getCode().equals(customer.getStatus()) ||
                        CustomerInfoStatusEnum.CAPITAL_INFO.getCode().equals(customer.getStatus())) {
                    vipUserStatusVo.setQueueVipCode(QueueVipTypeEnum.NORMAL.getCode());
                }
            }
        }
        if (customer != null) {
            if (CustomerInfoStatusEnum.CAPITAL_INFO.getCode().equals(customer.getStatus())) {
                vipUserStatusVo.setQueueVipCode(QueueVipTypeEnum.NORMAL.getCode());
            }
            vipUserStatusVo.setDataIsCompleted(customer.getDataIsCompleted());
        }
        return vipUserStatusVo;
    }
 
    private boolean checkUserVipStatus(Date endDate) {
        if (endDate != null) {
            int compare = DateUtil.compare(new Date(), endDate);
            return compare < 0;
        }
        return false;
    }
 
    private boolean checkUserSeniorVipStatus(Date endDate) {
        if (endDate != null) {
            int compare = DateUtil.compare(new Date(), endDate);
            return compare < 0;
        }
        return false;
    }
 
    private boolean checkUserIsTest(CustomerUser customerUser) {
        return 1 == customerUser.getTestUserFlag();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public VipUserStatusVo updateUserApprovalTime(String phone, String appId) {
        CustomerUser customerUser = getUser(phone);
        ChannelVipConfigVo channelVipConfig = channelInfoService.getChannelVipConfig(appId, phone);
        //更新用户审核时间
        DateTime approvalTime = DateUtil.offsetMinute(new Date(), channelVipConfig.getQuotaApprovalTime());
        DateTime nextApplyTime = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), Customer.VALID_DAY));
        customerUser.setApprovalTime(approvalTime);
        customerUser.setNextApplyTime(nextApplyTime);
        customerUser.setFirstQuota(randomQuota());
        customerUser.setVipQuota(randomVipQuota(customerUser.getFirstQuota()));
        customerUser.setShowActivationPage(true);
        customerUserMapper.updateById(customerUser);
        //返回当前用户状态信息
        Customer customer = customerMapper.getLatestCustomerRecord(customerUser.getPhone());
        VipUserStatusVo vipUserStatusVo = new VipUserStatusVo();
        vipUserStatusVo.setUserId(customerUser.getId());
        vipUserStatusVo.setPhone(customerUser.getPhone());
        vipUserStatusVo.setHasRecord(true);
        vipUserStatusVo.setFirstQuota(customerUser.getFirstQuota());
        vipUserStatusVo.setVipQuota(customerUser.getVipQuota());
        vipUserStatusVo.setApprovalTime(customerUser.getApprovalTime());
        vipUserStatusVo.setNextApplyTime(customerUser.getNextApplyTime());
        vipUserStatusVo.setCustomerId(customer.getId());
        vipUserStatusVo.setInfoStatus(customer.getStatus());
        vipUserStatusVo.setShowActivationPage(customerUser.getShowActivationPage());
        return vipUserStatusVo;
    }
 
    public static Integer randomQuota() {
        Random random = new Random();
        int nextInt = 3 + random.nextInt(8);
        return nextInt * 1000;
    }
 
    public static Integer randomVipQuota(Integer quota) {
        Random random = new Random();
        int nextInt = 1 + random.nextInt(6);
        return quota + nextInt * 1000;
    }
 
    private CustomerUser getUser(String phone) {
        LambdaQueryWrapper<CustomerUser> customerUserWrapper = new LambdaQueryWrapper<>();
        customerUserWrapper.eq(CustomerUser::getPhone, phone);
        customerUserWrapper.eq(CustomerUser::getDeleteFlag, 0);
        CustomerUser customerUser = customerUserMapper.selectOne(customerUserWrapper);
        if (customerUser == null) throw new CommonException("用户不存在");
        return customerUser;
    }
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BuyCardParamVo buyCardByYinSheng(VipCardVo cardVo, UserDetail userDetail) {
        //生成系统内订单
        String orderNo = SerialGenerator.getOrder();
        CustomerUser customerUser = getUser(userDetail.getPhone());
        VipCardOrder vipCardOrder = initVipCardOrder(orderNo, orderNo, PayTypeEnum.YIN_SHENG.getCode(), customerUser.getId(), cardVo);
        save(vipCardOrder);
        //构建银盛需要的参数
        Map<String, String> param = yinShengUtil.generateParam(cardVo, orderNo);
        BuyCardParamVo paramVo = new BuyCardParamVo();
        paramVo.setPayType(PayTypeEnum.YIN_SHENG.getCode());
        paramVo.setYinShengParam(param);
        paramVo.setPartnerThirdOrderId(orderNo);
        logger.info("银盛支付订单参数:" + paramVo);
        return paramVo;
    }
 
 
    @Override
    public String notifyByYinSheng(Map<String, String> params) {
        try {
            logger.info("银盛接口回调参数RequestParams->:{}", params);
            if (yinShengUtil.asynVerifyYs(params)) {
                //系统内订单状态更新
                String yinshengOrderId = params.get("trade_no");
                String orderId = params.get("out_trade_no");
                String status = params.get("trade_status");
                VipCardOrder vipCardOrder = lambdaQuery().eq(VipCardOrder::getPartnerThirdOrderId, orderId).one();
                String systemStatus = YinShengOrderEnum.parseSystemStatus(status);
                if (VipCardOrderEnum.STATUS_INVALID.getCode().equals(systemStatus)) {
                    logger.error("订单回调类型非法,回调类型" + status);
                }
                if (vipCardOrder != null) {
                    String oldStatus = vipCardOrder.getStatus();
                    vipCardOrder.setStatus(systemStatus);
                    vipCardOrder.setOrderId(yinshengOrderId);
                    if (!systemStatus.equals(oldStatus)) {
 
                        // 于2022-12-11新增:用于跟踪为什么partnerThirdOrderId为空
                        logger.info("notifyByYinSheng partnerThirdOrderId:{}", params);
                        // 完
 
                        if (StringUtils.isNotBlank(orderId)) {
                            update(Wrappers.lambdaUpdate(VipCardOrder.class)
                                    .set(VipCardOrder::getStatus, systemStatus)
                                    .set(VipCardOrder::getOrderId, yinshengOrderId)
                                    .eq(VipCardOrder::getPartnerThirdOrderId, orderId));
                        }
 
                        if (VipCardOrderEnum.STATUS_END.getCode().equals(systemStatus)) {
                            VipCard card = vipCardMapper.selectOne(Wrappers.<VipCard>lambdaQuery()
                                    .eq(VipCard::getCardId, vipCardOrder.getCardId()));
                            if (card == null) {
                                logger.error("银盛接口回调失败,对应会员卡不存在,原始数据" + vipCardOrder);
                                throw new CommonException("对应会员卡不存在");
                            }
                            VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(vipCardOrder.getUserId(), card.getValidDate(), null, null);
                            customerUserService.updateVipEffectiveTime(vipCardOrder, vipEffectiveTimeVo);
                        }
                    }
                } else {
                    logger.error("银盛接口回调失败,对应订单不存在");
                    throw new CommonException("对应订单不存在");
                }
                return "success";
            }
        } catch (Exception e) {
            logger.error(String.format("银盛回调接口异常,参数map=>", params) + e);
        }
        return "failure";
    }
 
    /**
     * <a href="https://opendocs.alipay.com/open/203/105285">...</a>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BuyCardParamVo buyCardByAlipay(VipCardVo cardVo, UserDetail user, Integer payType) {
        String orderId = SerialGenerator.getOrder();
        CustomerUser customerUser = getUser(user.getPhone());
        String amountValue = cardVo.parseSellingPrice();
        logger.info("开始创建支付宝订单, orderId={}, card={}", orderId, cardVo);
 
        BigDecimal amount = new BigDecimal(amountValue);
        SysAlipayAccount targetAccount;
        long usageId = alipayPlatformService.accountDecision(orderId, amount);
        targetAccount = alipayAccountMapper.selectByUsageId(usageId);
        try {
            String form = alipayPlatformService.generateAlipayForm(targetAccount,
                    orderId, amountValue, cardVo.getName(),
                    cardVo.getUrl(), alipayConf.getNotifyUrl());
            // 支付宝订单创建成功
            // 创建本地订单信息,订单状态为init
            VipCardOrder vipCardOrder = initVipCardOrder(orderId, orderId, payType, customerUser.getId(), cardVo);
            save(vipCardOrder);
 
            // 返回订单信息的表单
            BuyCardParamVo vo = new BuyCardParamVo();
            vo.setPayType(payType);
            vo.setPartnerThirdOrderId(orderId);
            vo.setForm(form);
            logger.info("返回参数信息" + vo);
            return vo;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.error("支付宝订单创建失败:" + e.getMessage(), e);
            throw new CommonException("支付宝订单创建失败:" + e.getMessage(), e);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void alipayNotifyOrder(Map<String, String[]> map) {
        try {
            map.forEach((k, v) -> logger.info(">> 支付宝回调参数:alipayNotifyOrderTestRequestParams {} = {}", k, Arrays.toString(v)));
            String alipayOrderId = map.get("trade_no")[0];
            String orderId = map.get("out_trade_no")[0];
            String tradeStatus = map.get("trade_status")[0];
            String status = alipayOrderStatus(tradeStatus);
            if (!VipCardOrderEnum.STATUS_END.getCode().equals(status)) {
                // 支付失败,删除支付记录
                alipayAccountUsageMapper.delete(Wrappers.<SysAlipayAccountUsage>lambdaUpdate()
                        .eq(SysAlipayAccountUsage::getOrderId, orderId));
 
                // 于2022-12-11新增:用于跟踪为什么partnerThirdOrderId为空
                logger.info("alipayNotifyOrder 1 partnerThirdOrderId:{}", map);
                // 完
 
                // 更新订单状态
                update(Wrappers.<VipCardOrder>lambdaUpdate()
                        .set(VipCardOrder::getStatus, status)
                        .eq(VipCardOrder::getPartnerThirdOrderId, orderId));
            } else {
                alipayAccountUsageMapper.updateStatus(orderId);
 
                // 于2022-12-11新增:用于跟踪为什么partnerThirdOrderId为空
                logger.info("alipayNotifyOrder 2 partnerThirdOrderId:{}", map);
                // 完
 
                // 支付成功,更新会员订单状态与支付宝订单号
                if (StringUtils.isNotBlank(orderId)) {
                    update(Wrappers.<VipCardOrder>lambdaUpdate()
                            .set(VipCardOrder::getStatus, status)
                            .set(VipCardOrder::getOrderId, alipayOrderId)
                            .eq(VipCardOrder::getPartnerThirdOrderId, orderId));
                }
 
                // 获取卡信息
                VipCardOrder cardOrder = getOne(Wrappers.<VipCardOrder>lambdaQuery()
                        .eq(VipCardOrder::getPartnerThirdOrderId, orderId));
                if (cardOrder == null) {
                    throw new CommonException("对应支付记录不存在");
                }
                VipCard card = vipCardMapper.selectOne(Wrappers.<VipCard>lambdaQuery()
                        .eq(VipCard::getCardId, cardOrder.getCardId()));
                if (card == null) {
                    logger.error("支付宝接口回调失败,对应会员卡不存在,原始数据" + cardOrder);
                    throw new CommonException("对应会员卡不存在");
                }
                // 更新用户会员到期时间
                VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(cardOrder.getUserId(), card.getValidDate(), null, null);
                customerUserService.updateVipEffectiveTime(cardOrder, vipEffectiveTimeVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String msg = String.format("支付宝回调接口异常! map=%s", paramToString(map));
            logger.error(msg, e);
            throw new CommonException(msg, e);
        }
    }
 
    private List<VipCardVo> getVipCardListFromWeiYa() {
        HttpResponse resp = HttpRequest.post(weiyaConf.getGetChannelDataUrl())
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .body(weiYaUtil.generateParamForGetChannelData())
                .execute();
        if (resp.getStatus() == HttpStatus.HTTP_OK) {
            logger.info("url={}, resp={}", weiyaConf.getGetChannelDataUrl(), resp.body());
            WeiYaGetChannelDataResp resData = JSON.parseObject(resp.body(), WeiYaGetChannelDataResp.class);
            return weiYaUtil.transferToVipCardData(resData);
        }
        logger.error("访问纬雅权益接口获取所有权益信息失败! url={}, resp={}", weiyaConf.getGetChannelDataUrl(), resp);
        throw new CommonException("访问纬雅权益接口获取所有权益信息失败! url={}, resp={}", weiyaConf.getGetChannelDataUrl(), resp);
    }
 
    @Override
    public BuyCardParamVo buyCardByWeiYa(VipCardVo card, UserDetail user) {
        String orderId = SerialGenerator.getOrder();
 
        // 拼接纬雅权益支付的页面URL
        String returnUrl = card.getUrl();
        String phone = user.getPhone();
        CustomerUser customerUser = getUser(phone);
        String channelUserId = customerUser.getId().toString();
        String targetURL = weiYaUtil.memberPayUrl(
                channelUserId, phone, returnUrl, card.getCardId(), orderId);
 
        // 生成系统内订单
        VipCardOrder vipCardOrder = initVipCardOrder(orderId, orderId, PayTypeEnum.WEI_YA.getCode(), customerUser.getId(), card);
        save(vipCardOrder);
 
        // 返回体
        BuyCardParamVo vo = new BuyCardParamVo();
        vo.setWeiYaUrl(targetURL);
        vo.setPayType(PayTypeEnum.WEI_YA.getCode());
        vo.setPartnerThirdOrderId(orderId);
        logger.info("纬雅权益接口订单参数" + vo);
        return vo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void weiyaOrderNotify(WeiyaOrderNotifyDTO notifyDTO) {
        try {
            logger.info(">> 纬雅回调参数notifyDTO={}", notifyDTO);
            String status = weiyaOrderStatus(notifyDTO);
            if (!VipCardOrderEnum.STATUS_END.getCode().equals(status)) {
                // 支付失败,删除支付记录
                alipayAccountUsageMapper.delete(Wrappers.<SysAlipayAccountUsage>lambdaUpdate()
                        .eq(SysAlipayAccountUsage::getOrderId, notifyDTO.getSankuaiOrderId()));
 
                // 于2022-12-11新增:用于跟踪为什么partnerThirdOrderId为空
                logger.info("weiyaOrderNotify partnerThirdOrderId:{}", notifyDTO);
                // 完
 
                // 更新订单状态
                update(Wrappers.<VipCardOrder>lambdaUpdate()
                        .set(VipCardOrder::getStatus, status)
                        .eq(VipCardOrder::getPartnerThirdOrderId, notifyDTO.getOrderId()));
            } else {
                // 支付成功,更新会员订单状态与支付宝订单号
                update(Wrappers.<VipCardOrder>lambdaUpdate()
                        .set(VipCardOrder::getStatus, status)
                        .set(VipCardOrder::getPrice, notifyDTO.getPaymentAmount().doubleValue() * 100)
                        .set(VipCardOrder::getOrderId, notifyDTO.getOrderId())
                        .eq(VipCardOrder::getPartnerThirdOrderId, notifyDTO.getSankuaiOrderId()));
                VipCardOrder cardOrder = getOne(Wrappers.<VipCardOrder>lambdaQuery()
                        .eq(VipCardOrder::getPartnerThirdOrderId, notifyDTO.getSankuaiOrderId()));
                // 更新用户会员到期时间
                VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(cardOrder.getUserId(), notifyDTO.getPaymentDays(), null, null);
                customerUserService.updateVipEffectiveTime(cardOrder, vipEffectiveTimeVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String msg = String.format("纬雅回调接口异常! resp=%s", notifyDTO);
            logger.error(msg, e);
            throw new CommonException(msg, e);
        }
    }
 
    private String weiyaOrderStatus(WeiyaOrderNotifyDTO notifyDTO) {
        return "1".equals(notifyDTO.getOrderStatus()) ? VipCardOrderEnum.STATUS_END.getCode() : VipCardOrderEnum.STATUS_INVALID.getCode();
    }
 
    private String paramToString(Map<String, String[]> map) {
        StringBuilder sb = new StringBuilder();
        map.forEach((k, v) -> sb.append("key=").append(k).append(",value=").append(Arrays.toString(v)).append(", "));
        return sb.toString();
    }
 
    private String alipayOrderStatus(String alipayStatus) {
        switch (alipayStatus) {
            case "WAIT_BUYER_PAY":
                return VipCardOrderEnum.STATUS_INIT.getCode();
            case "TRADE_CLOSED":
                return VipCardOrderEnum.STATUS_CLOSE.getCode();
            case "TRADE_SUCCESS":
            case "TRADE_FINISHED":
                return VipCardOrderEnum.STATUS_END.getCode();
            default:
                return VipCardOrderEnum.STATUS_INVALID.getCode();
        }
    }
 
    @Override
    public JSONObject getVipCardListV2(String appId, String phone) {
        List<VipCardVo> vipCardList = getVipCardList(appId, phone);
        ChannelVipConfigVo channelVipConfig = channelInfoService.getChannelVipConfig(appId, phone);
        JSONObject result = new JSONObject();
        result.put("defaultCardId", channelVipConfig.getDefaultCardId());
        result.put("vipCardList", vipCardList);
        return result;
    }
 
    @Override
    public void updateShowActivationPage(String phone) {
        CustomerUser customerUser = customerUserService.getUserByPhone(phone);
        customerUser.setShowActivationPage(false);
        customerUserService.updateById(customerUser);
    }
 
    @Override
    public List<VipCardVo> getQueueVipList(String appId, String phone) {
        ChannelVipConfigVo channelVipConfig = channelInfoService.getChannelVipConfig(appId, phone);
        Integer memberDiscount = channelVipConfig.getMemberDiscount();
        return vipCardService.getVipCardList(memberDiscount, VipCardTypeEnum.AUDIT_QUEUE.getCode());
    }
 
    @Override
    public QueueVo getQueue(UserDetail user) {
        if (Objects.isNull(user)) throw new CommonException("用户不存在");
        CustomerUser customerUser = customerUserMapper.selectOne(Wrappers.lambdaQuery(CustomerUser.class).eq(CustomerUser::getPhone, user.getPhone()));
        if (Objects.isNull(customerUser)) throw new CommonException("用户不存在");
        QueueVo queueVo = new QueueVo();
        Random random = new Random();
        int vipQueue = 1 + random.nextInt(5);
        queueVo.setVipQueue(vipQueue);
        int commonQueue;
        if (customerUser.getCommonQueue() == null) {
            commonQueue = 2000 + random.nextInt(100);
        } else {
            commonQueue = customerUser.getCommonQueue() + random.nextInt(200);
        }
        customerUser.setCommonQueue(commonQueue);
        customerUserMapper.update(null, Wrappers.<CustomerUser>lambdaUpdate()
                .set(CustomerUser::getCommonQueue, commonQueue)
                .eq(CustomerUser::getId, customerUser.getId()));
        queueVo.setCommonQueue(customerUser.getCommonQueue());
        return queueVo;
    }
 
    @Override
    public VipCardVo getQueueDefaultVip(String appId, String phone) {
        VipCard vipCard;
        CustomerUser userByPhone = customerUserService.getUserByPhone(phone);
        if (Objects.isNull(userByPhone)) throw new CommonException("用户不存在");
        ChannelInfo channelInfoByCode = channelInfoService.getChannelInfoByCode(userByPhone.getSourceChannel());
        if (Objects.isNull(channelInfoByCode)) throw new CommonException("渠道不存在");
        if (1 == channelInfoByCode.getVersion4IsOpen()) {
            //4.0开关开启下的审核排队会员卡信息
            vipCard = vipCardMapper.selectOne(new LambdaQueryWrapper<VipCard>()
                    .eq(VipCard::getQueueVipCode, QueueVipTypeEnum.VIP3.getCode()));
        } else {
            vipCard = vipCardMapper.getDefaultCardByType(VipCardTypeEnum.AUDIT_QUEUE.getCode());
        }
        if (Objects.isNull(vipCard)) throw new CommonException("会员卡不存在");
        VipCardVo vipCardVo = new VipCardVo();
        vipCardVo.setCardId(vipCard.getCardId());
        vipCardVo.setName(vipCard.getCardName());
        vipCardVo.setSellingPrice(vipCard.getPrice());
        vipCardVo.setMarkedPrice(vipCard.getPrice());
        return vipCardVo;
    }
 
 
    @Override
    public VipCardVo getLoanMarketVip(String appId, String phone) {
        VipCard vipCard = vipCardMapper.getDefaultCardByType(VipCardTypeEnum.LOAN_MARKET_VIP.getCode());
        VipCardVo vipCardVo = new VipCardVo();
        vipCardVo.setCardId(vipCard.getCardId());
        vipCardVo.setName(vipCard.getCardName());
        vipCardVo.setSellingPrice(vipCard.getPrice());
        vipCardVo.setMarkedPrice(vipCard.getPrice());
        return vipCardVo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notifyInnerVipOrder(AlipayOrderInfo alipayOrderInfo) {
        String orderId = alipayOrderInfo.getOrderId();
        VipCardOrder vipCardOrder = vipCardOrderMapper.selectOne(Wrappers.<VipCardOrder>lambdaQuery()
                .eq(VipCardOrder::getOrderId, orderId));
        if (Objects.isNull(vipCardOrder)) throw new CommonException("订单不存在");
        String status = alipayOrderStatus(alipayOrderInfo.getOrderStatus());
        if (!VipCardOrderEnum.STATUS_END.getCode().equals(status)) {
            // 更新订单状态
            update(Wrappers.<VipCardOrder>lambdaUpdate()
                    .set(VipCardOrder::getStatus, status)
                    .eq(VipCardOrder::getId, vipCardOrder.getId()));
        } else {
            // 支付成功,更新会员订单状态与支付宝订单号
            update(Wrappers.<VipCardOrder>lambdaUpdate()
                    .set(VipCardOrder::getStatus, status)
                    .eq(VipCardOrder::getId, vipCardOrder.getId()));
            // 获取卡信息
            VipCard card = vipCardMapper.selectOne(Wrappers.<VipCard>lambdaQuery()
                    .eq(VipCard::getCardId, vipCardOrder.getCardId()));
            if (card == null) {
                logger.error("支付宝接口回调失败,对应会员卡不存在,原始数据" + vipCardOrder);
                throw new CommonException("会员卡不存在");
            }
            // 更新用户会员到期时间
            VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(vipCardOrder.getUserId(), card.getValidDate(), null, null);
            customerUserService.updateVipEffectiveTime(vipCardOrder, vipEffectiveTimeVo);
        }
    }
 
    @Override
    public VipCardVo getSeniorVip(String appId, String phone) {
        VipCard vipCard = vipCardMapper.getDefaultCardByType(VipCardTypeEnum.SENIOR_VIP.getCode());
        VipCardVo vipCardVo = new VipCardVo();
        vipCardVo.setCardId(vipCard.getCardId());
        vipCardVo.setName(vipCard.getCardName());
        vipCardVo.setSellingPrice(vipCard.getPrice());
        vipCardVo.setMarkedPrice(vipCard.getPrice());
        return vipCardVo;
    }
 
 
    @Override
    public PaymentCheckVo checkBeforePayment(PaymentCheckDto checkDto, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        UserDetail user = UserUtil.getUser(token);
        if (Objects.isNull(user) || Objects.isNull(user.getId())) throw new CommonException("Token无效");
        CustomerUser customerUser = customerUserMapper.selectById(user.getId());
        if (Objects.isNull(customerUser)) throw new CommonException("用户不存在");
        Integer payType = null;
        SystemParam systemParam = systemParamMapper.getDefaultParam();
        if (VipCardTypeEnum.MEMBER_SERVICE.getCode().equals(checkDto.getVipCardType())) {
            payType = systemParam.getPaymentMethod();
        } else if (VipCardTypeEnum.AUDIT_QUEUE.getCode().equals(checkDto.getVipCardType())) {
            payType = systemParam.getQueuePayType();
        } else if (VipCardTypeEnum.LOAN_MARKET_VIP.getCode().equals(checkDto.getVipCardType())) {
            payType = systemParam.getLoanVipPayType();
        } else if (VipCardTypeEnum.SENIOR_VIP.getCode().equals(checkDto.getVipCardType())) {
            payType = systemParam.getSeniorVipPayType();
        }
        if (Objects.isNull(payType)) throw new CommonException("不存在的会员类型");
        PaymentCheckVo checkVo = new PaymentCheckVo();
        checkVo.setPayType(payType);
        if (PayTypeEnum.YIN_SHENG_FAST_PROTOCOL.getCode().equals(payType)) {// 银盛
            boolean result = yinShengService.checkBeforePayment(customerUser.getId());// 查看签约状态
            checkVo.setCheckResult(result);
        } else if (PayTypeEnum.SHAN_TAI_FAST_PROTOCOL.getCode().equals(payType)) {// 汇付宝
//            boolean result = shanTaiService.checkBeforePayment(customerUser.getId());
//            checkVo.setCheckResult(result);
            boolean result = huiFuBaoSignService.checkBeforePayment(customerUser.getId());
            checkVo.setCheckResult(result);
        } else if (PayTypeEnum.BAOFU_PROTOCOL.getCode().equals(payType)) {// 宝付
            boolean result = baofuService.checkBeforePayment(customerUser.getId());
            checkVo.setCheckResult(result);
        } /*else if (PayTypeEnum.HUIFUBAO_PROTOCOL.getCode().equals(payType)) {// 宝付
            boolean result = huiFuBaoSignService.checkBeforePayment(customerUser.getId());
            checkVo.setCheckResult(result);
        }*/ else {
            checkVo.setCheckResult(true);
        }
        return checkVo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BuyCardParamVo buyCardByYSProtocol(VipCardVo cardVo, UserDetail userDetail) {
        //生成系统内订单
        String orderNo = SerialGenerator.getOrder();
        CustomerUser customerUser = getUser(userDetail.getPhone());
        VipCard card = vipCardMapper.selectOne(Wrappers.lambdaQuery(VipCard.class).eq(VipCard::getCardId, cardVo.getCardId()));
        if (Objects.isNull(card)) throw new CommonException("对应会员卡不存在");
        VipCardOrder vipCardOrder = initVipCardOrder(orderNo, orderNo, PayTypeEnum.YIN_SHENG_FAST_PROTOCOL.getCode(), customerUser.getId(), cardVo);
        YSFastProtocolParamVo protocolParamVo = yinShengService.buyCardByYSProtocol(vipCardOrder, cardVo, card);
        BuyCardParamVo paramVo = new BuyCardParamVo();
        paramVo.setPayType(PayTypeEnum.YIN_SHENG_FAST_PROTOCOL.getCode());
        paramVo.setPartnerThirdOrderId(vipCardOrder.getPartnerThirdOrderId());
        paramVo.setYsFastProtocolParam(protocolParamVo);
        return paramVo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BuyCardParamVo buyCardBySTProtocol(VipCardVo cardVo, UserDetail userDetail) {
        //生成系统内订单
        //String orderNo = SerialGenerator.getOrder();
        String orderNo = serialGenerator.getOrderWithServerName();
        CustomerUser customerUser = getUser(userDetail.getPhone());
        Customer customer = customerMapper.getLatestCustomerRecord(customerUser.getPhone());
        if (Objects.isNull(customer)) throw new CommonException("银行卡信息不存在");
        VipCard card = vipCardMapper.selectOne(Wrappers.lambdaQuery(VipCard.class).eq(VipCard::getCardId, cardVo.getCardId()));
        if (Objects.isNull(card)) throw new CommonException("对应会员卡不存在");
        if (StringUtils.isBlank(card.getCardId())) throw new CommonException("对应价格未设置");
        List<ShanTaiSignRecord> signRecords = shanTaiSignRecordMapper.selectList(Wrappers.lambdaQuery(ShanTaiSignRecord.class).eq(ShanTaiSignRecord::getCustomerUserId, customerUser.getId()).orderByDesc(ShanTaiSignRecord::getCreationDate));
        ShanTaiSignRecord shanTaiSignRecord = null;
        if (!CollectionUtils.isEmpty(signRecords)) shanTaiSignRecord = signRecords.get(0);
        if (Objects.isNull(shanTaiSignRecord)) throw new CommonException("该用户还未绑定银行卡");
        ShanTaiPayDto shanTaiPayDto = new ShanTaiPayDto();
        shanTaiPayDto.setCardId(card.getStCardId());
        shanTaiPayDto.setBankCardNo(shanTaiSignRecord.getSignCardNumber());
        shanTaiPayDto.setPartnerThirdOrderId(orderNo);
        VipCardOrder vipCardOrder = initVipCardOrder(orderNo, orderNo, PayTypeEnum.SHAN_TAI_FAST_PROTOCOL.getCode(), customerUser.getId(), cardVo);
        vipCardOrderMapper.insert(vipCardOrder);
        ShanTaiPayInfo protocolParamVo = shanTaiService.buyCardStartDirect(shanTaiPayDto, userDetail);
        if (Objects.isNull(protocolParamVo)) throw new CommonException("直接通知扣费异常");
        vipCardOrderMapper.update(null, Wrappers.lambdaUpdate(VipCardOrder.class)
                .set(VipCardOrder::getOrderId, protocolParamVo.getPayOrderId())
                .eq(VipCardOrder::getId, vipCardOrder.getId()));
        BuyCardParamVo paramVo = new BuyCardParamVo();
        paramVo.setPayType(PayTypeEnum.SHAN_TAI_FAST_PROTOCOL.getCode());
        paramVo.setPartnerThirdOrderId(vipCardOrder.getPartnerThirdOrderId());
        paramVo.setStFastProtocolParam(protocolParamVo);
        if (ShanTaiSureTypeEnum.SMS_VERIFY.getCode().equalsIgnoreCase(protocolParamVo.getType())) {
            paramVo.setSTVerificationType(0);
        } else {
            paramVo.setSTVerificationType(1);
        }
        return paramVo;
    }
 
    /**
     * 购买会员服务预支付
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BuyCardParamVo buyCardByBfProtocol(VipCardVo cardVo, UserDetail userDetail) {
        //生成系统内订单
        String orderNo = SerialGenerator.getOrder();
        CustomerUser customerUser = getUser(userDetail.getPhone());
        Customer customer = customerMapper.getLatestCustomerRecord(customerUser.getPhone());
        if (Objects.isNull(customer)) throw new CommonException("银行卡信息不存在");
        VipCard card = vipCardMapper.selectOne(Wrappers.lambdaQuery(VipCard.class).eq(VipCard::getCardId, cardVo.getCardId()));
        if (Objects.isNull(card)) throw new CommonException("对应会员卡不存在");
        if (StringUtils.isBlank(card.getCardId())) throw new CommonException("对应价格未设置");
        BaofuSignRecord baofuSignRecord = null;
        List<BaofuSignRecord> signRecords = baofuSignRecordMapper.selectList(Wrappers.
                lambdaQuery(BaofuSignRecord.class).eq(BaofuSignRecord::getCustomerUserId, customerUser.getId())
                .orderByDesc(BaofuSignRecord::getCreationDate));
        if (!signRecords.isEmpty()) {
            baofuSignRecord = signRecords.get(0);
        }
        if (baofuSignRecord == null) {
            throw new CommonException("该用户还未绑定银行卡");
        }
//        BaofuPayDto baofuPayDto = new BaofuPayDto();
//        baofuPayDto.setCardId(card.getStCardId());
//        baofuPayDto.setBankCardNo(baofuSignRecord.getSignCardNumber());
//        baofuPayDto.setPartnerThirdOrderId(orderNo);
        RecordDto recordDto = new RecordDto();
        recordDto.setAmount(card.getPrice());
        String tradeNo = ConstantsUtil.getOrder();// 订单号
        recordDto.setOrderId(orderNo);
        recordDto.setPartnerThirdOrderId(tradeNo);
        VipCardOrder vipCardOrder = initVipCardOrder(orderNo, tradeNo, PayTypeEnum.BAOFU_PROTOCOL.getCode(), customerUser.getId(), cardVo);
        vipCardOrderMapper.insert(vipCardOrder);
        BaofuRecordPayInfo recordPayInfo = baofuService.readyPay(recordDto, userDetail);
        if (recordPayInfo == null) {
            throw new CommonException("宝付预支付异常");
        }
 
        if (recordPayInfo.getError() != null) {
            throw new CommonException(recordPayInfo.getError());
        }
 
 
        BuyCardParamVo paramVo = new BuyCardParamVo();
        paramVo.setPayType(PayTypeEnum.BAOFU_PROTOCOL.getCode());
        paramVo.setPartnerThirdOrderId(vipCardOrder.getPartnerThirdOrderId());
        paramVo.setUiqueCode(recordPayInfo.getUniqueCode());// 预支付返回的唯一码
        paramVo.setSTVerificationType(0);
        return paramVo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BuyCardParamVo buyCardByHFBProtocol(VipCardVo cardVo, UserDetail userDetail) {
        //生成系统内订单
        //String orderNo = SerialGenerator.getOrder();
        String orderNo = serialGenerator.getOrderWithServerName();
        CustomerUser customerUser = getUser(userDetail.getPhone());
        Customer customer = customerMapper.getLatestCustomerRecord(customerUser.getPhone());
        if (Objects.isNull(customer)) throw new CommonException("银行卡信息不存在");
        VipCard card = vipCardMapper.selectOne(Wrappers.lambdaQuery(VipCard.class).eq(VipCard::getCardId, cardVo.getCardId()));
        if (Objects.isNull(card)) throw new CommonException("对应会员卡不存在");
        if (StringUtils.isBlank(card.getCardId())) throw new CommonException("对应价格未设置");
        List<HuifubaoSignRecord> signRecords = huifubaoSignRecordMapper.selectList(Wrappers.lambdaQuery(HuifubaoSignRecord.class).eq(HuifubaoSignRecord::getCustomerUserId, customerUser.getId()).orderByDesc(HuifubaoSignRecord::getCreationDate));
        HuifubaoSignRecord huifubaoSignRecord = null;
        if (!CollectionUtils.isEmpty(signRecords)) huifubaoSignRecord = signRecords.get(0);
        if (Objects.isNull(huifubaoSignRecord)) throw new CommonException("该用户还未绑定银行卡");
        HuiFuBaoPayVo huiFuBaoPayVo = new HuiFuBaoPayVo();
        BigDecimal bigDecimal = new BigDecimal(cardVo.getSellingPrice()).divide(new BigDecimal(100));
        huiFuBaoPayVo.setPayAmt(bigDecimal);
        huiFuBaoPayVo.setHyAuthUid(huifubaoSignRecord.getSignUniqueCode());
        huiFuBaoPayVo.setGoodsName("hfb支付");
        VipCardOrder vipCardOrder = initVipCardOrder(orderNo, orderNo, PayTypeEnum.SHAN_TAI_FAST_PROTOCOL.getCode(), customerUser.getId(), cardVo);
        vipCardOrderMapper.insert(vipCardOrder);
        HuiFuBaoSendPayInfo huiFuBaoSendPayInfo = huiFuBaoPayService.sendPaySMS(huiFuBaoPayVo, userDetail);
        if (Objects.isNull(huiFuBaoSendPayInfo)) throw new CommonException("短信通知扣费异常");
        vipCardOrderMapper.update(null, Wrappers.lambdaUpdate(VipCardOrder.class)
                .set(VipCardOrder::getOrderId, huiFuBaoSendPayInfo.getAgentBillId())
                .eq(VipCardOrder::getId, vipCardOrder.getId()));
        ShanTaiPayInfo shanTaiPayInfo = new ShanTaiPayInfo();
        shanTaiPayInfo.setPayOrderId(huiFuBaoSendPayInfo.getAgentBillId());
        shanTaiPayInfo.setType("SMS_VERIFY");
        shanTaiPayInfo.setSmsLength(String.valueOf(huiFuBaoSendPayInfo.getHyTokenId().length()));
        shanTaiPayInfo.setBankCode(huifubaoSignRecord.getSignCardNumber());
        BuyCardParamVo paramVo = new BuyCardParamVo();
        paramVo.setPayType(PayTypeEnum.SHAN_TAI_FAST_PROTOCOL.getCode());
        paramVo.setPartnerThirdOrderId(vipCardOrder.getPartnerThirdOrderId());
        paramVo.setSTVerificationType(0);
        paramVo.setUiqueCode(huiFuBaoSendPayInfo.getHyTokenId());// 预支付返回的唯一码
        paramVo.setStFastProtocolParam(shanTaiPayInfo);
        return paramVo;
    }
 
    @Override
    public String getSTOrderStatus(String partnerThirdOrderId) {
        VipCardOrder vipCardOrder = vipCardOrderMapper.getOrderByThirdId(partnerThirdOrderId);
        if (vipCardOrder == null) {
            throw new CommonException("该订单不存在");
        }
        String status = vipCardOrder.getStatus();
        if (!VipCardOrderEnum.STATUS_INIT.getCode().equals(status) && !VipCardOrderEnum.STATUS_WAIT.getCode().equals(status)) {
            return vipCardOrder.getStatus();
        }
        return getStatus(partnerThirdOrderId, vipCardOrder, vipCardOrder);
    }
 
    @Override
    public String getHFBOrderStatus(String partnerThirdOrderId) {
        VipCardOrder vipCardOrder = vipCardOrderMapper.getOrderByThirdId(partnerThirdOrderId);
        if (vipCardOrder == null) {
            throw new CommonException("该订单不存在");
        }
        String status = vipCardOrder.getStatus();
        if (!VipCardOrderEnum.STATUS_INIT.getCode().equals(status) && !VipCardOrderEnum.STATUS_WAIT.getCode().equals(status)) {
            return vipCardOrder.getStatus();
        }
 
        GetOrderStatusVo orderStatus = huiFuBaoPayService.getOrderStatus(vipCardOrder.getOrderId());
        String value = orderStatus.getValue();
        update(Wrappers.<VipCardOrder>lambdaUpdate()
                .set(VipCardOrder::getStatus, value)
                .eq(VipCardOrder::getPartnerThirdOrderId, partnerThirdOrderId));
        if (Objects.equals(VipCardOrderEnum.STATUS_END.getCode(),value)) {
            VipCard card = vipCardMapper.selectOne(Wrappers.<VipCard>lambdaQuery()
                .eq(VipCard::getCardId, vipCardOrder.getCardId()));
            if (card == null) {
                logger.error("更新用户会员到期时间失败,会员卡不存在,原始数据" + vipCardOrder);
                throw new CommonException("查询闪态订单状态出错:对应会员卡不存在");
            }
            VipEffectiveTimeVo vipEffectiveTimeVo = customerUserService.calculateExpiredDate(vipCardOrder.getUserId(), card.getValidDate(), null, null);
            customerUserService.updateVipEffectiveTime(vipCardOrder, vipEffectiveTimeVo);
        }
        return value;
    }
 
}