44323
2023-09-26 7aa9607492e2c0b70838c53083f5362e49e74f44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
package com.dsh.account.service.impl;
 
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsh.account.dto.SelectDto;
import com.dsh.account.entity.*;
import com.dsh.account.enums.RechargeRecordEnum;
import com.dsh.account.feignclient.activity.IntroduceRewardsClient;
import com.dsh.account.feignclient.activity.MerChandiseClient;
import com.dsh.account.feignclient.activity.MerChandiseStoreClient;
import com.dsh.account.feignclient.activity.UserConponClient;
import com.dsh.account.feignclient.activity.model.*;
import com.dsh.account.feignclient.competition.DeductionCompetitionsClient;
import com.dsh.account.feignclient.competition.model.BillingDataRequestVo;
import com.dsh.account.feignclient.competition.model.PaymentCompetition;
import com.dsh.account.feignclient.competition.model.PurchaseRecordVo;
import com.dsh.account.feignclient.course.CoursePackageClient;
import com.dsh.account.feignclient.course.CoursePackageConfigClient;
import com.dsh.account.feignclient.course.CoursePaymentClient;
import com.dsh.account.feignclient.course.VideoOfCourseListClient;
import com.dsh.account.feignclient.course.model.*;
import com.dsh.account.feignclient.other.ImgConfigClient;
import com.dsh.account.feignclient.other.RechargeConfigClient;
import com.dsh.account.feignclient.other.SiteClient;
import com.dsh.account.feignclient.other.StoreClient;
import com.dsh.account.feignclient.other.model.SiteBooking;
import com.dsh.account.feignclient.other.model.Store;
import com.dsh.account.feignclient.other.model.StoreDetailOfCourse;
import com.dsh.account.feignclient.other.model.TImgConfig;
import com.dsh.account.mapper.*;
import com.dsh.account.model.*;
import com.dsh.account.model.dto.Coupon;
import com.dsh.account.model.query.appUserQuery.QueryAppUser;
import com.dsh.account.model.vo.DetailsListVo;
import com.dsh.account.model.vo.QueryAppUserVO;
import com.dsh.account.model.vo.classDetails.CourseVenue;
import com.dsh.account.model.vo.classDetails.ExerciseVideo;
import com.dsh.account.model.vo.classDetails.RegisteredCourse;
import com.dsh.account.model.vo.classDetails.classInsVo.ClassInfoVo;
import com.dsh.account.model.vo.userBenefitDetail.*;
import com.dsh.account.service.TAppGiftService;
import com.dsh.account.service.TAppUserService;
import com.dsh.account.util.*;
import com.dsh.account.util.akeylogin.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author administrator
 * @since 2023-06-14
 */
@Service
public class TAppUserServiceImpl extends ServiceImpl<TAppUserMapper, TAppUser> implements TAppUserService {
 
 
    @Resource
    private TStudentMapper tsmapper;
 
    @Resource
    private ImgConfigClient configClient;
 
    @Autowired
    private ALiSendSms aLiSendSms;
 
    @Autowired
    private RedisUtil redisUtil;
 
    @Autowired
    private GDMapGeocodingUtil gdMapGeocodingUtil;
 
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
 
    @Resource
    private CoursePaymentClient paymentClient;
 
    @Resource
    private StoreClient storeClient;
 
    @Resource
    private MerChandiseClient mcClient;
 
    @Resource
    private ImgConfigClient icfgClient;
 
 
    @Resource
    private VideoOfCourseListClient voclClient;
 
    @Resource
    private VipPaymentMapper vipPaymentMapper;
 
    @Resource
    private RechargeRecordsMapper rrMapper;
 
    @Resource
    private RechargeConfigClient reconMapper;
 
    @Resource
    private UserConponClient ucponClient;
 
    @Resource
    private CoursePackageClient cpageClient;
 
    @Resource
    private DeductionCompetitionsClient deducClient;
 
    @Resource
    private UserIntegralChangesMapper uicMapper;
 
    @Resource
    private MerChandiseStoreClient mcsClient;
 
    @Resource
    private CoursePackageConfigClient cpconClient;
 
    @Resource
    private PayMoneyUtil payMoneyUtil;
 
    @Resource
    private SiteClient stClient;
    @Autowired
    private TAppUserMapper appUserMapper;
 
    @Autowired
    private TAppGiftService appGiftService;
 
    @Autowired
    private IntroduceRewardsClient introduceRewardsClient;
    @Override
    public List<QueryAppUserVO> listAll(QueryAppUser query) {
       return appUserMapper.listAll(query);
    }
 
    @Override
    public HashMap<String,Object> weeksOfCourseDetailsList(Integer appUserId, Integer stuId, String time, Integer storeId,String lon,String lat) {
        // 门店id 查出所有课程
        HashMap<String, Object> map = paymentClient.weeksOfCourseDetailsList(new CourseDetailReq(appUserId, stuId, time, storeId,lon,lat));
 
        return map;
    }
 
 
    @Override
    public List<SelectDto> getSelects(List<Integer> studentIds) {
        return this.baseMapper.getSelects(studentIds);
    }
 
    @Override
    public Object changeState(AdvertisementChangeStateDTO dto) {
        return appUserMapper.changeState(dto.getIds(),dto.getState());
    }
 
    @Override
    public List<TAppUser> queryAPPUserByNameAndPhone(AppUserByNameAndPhoneDTO dto) {
        return appUserMapper.queryAPPUserByNameAndPhone(dto);
    }
 
    @Override
    public ClassInfoVo queryUserOfStus(Integer id) {
        TAppUser tAppUser = this.baseMapper.selectById(id);
        ClassInfoVo classInfoVo = new ClassInfoVo();
        if (ToolUtil.isNotEmpty(tAppUser)){
            List<TStudent> tStudents = tsmapper.selectList(new QueryWrapper<TStudent>()
                    .eq("appUserId",tAppUser.getId())
                    .eq("state",1)
                    .eq("isDefault",1));
            if (tStudents.size() > 0 ){
                TStudent tStudent = tStudents.get(0);
                classInfoVo.setStuId(tStudent.getId());
                classInfoVo.setIsThere(1);
                classInfoVo.setStuImg(tStudent.getHeadImg());
                classInfoVo.setStuSex(tStudent.getSex());
                classInfoVo.setStuAge(DateUtil.age(tStudent.getBirthday()));
                classInfoVo.setStuName(tStudent.getName());
                classInfoVo.setHeight(tStudent.getHeight());
                classInfoVo.setWeight(tStudent.getWeight());
                classInfoVo.setBmi(tStudent.getBmi());
                classInfoVo.setBodyStatus(BMIBodyUtil.getBodyStatus(tStudent.getBmi()));
 
                List<RegisteredCourse> courseList = new ArrayList<>();
                List<StuCourseResp> stuCoursePayment = paymentClient.getStuCoursePayment(tStudent.getId());
                List<Integer> coursePackIds = new ArrayList<>();
                if (stuCoursePayment.size() > 0){
                    coursePackIds = stuCoursePayment.stream().map(StuCourseResp::getCourseId).collect(Collectors.toList());
                    for (StuCourseResp tCoursePackagePayment : stuCoursePayment) {
                        RegisteredCourse course = new RegisteredCourse();
                        course.setId(tCoursePackagePayment.getId());
                        course.setCourseId(tCoursePackagePayment.getCourseId());
                        course.setCourseName(tCoursePackagePayment.getCourseName());
                        course.setTotalNums(ToolUtil.isEmpty(tCoursePackagePayment.getTotalCourseNums()) ? 0 : tCoursePackagePayment.getTotalCourseNums());
                        course.setDeductedNums(ToolUtil.isEmpty(tCoursePackagePayment.getDeductionNums()) ? 0 : tCoursePackagePayment.getDeductionNums());
                        course.setRemainingNums(ToolUtil.isEmpty(tCoursePackagePayment.getResidueNums())? 0 : tCoursePackagePayment.getResidueNums());
                        course.setPeriodOfValidity(tCoursePackagePayment.getPeriodOfValidity());
                        courseList.add(course);
                    }
 
                }
                classInfoVo.setCourseList(courseList);
                List<ExerciseVideo> stuCourseOfVideoList = voclClient.getStuCourseOfVideoList(coursePackIds);
                System.out.println(stuCourseOfVideoList);
                classInfoVo.setExerciseVideoList(stuCourseOfVideoList);
            }else {
                classInfoVo.setIsThere(2);
                List<TImgConfig> tImgConfigs = configClient.getNoneStuImgs();
                if (tImgConfigs.size() > 0){
                    classInfoVo.setImgs(tImgConfigs.get(0).getContent());
                }
            }
        }
        return classInfoVo;
    }
 
    /**
     * 处理数据
     * @param storeOfCourses
     * @param longitude
     * @param latitude
     * @return
     */
    public List<CourseVenue> dealDatas(List<CourseOfStoreVo> storeOfCourses, String longitude , String latitude){
        List<CourseVenue> courseVenues = new ArrayList<>();
        Map<Integer, List<CourseOfStoreVo>> map = storeOfCourses.stream().collect(Collectors.groupingBy(CourseOfStoreVo::getStoreId));
        for (Map.Entry<Integer, List<CourseOfStoreVo>> integerListEntry : map.entrySet()) {
            Integer storeId = integerListEntry.getKey();
            List<CourseOfStoreVo> value = integerListEntry.getValue();
            CourseVenue courseVenue = new CourseVenue();
            courseVenue.setStoreId(storeId);
            courseVenue.setAreaName(value.get(0).getCourseName());
            if (ToolUtil.isEmpty(longitude) && ToolUtil.isEmpty(latitude)){
                courseVenue.setSiteDistance(0+"");
            }else {
                courseVenue.setSiteDistance(LonlatUtils.distance(Double.parseDouble(longitude), Double.parseDouble(latitude),
                        Double.parseDouble(value.get(0).getLon()), Double.parseDouble(value.get(0).getLat())) + "");
            }
            List<CourseVenue.CouList> courses = new ArrayList<>();
            for (CourseOfStoreVo courseOfStoreVo : value) {
                CourseVenue.CouList couList = new CourseVenue.CouList();
                couList.setCourseID(courseOfStoreVo.getCourseId());
                couList.setCourseName(courseOfStoreVo.getCourseName());
                couList.setTimeStr(courseOfStoreVo.getClassStartTime() + "-" + courseOfStoreVo.getClassEndTime());
                couList.setDetail("¥" + courseOfStoreVo.getCoursePrice() + "/会员扣2学时");
                couList.setStatus(courseOfStoreVo.getStatus());
 
                couList.setAllNum(courseOfStoreVo.getAllNum());
                couList.setUseNum(courseOfStoreVo.getUseNum());
                couList.setLastNum(courseOfStoreVo.getLastNum());
                courses.add(couList);
            }
            courseVenue.setCourses(courses);
            courseVenues.add(courseVenue);
        }
        return courseVenues;
    }
 
 
    /**
     * 获取短信验证码
     * @param type 1:登录,2:注册,3:修改密码,4:忘记密码
     * @param phone
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil getSMSCode(Integer type, String phone) throws Exception {
        if(type == 2){
            TAppUser tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).ne("state", 3));
            if(null != tAppUser){
                return ResultUtil.error("账号已存在");
            }
        }
        String numberRandom = UUIDUtil.getNumberRandom(6);
        String templateCode = "";
        if(type == 1 || type == 2){
            templateCode = "SMS_161275250";
        }
        if(type == 3 || type == 4){
            templateCode = "SMS_160960014";
        }
        aLiSendSms.sendSms(phone, templateCode, "{\"code\":\"" + numberRandom + "\"}");
        redisUtil.setStrValue(phone, numberRandom, 300);
        return ResultUtil.success();
    }
 
 
    /**
     * 注册用户
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil addAppUser(AddAppUserVo addAppUserVo) throws Exception {
        TAppUser tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", addAppUserVo.getPhone()).ne("state", 3));
        if(null != tAppUser){
            return ResultUtil.error("账号已存在");
        }
        String value = redisUtil.getValue(addAppUserVo.getPhone());
        if(!"123456".equals(addAppUserVo.getCode()) && (ToolUtil.isEmpty(value) || !value.equals(addAppUserVo.getCode()))){
            return ResultUtil.error("验证码无效");
        }
 
        tAppUser = new TAppUser();
        tAppUser.setCode(UUIDUtil.getNumberRandom(16));
        tAppUser.setPhone(addAppUserVo.getPhone());
        tAppUser.setPassword(Md5Util.MD5Encode(addAppUserVo.getPassword(), null));
        tAppUser.setIsVip(0);
        tAppUser.setState(1);
        tAppUser.setInsertTime(new Date());
        this.baseMapper.insert(tAppUser);
 
 
        // 介绍有礼
        if(addAppUserVo.getReferralUserId()!=null){
            Map<String, String> geocode = gdMapGeocodingUtil.geocode(addAppUserVo.getLon(), addAppUserVo.getLat());
            Integer num=0;
            if(null != geocode){
                String province = geocode.get("province");
                String provinceCode = geocode.get("provinceCode");
                String city = geocode.get("city");
                String cityCode = geocode.get("cityCode");
                 num =  introduceRewardsClient.getGiftList(cityCode);
            }
            TAppGift one = appGiftService.getOne(new LambdaQueryWrapper<TAppGift>().eq(TAppGift::getUserId, addAppUserVo.getReferralUserId()));
            if(one!=null){
                one.setNum(one.getNum()+num);
                appGiftService.updateById(one);
            }else {
                TAppGift tAppGift = new TAppGift();
                tAppGift.setUserId(addAppUserVo.getReferralUserId());
                tAppGift.setNum(num);
                appGiftService.save(tAppGift);
            }
 
        }
 
        return ResultUtil.success();
    }
 
 
    /**
     * 账号密码登录
     * @param phone
     * @param password
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil loginPassword(String phone, String password) throws Exception {
        TAppUser tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).ne("state", 3));
        if(null == tAppUser){
            return ResultUtil.error("请先注册", "");
        }
        if(tAppUser.getState() == 2){
            return ResultUtil.error("您的账号已被冻结", "");
        }
//        password = Md5Util.MD5Encode(password, null);
        if(!tAppUser.getPassword().equals(password)){
            return ResultUtil.error("账号密码错误", "");
        }
        String token = getToken(tAppUser);
        return ResultUtil.success(token);
    }
 
 
    /**
     * 验证码登录
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil loginSMSCode(LoginSMSCodeVo loginSMSCodeVo) throws Exception {
        String value = redisUtil.getValue(loginSMSCodeVo.getPhone());
        if(!"123456".equals(loginSMSCodeVo.getCode()) && (ToolUtil.isEmpty(value) || !value.equals(loginSMSCodeVo.getCode()))){
            return ResultUtil.error("验证码无效", "");
        }
        TAppUser tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", loginSMSCodeVo.getPhone()).ne("state", 3));
        if(null == tAppUser){
            tAppUser = new TAppUser();
            tAppUser.setCode(UUIDUtil.getNumberRandom(16));
            tAppUser.setPhone(loginSMSCodeVo.getPhone());
            tAppUser.setPassword(Md5Util.MD5Encode("111111", null));
            tAppUser.setIsVip(0);
            tAppUser.setState(1);
            this.baseMapper.insert(tAppUser);
        }
        if(tAppUser.getState() == 2){
            return ResultUtil.error("您的账号已被冻结", "");
        }
        String token = getToken(tAppUser);
        return ResultUtil.success(token);
    }
 
 
    /**
     * 微信登录
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil loginWechat(LoginWeChatVo loginWechatVo) throws Exception {
        TAppUser tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("openid", loginWechatVo.getOpenId()).ne("state", 3));
        if(null == tAppUser){
            tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", loginWechatVo.getPhone()).ne("state", 3));
            if(null == tAppUser){
                tAppUser = new TAppUser();
                tAppUser.setCode(UUIDUtil.getNumberRandom(16));
                tAppUser.setOpenid(loginWechatVo.getOpenId());
                tAppUser.setPhone(loginWechatVo.getPhone());
                tAppUser.setPassword(Md5Util.MD5Encode("111111", null));
                tAppUser.setIsVip(0);
                tAppUser.setState(1);
                tAppUser.setInsertTime(new Date());
                this.baseMapper.insert(tAppUser);
            }
        }
        if(tAppUser.getState() == 2){
            return ResultUtil.error("您的账号已被冻结", "");
        }
 
        if(ToolUtil.isNotEmpty(tAppUser.getOpenid())){
            tAppUser.setOpenid(loginWechatVo.getOpenId());
        }
        if(ToolUtil.isNotEmpty(tAppUser.getPhone())){
            tAppUser.setPhone(loginWechatVo.getPhone());
        }
        this.updateById(tAppUser);
 
        String token = getToken(tAppUser);
        return ResultUtil.success(token);
    }
 
 
    /**
     * 获取JWT token和存储个人信息
     * @param appUser
     * @return
     */
    private String getToken(TAppUser appUser){
        String randomKey = jwtTokenUtil.getRandomKey();
        String token = jwtTokenUtil.generateToken(appUser.getId().toString(), randomKey);
        redisUtil.setStrValue(token.substring(token.length() - 32), String.valueOf(appUser.getId()), 7 * 24 * 60 * 60);
        redisUtil.setStrValue("USER_" + appUser.getPhone(), token.substring(token.length() - 32));
        redisUtil.setStrValue("USER_" + appUser.getId(), token);
        return token;
    }
 
 
    /**
     * 修改密码
     * @param phone
     * @param code
     * @param password
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil updatePassword(String phone, String code, String password) throws Exception {
        String value = redisUtil.getValue(phone);
        if(!"123456".equals(code) && (ToolUtil.isEmpty(value) || !value.equals(code))){
            return ResultUtil.error("验证码无效");
        }
        TAppUser tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).ne("state", 3));
        if(tAppUser.getState() == 2){
            return ResultUtil.error("您的账号已被冻结", "");
        }
        tAppUser.setPassword(Md5Util.MD5Encode(password, null));
        this.updateById(tAppUser);
        return ResultUtil.success();
    }
 
 
    /**
     * 定时任务修改到期会员的状态
     */
    @Override
    public void membershipEnd() {
        this.baseMapper.membershipEnd();
    }
 
 
    /**
     * 获取加入玩湃首页数据
     * @param lon
     * @param lat
     * @return
     * @throws Exception
     */
    @Override
    public JoinPlayPaiVo queryJoinPlayPai(Integer uid, String lon, String lat) throws Exception {
        TAppUser appUser = this.getById(uid);
        if(ToolUtil.isEmpty(appUser.getProvince()) && ToolUtil.isNotEmpty(lon)){
            Map<String, String> geocode = gdMapGeocodingUtil.geocode(lon, lat);
            if(null != geocode){
                String province = geocode.get("province");
                String provinceCode = geocode.get("provinceCode");
                String city = geocode.get("city");
                String cityCode = geocode.get("cityCode");
                appUser.setProvince(province);
                appUser.setProvinceCode(provinceCode);
                appUser.setCity(city);
                appUser.setCityCode(cityCode);
                this.updateById(appUser);
            }
        }
 
 
        JoinPlayPaiVo joinPlayPaiVo = new JoinPlayPaiVo();
        joinPlayPaiVo.setIsVip(appUser.getIsVip());
        if(ToolUtil.isEmpty(lon) ||ToolUtil.isEmpty(lat)){
            return joinPlayPaiVo;
        }
 
        Map<String, String> geocode = gdMapGeocodingUtil.geocode(lon, lat);
        if(null != geocode){
            String provinceCode = geocode.get("provinceCode");
            String cityCode = geocode.get("cityCode");
            List<Store> stores = storeClient.queryStoreList(new QueryStoreList(provinceCode, cityCode));
            Store s = null;
            Double d = 0D;
            for (Store store : stores) {
                Map<String, Double> distance = GeodesyUtil.getDistance(lon + "," + lat, store.getLon() + "," + store.getLat());
                Double wgs84 = distance.get("WGS84");
                if(s == null || d.compareTo(wgs84) < 0){
                    s = store;
                    d = wgs84;
                }
            }
            joinPlayPaiVo.setName(s.getName());
            joinPlayPaiVo.setLon(s.getLon());
            joinPlayPaiVo.setLat(s.getLat());
            joinPlayPaiVo.setStoreId(s.getId());
            joinPlayPaiVo.setPhone(s.getPhone());
        }
        return joinPlayPaiVo;
    }
 
    @Override
    public IndexOfUserBenefirVo queryBenefitDetails(Integer appUserId) {
        IndexOfUserBenefirVo benefirVo = new IndexOfUserBenefirVo();
 
        TAppUser appUser = this.getById(appUserId);
        benefirVo.setUserHeadImg(appUser.getHeadImg());
        benefirVo.setUserName(appUser.getName());
        benefirVo.setWpCoin(ToolUtil.isEmpty(appUser.getPlayPaiCoins()) ? 0 : appUser.getPlayPaiCoins());
        benefirVo.setUserIntegral(ToolUtil.isEmpty(appUser.getIntegral()) ? 0 : appUser.getIntegral());
        if (appUser.getIsVip() == 1){
            benefirVo.setIsMember("年度会员");
        }else {
            benefirVo.setIsMember("普通用户");
        }
        List<IntegralCommodity> convertibleGoods = mcClient.getConvertibleGoods();
        benefirVo.setCommodities(convertibleGoods);
        benefirVo.setImage(icfgClient.getImageConfig());
        return benefirVo;
    }
 
    @Override
    public List<ConsumeDetail>  queryUserBillingDetails(String yearMonth, Integer recordId, Integer appUserId) {
        List<ConsumeDetail> details = new ArrayList<>();
 
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm");
        SimpleDateFormat result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date monthStart = null;
        Date monthEnd = null;
        if (StringUtils.hasText(yearMonth)) {
            monthStart = DateTimeHelper.getCurrentIdetMouthStart(yearMonth);
            monthEnd = DateTimeHelper.getCurrentIdeaMouthEnd(yearMonth);
        } else {
            monthStart = DateTimeHelper.getCurrentMouthStart();
            monthEnd = DateTimeHelper.getCurrentMouthEnd();
        }
 
        BillingDataRequestVo requestVo = new BillingDataRequestVo();
        requestVo.setMonthStart(result.format(monthStart));
        requestVo.setMonthEnd(result.format(monthEnd));
        requestVo.setAppUserId(appUserId);
//            1.赛事报名
        BillingRequestVo allCompetitionPayRecord = deducClient.getAllCompetitionPayRecord(requestVo);
        if (ToolUtil.isNotEmpty(allCompetitionPayRecord.getRequests())){
            for (BillingRequest paymentCompetition : allCompetitionPayRecord.getRequests()) {
                ConsumeDetail consumeDetail = new ConsumeDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.EVENT_REGISTRATION.getMsg());
                consumeDetail.setConsumeTime(paymentCompetition.getTime());
                consumeDetail.setConsumeAmount("-" + paymentCompetition.getAmount());
                details.add(consumeDetail);
                consumeDetail.setType(1);
            }
        }
//            2.取消赛事报名
        BillingRequestVo cancelOrderOfUserPayRecord = deducClient.getCancelOrderOfUserPayRecord(requestVo);
        if (ToolUtil.isNotEmpty(cancelOrderOfUserPayRecord.getRequests())){
            for (BillingRequest paymentCompetition : cancelOrderOfUserPayRecord.getRequests()) {
                ConsumeDetail consumeDetail = new ConsumeDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.CANCEL_EVENT_REGISTRATION.getMsg());
                consumeDetail.setConsumeTime(paymentCompetition.getTime());
                consumeDetail.setConsumeAmount("+" + paymentCompetition.getAmount());
                consumeDetail.setType(1);
                details.add(consumeDetail);
            }
        }
//            3.课包购买
        BillingRequestVo amountPayRecord = paymentClient.getAmountPayRecord(requestVo);
        if (ToolUtil.isNotEmpty(amountPayRecord.getRequests())){
            for (BillingRequest coursePackagePayment : amountPayRecord.getRequests()) {
                ConsumeDetail consumeDetail = new ConsumeDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.COURSE_PACKAGE_PURCHASE.getMsg());
                consumeDetail.setConsumeTime(coursePackagePayment.getTime());
                consumeDetail.setConsumeAmount("-" + coursePackagePayment.getAmount());
                consumeDetail.setType(2);
                details.add(consumeDetail);
            }
        }
//            4.场地预约
        RequestOfTypeVo allSiteBookingList = stClient.getAllSiteBookingList(requestVo);
        if (ToolUtil.isNotEmpty(allSiteBookingList.getRequest())){
            for (BillingRequestOfType booking : allSiteBookingList.getRequest()) {
                ConsumeDetail consumeDetail = new ConsumeDetail();
                if (booking.getStatus() != 5){
                    consumeDetail.setConsumeName(RechargeRecordEnum.VENUE_RESERVATION.getMsg());
                    consumeDetail.setConsumeAmount("-" + booking.getAmount());
                    consumeDetail.setConsumeTime(booking.getTime());
                    consumeDetail.setType(2);
                }else {
                    consumeDetail.setConsumeName(RechargeRecordEnum.CANCEL_VENUE_RESERVATION.getMsg());
                    consumeDetail.setConsumeAmount("+" + booking.getAmount());
                    consumeDetail.setConsumeTime(booking.getTime());
                    consumeDetail.setType(1);
                }
                details.add(consumeDetail);
            }
        }
 
//            5.智慧球场
//            6.年度会员
        List<VipPayment> vipPayments = vipPaymentMapper.selectList(new QueryWrapper<VipPayment>()
                .eq("payStatus", 2)
                .eq("appUserId", appUserId)
                .between("insertTime", monthStart, monthEnd));
        if (vipPayments.size() > 0) {
            for (VipPayment vipPayment : vipPayments) {
                ConsumeDetail consumeDetail = new ConsumeDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.ANNUAL_MEMBERSHIP.getMsg());
                consumeDetail.setConsumeTime(simpleDateFormat.format(vipPayment.getInsertTime()));
                consumeDetail.setConsumeAmount("-" + vipPayment.getAmount());
                consumeDetail.setType(2);
                details.add(consumeDetail);
            }
        }
//            7.充值
        List<RechargeRecords> rechargeRecords = rrMapper.selectList(new QueryWrapper<RechargeRecords>()
                .eq("payStatus", 2)
                .eq("appUserId", appUserId)
                .between("insertTime", monthStart, monthEnd));
        if (rechargeRecords.size() > 0) {
            for (RechargeRecords rechargeRecord : rechargeRecords) {
                ConsumeDetail consumeDetail = new ConsumeDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.RECHARGE.getMsg() + ":" + rechargeRecord.getPlayPaiCoins());
                consumeDetail.setConsumeTime(simpleDateFormat.format(rechargeRecord.getInsertTime()));
                consumeDetail.setConsumeAmount("-" + rechargeRecord.getAmount());
                consumeDetail.setType(2);
                details.add(consumeDetail);
            }
        }
        if (details.size() > 0 ){
            Collections.sort(details, new Comparator<ConsumeDetail>() {
                @Override
                public int compare(ConsumeDetail record1, ConsumeDetail record2) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");
                    Date date1 = null;
                    Date date2 = null;
                    try {
                        date1 = dateFormat.parse(record1.getConsumeTime());
                        date2 = dateFormat.parse(record2.getConsumeTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    // 倒序排序
                    return date2.compareTo(date1);
                }
            });
 
            if (ToolUtil.isNotEmpty(recordId)){
                details = details.stream()
                        .filter(response -> Objects.equals(response.getType(), recordId))
                        .collect(Collectors.toList());
            }
        }
        return details;
    }
 
    @Override
    public void cancellation(Integer appUserId) {
        TAppUser tAppUser = this.baseMapper.selectById(appUserId);
        if (null != tAppUser){
            tAppUser.setState(3);
            this.baseMapper.updateById(tAppUser);
        }
    }
 
    @Override
    public List<RechargeCentVo> getSysRechargeConfig(Integer appUserId) {
        List<RechargeCentVo> centVos = new ArrayList<>();
        TAppUser tAppUser = this.baseMapper.selectById(appUserId);
        List<Map<String, Object>> rechargeConfig = reconMapper.getRechargeConfig();
        System.out.println(rechargeConfig);
        if (rechargeConfig.size() > 0 ){
            for (Map<String, Object> stringObjectMap : rechargeConfig) {
                RechargeCentVo vo = new RechargeCentVo();
                Double money = (Double) stringObjectMap.get("money");
                vo.setAmount(BigDecimal.valueOf(money) );
                if (tAppUser.getIsVip() == 1){
                    vo.setWpGold((Integer) stringObjectMap.get("MemberCoins"));
                }else {
                    vo.setWpGold((Integer) stringObjectMap.get("usersCoins"));
                }
                centVos.add(vo);
            }
        }
        return centVos;
    }
 
    @Override
    public List<Goods> queryAppUserIntegral(MallRequest request ) {
        List<Goods> goods = new ArrayList<>();
 
        CommodityRequest commodityRequest = new CommodityRequest();
        commodityRequest.setLon(request.getLon());
        commodityRequest.setLat(request.getLat());
        PointMerchandiseVo vicinityGoods = mcClient.getVicinityGoods(commodityRequest);
        if (ToolUtil.isNotEmpty(vicinityGoods.getMerchandises())) {
            for (PointsMerchandise vicinityGood : vicinityGoods.getMerchandises()) {
                Goods commodity = new Goods();
                switch (vicinityGood.getType()) {
                    case 1:
                        commodity.setGoodId(vicinityGood.getId());
                        commodity.setGoodName(vicinityGood.getName());
                        commodity.setGoodImg(vicinityGood.getCover());
                        commodity.setCondition(vicinityGood.getRedemptionMethod());
                        if (vicinityGood.getRedemptionMethod() == 1) {
                            commodity.setIntegral(vicinityGood.getIntegral().intValue());
                        } else {
                            commodity.setIntegral(vicinityGood.getIntegral().intValue());
                            commodity.setAmount(vicinityGood.getCash());
                        }
                        commodity.setBelongsType(vicinityGood.getUserPopulation());
                        commodity.setGoodsType(1);
                        commodity.setNums(mcClient.getRedeemedQuantity(vicinityGood.getId()));
                        List<Integer> integers = mcsClient.queryPointMerStoreIds(vicinityGood.getId());
                        commodity.setShopIds(integers);
                        break;
                    case 2:
                        commodity.setGoodId(vicinityGood.getCoursePackageId());
                        CoursePackage coursePackage = cpageClient.queryCoursePackageById(vicinityGood.getCoursePackageId());
                        commodity.setGoodImg(coursePackage.getCoverDrawing());
                        commodity.setGoodName(coursePackage.getName());
                        commodity.setCondition(vicinityGood.getRedemptionMethod());
                        if (vicinityGood.getRedemptionMethod() == 1) {
                            commodity.setIntegral(vicinityGood.getIntegral().intValue());
                        } else {
                            commodity.setIntegral(vicinityGood.getIntegral().intValue());
                            commodity.setAmount(vicinityGood.getCash());
                        }
                        commodity.setBelongsType(vicinityGood.getUserPopulation());
                        commodity.setGoodsType(2);
                        commodity.setNums(mcClient.getRedeemedQuantity(vicinityGood.getId()));
                        commodity.setShopIds(mcsClient.queryPointMerStoreIds(vicinityGood.getId()));
                        break;
                    case 3:
                        commodity.setGoodId(vicinityGood.getId());
                        commodity.setGoodName(vicinityGood.getName());
                        commodity.setGoodImg(vicinityGood.getCover());
                        commodity.setCondition(vicinityGood.getRedemptionMethod());
                        if (vicinityGood.getRedemptionMethod() == 1) {
                            commodity.setIntegral(vicinityGood.getIntegral().intValue());
                        } else {
                            commodity.setIntegral(vicinityGood.getIntegral().intValue());
                            commodity.setAmount(vicinityGood.getCash());
                        }
                        commodity.setBelongsType(vicinityGood.getUserPopulation());
                        commodity.setGoodsType(3);
                        commodity.setNums(mcClient.getRedeemedQuantity(vicinityGood.getId()));
                        commodity.setShopIds(mcsClient.queryPointMerStoreIds(vicinityGood.getId()));
                        break;
                    default:
 
                        break;
                }
                goods.add(commodity);
            }
        }
        List<Coupon> allCoupons = ucponClient.getAllCoupons(commodityRequest);
        if (allCoupons.size() > 0) {
            for (Coupon allCoupon : allCoupons) {
                Goods commodity = new Goods();
                commodity.setGoodId(allCoupon.getId());
                commodity.setGoodName(allCoupon.getName());
                commodity.setCondition(allCoupon.getRedemptionMethod());
                commodity.setGoodImg(allCoupon.getCover());
                if (allCoupon.getRedemptionMethod() == 1) {
                    commodity.setIntegral(allCoupon.getIntegral().intValue());
                } else {
                    commodity.setIntegral(allCoupon.getIntegral().intValue());
                    commodity.setAmount(allCoupon.getCash());
                }
                commodity.setBelongsType(allCoupon.getUserPopulation());
                commodity.setGoodsType(4);
                commodity.setShopIds(ucponClient.getCouponStoreIds(allCoupon.getId()));
                commodity.setNums(ucponClient.getRedeemedQuantity(allCoupon.getId()));
                goods.add(commodity);
            }
        }
 
        if (StringUtils.hasText(request.getSearch())){
            if (goods.size() > 0 ){
                goods = goods.stream()
                        .filter(merchandise -> merchandise.getGoodName().contains(request.getSearch()))
                        .collect(Collectors.toList());
            }
        }
        // 2.0 门店筛选
        if (request.getShopId()!=null){
            if (goods.size() > 0 ){
                goods = goods.stream()
                        .filter(merchandise -> merchandise.getShopIds().contains(request.getShopId()))
                        .collect(Collectors.toList());
            }
        }
 
        if (null != request.getRank()){
            switch (request.getRank()){
                case 1:
                    if (goods.size() > 0 ){
                        goods = goods.stream()
                                .sorted(Comparator.comparing(Goods::getIntegral).reversed())
                                .collect(Collectors.toList());
                    }
                    break;
                case 2:
                    if (goods.size() > 0 ){
                        goods = goods.stream()
                                .sorted(Comparator.comparing(Goods::getIntegral))
                                .collect(Collectors.toList());
                    }
                    break;
                case 3:
                    if (goods.size() > 0 ){
                        goods = goods.stream()
                                .sorted(Comparator.comparing(Goods::getNums).reversed())
                                .collect(Collectors.toList());
                    }
                    break;
                default:
                    break;
            }
 
        }
        if (null != request.getGoodsType()){
            if (goods.size() > 0 ){
                goods = goods.stream()
                        .filter(merchandise -> merchandise.getGoodsType().equals(request.getGoodsType()))
                        .collect(Collectors.toList());
            }
        }
 
        //当前第几页
        int pageNo = request.getPageNum();
        //一页五条
        int size = request.getPageSize();
 
        //分页
        goods = goods.stream().skip((pageNo - 1) * size).limit(size).
                collect(Collectors.toList());
        return goods;
    }
 
    // 对数据进行分页处理的方法
    private static Page<Goods> getPage(List<Goods> dataList, Pageable pageable) {
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), dataList.size());
        return new PageImpl<>(dataList.subList(start, end), pageable, dataList.size());
    }
 
    @Override
    public ProductDetailsVo productDetails(Integer goodId, Integer goodsType ) {
        ProductDetailRequest detailsVo = new ProductDetailRequest();
        detailsVo.setGoodsType(goodsType);
        detailsVo.setGoodId(goodId);
        return mcClient.getGoodDetailsWithId(detailsVo);
    }
 
    @Override
    public StuAndStoreResponse queryAppUserDefaultStuAndStore(Integer userIdFormRedis,Integer pointsMerId, String lat, String lon,Integer isCourse) {
        StuAndStoreResponse response = new StuAndStoreResponse();
        if (isCourse == 1){
            List<TStudent> tStudents = tsmapper.selectList(new QueryWrapper<TStudent>()
                    .eq("appUserId",userIdFormRedis)
                    .eq("state",1)
                    .eq("isDefault",1));
            if (tStudents.size() > 0 ){
                response.setStuId(tStudents.get(0).getId());
                response.setStuName(tStudents.get(0).getName());
                response.setStuPhone(tStudents.get(0).getPhone());
                response.setStuAge(DateUtil.age(tStudents.get(0).getBirthday()));
            }
            return response;
        }else {
            PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(pointsMerId);
            if (pointsMerchandise.getType() == 4){
                List<Integer> couponStoreIds = ucponClient.getCouponStoreIds(pointsMerId);
                StoreDetailOfCourse courseOfStore = storeClient.getCourseOfStore(couponStoreIds.get(0));
                if(ToolUtil.isNotEmpty(courseOfStore)){
                    response.setStoreId(couponStoreIds.get(0));
                    response.setStoreName(courseOfStore.getStoreName());
                }
            }else {
                List<Integer> integers = mcsClient.queryPointMerStoreIds(pointsMerId);
                StoreDetailOfCourse courseOfStore = storeClient.getCourseOfStore(integers.get(0));
                if(ToolUtil.isNotEmpty(courseOfStore)){
                    response.setStoreId(integers.get(0));
                    response.setStoreName(courseOfStore.getStoreName());
                }
            }
            return response;
        }
    }
 
    @Override
    @Transactional
    public ResultUtil productRedemptionOperation(Integer userIdFormRedis, GoodsExchangeVo exchangeType) {
        System.out.println("exchangeType:--->");
        System.out.println(exchangeType);
 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
        PointsMerchandise merchandise = mcClient.selectPointsMerchandiseById(exchangeType.getGoodId());
        if (ToolUtil.isEmpty(merchandise)){
            return ResultUtil.error("商品不存在");
        }
        TAppUser tAppUser = this.baseMapper.selectById(userIdFormRedis);
        if (ToolUtil.isEmpty(tAppUser)){
            return ResultUtil.error("用户不存在");
        }
        int goodsNums = 0;
        if (ToolUtil.isEmpty(exchangeType.getNums())){
            goodsNums = 1;
        }else {
            goodsNums = exchangeType.getNums();
        }
        AppUserGoodResp goodResp = new AppUserGoodResp();
        goodResp.setAppUserId(userIdFormRedis);
        goodResp.setGoodId(merchandise.getId());
        int count = mcClient.queryUserHasGoodsNums(goodResp);
        if (ToolUtil.isNotEmpty(count) && count >= merchandise.getPickUpQuantity()){
            return ResultUtil.error("超过限领数量");
        }
 
        for (int i = 0; i < goodsNums; i++) {
//            新增积分商品兑换记录
            UserPointsMerchandise pointsMerchandise = new UserPointsMerchandise();
            pointsMerchandise.setPointsMerchandiseId(exchangeType.getGoodId());
            pointsMerchandise.setUserId(userIdFormRedis);
            pointsMerchandise.setStatus(1);
            pointsMerchandise.setState(1);
            if (merchandise.getUseScope() == 3){
                if (exchangeType.getGoodsType() == 2){
                    CoursePackage coursePackage = cpageClient.queryCoursePackageById(merchandise.getCoursePackageId());
                    pointsMerchandise.setStoreId(coursePackage.getStoreId());
                }else {
                    pointsMerchandise.setStoreId(exchangeType.getStoreId());
                }
            }
            pointsMerchandise.setCode(code);
            mcClient.saveDetailsUserPointMercase(pointsMerchandise);
        }
 
        switch (exchangeType.getExchangeType()){
//            积分
            case 1:
                boolean b = dealAppUserIntegral(userIdFormRedis,tAppUser,merchandise.getIntegral());
                if (b){
                    switch (exchangeType.getGoodsType()){
                        case 2:
                            Integer stuNums = 0;
                            if (ToolUtil.isNotEmpty(exchangeType.getStuIds())){
                                stuNums = exchangeType.getStuIds().size();
                            }else {
                                stuNums = 1;
                            }
                            for (int i = 0; i < stuNums; i++) {
                                List<CoursePackagePaymentConfig> courseConfigList = cpconClient.getCourseConfigList(merchandise.getCoursePackageId());
                                TCoursePackagePayment packagePayment = new TCoursePackagePayment();
                                packagePayment.setAppUserId(userIdFormRedis);
                                packagePayment.setStudentId(exchangeType.getStuIds().get(i));
                                packagePayment.setCoursePackageId(merchandise.getCoursePackageId());
                                for (CoursePackagePaymentConfig coursePackagePaymentConfig : courseConfigList) {
                                    if (Objects.equals(coursePackagePaymentConfig.getId(), merchandise.getCoursePackageConfigId())) {
                                        packagePayment.setClassHours(coursePackagePaymentConfig.getClassHours());
                                        packagePayment.setTotalClassHours(coursePackagePaymentConfig.getClassHours());
                                        packagePayment.setLaveClassHours(coursePackagePaymentConfig.getClassHours());
                                        packagePayment.setOriginalPrice(coursePackagePaymentConfig.getCashPayment());
                                        break;
                                    }
                                }
                                packagePayment.setPlayPaiCoin(merchandise.getIntegral());
                                packagePayment.setAbsencesNumber(0);
                                packagePayment.setPayUserType(1);
                                packagePayment.setPayStatus(2);
                                packagePayment.setPayUserId(userIdFormRedis);
                                packagePayment.setStatus(1);
                                packagePayment.setState(1);
                                packagePayment.setCode(code);
                                paymentClient.savePaymentCoursePackage(packagePayment);
                            }
                            break;
                        case 4:
                            for (int i = 0; i < goodsNums; i++) {
                                UserCoupon coupon = new UserCoupon();
                                coupon.setCouponId(exchangeType.getGoodId());
                                coupon.setUserId(userIdFormRedis);
                                coupon.setStatus(1);
                                ucponClient.insertToAppuserCoupon(coupon);
                            }
                            break;
                        default:
                            break;
                    }
                }else {
                    return ResultUtil.error("用户积分不足!");
                }
                break;
            case 2:
//                积分+现金
                boolean dealt = dealAppUserIntegral(userIdFormRedis,tAppUser,merchandise.getIntegral());
                switch (exchangeType.getPayType()) {
                    case 1:
                        try {
                            if (merchandise.getType() == 2) {
                                return WechatPayment(merchandise.getCash().multiply(new BigDecimal(exchangeType.getStuIds().size())), code);
                            } else {
                                return WechatPayment(merchandise.getCash().multiply(new BigDecimal(goodsNums)), code);
                            }
                        } catch (Exception e) {
                            return ResultUtil.runErr();
                        }
                    case 2:
                        if (merchandise.getType() == 2) {
                            return AlipayPayment(merchandise.getCash().multiply(new BigDecimal(exchangeType.getStuIds().size())), code);
                        } else {
                            return AlipayPayment(merchandise.getCash().multiply(new BigDecimal(goodsNums)), code);
                        }
                    default:
                        break;
                }
                break;
            case 3:
                switch (exchangeType.getPayType()) {
                    case 1:
                        try {
                            if (merchandise.getType() == 2) {
                                return WechatPayment(merchandise.getCash().multiply(new BigDecimal(exchangeType.getStuIds().size())), code);
                            } else {
                                return WechatPayment(merchandise.getCash().multiply(new BigDecimal(goodsNums)), code);
                            }
                        } catch (Exception e) {
                            return ResultUtil.runErr();
                        }
                    case 2:
                        if (merchandise.getType() == 2) {
                            return AlipayPayment(merchandise.getCash().multiply(new BigDecimal(exchangeType.getStuIds().size())), code);
                        } else {
                            return AlipayPayment(merchandise.getCash().multiply(new BigDecimal(goodsNums)), code);
                        }
                    default:
                        break;
                }
                break;
            default:
                break;
        }
        return ResultUtil.success();
    }
 
    public boolean dealAppUserIntegral(Integer appUserId,TAppUser appUser,Integer points){
        try {
            if (ToolUtil.isEmpty(appUser.getIntegral()) || (ToolUtil.isNotEmpty(appUser.getIntegral()) && appUser.getIntegral() < points)){
                return false;
            }
            //        积分变更记录
            UserIntegralChanges userIntegralChanges = new UserIntegralChanges();
            userIntegralChanges.setAppUserId(appUserId);
            userIntegralChanges.setOldIntegral(appUser.getIntegral());
            userIntegralChanges.setType(2);
            appUser.setIntegral(null == appUser.getIntegral() ? points : appUser.getIntegral() - points);
            userIntegralChanges.setNewIntegral(appUser.getIntegral());
            userIntegralChanges.setInsertTime(new Date());
            userIntegralChanges.setCategory(2);
            uicMapper.insert(userIntegralChanges);
 
            this.baseMapper.updateById(appUser);
            return true;
        }catch (Exception e){
            return false;
        }
    }
 
    private ResultUtil AlipayPayment(BigDecimal cash, String code) {
        ResultUtil alipay = payMoneyUtil.alipay("课包续费", "", "", code, cash.toString(),
                "/base/pointMer/exchangeGoodPaymentAliCallback");
        if(alipay.getCode() == 200){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int num = 1;
                        int wait = 0;
                        while (num <= 10){
                            int min = 5000;
                            wait += (min * num);
                            Thread.sleep(wait);
                            List<UserPointsMerchandise> userPointsMerchandises = mcClient.queryUserPointMerchaseByCode(code);
                            if(userPointsMerchandises.get(0).getPayStatus() == 2){
                                break;
                            }
                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryALIOrder(code);
                            if(resultUtil.getCode() == 200 && userPointsMerchandises.get(0).getPayStatus() == 1){
                                /**
                                 * WAIT_BUYER_PAY(交易创建,等待买家付款)、
                                 * TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、
                                 * TRADE_SUCCESS(交易支付成功)、
                                 * TRADE_FINISHED(交易结束,不可退款)
                                 */
                                Map<String, String> data1 = resultUtil.getData();
                                String s = data1.get("tradeStatus");
                                String tradeNo = data1.get("tradeNo");
                                if("REFUND".equals(s) || "NOTPAY".equals(s) || "CLOSED".equals(s) || "REVOKED".equals(s) || "PAYERROR".equals(s) || num == 10){
                                    mcClient.deletePaymentRecord(code);
                                    break;
                                }
                                if("TRADE_SUCCESS".equals(s)){
                                    for (UserPointsMerchandise userPointsMerchandise : userPointsMerchandises) {
                                        userPointsMerchandise.setPayStatus(2);
                                        userPointsMerchandise.setOrderNumber(tradeNo);
                                        userPointsMerchandise.setPayType(2);
                                        mcClient.updateDetailsUserPointMercase(userPointsMerchandise);
                                    }
                                    break;
                                }
                                if("WAIT_BUYER_PAY".equals(s)){
                                    num++;
                                }
                            }
                        }
                    }catch (Exception e){
                        mcClient.deletePaymentRecord(code);
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return alipay;
    }
 
    private ResultUtil WechatPayment(BigDecimal cash, String code) throws Exception {
        ResultUtil weixinpay = payMoneyUtil.weixinpay("课包", "", code, cash.toString(),
                "/base/pointMer/exchangeGoodPaymentWeChatCallback", "APP", "");
        if(weixinpay.getCode() == 200){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int num = 1;
                        int wait = 0;
                        while (num <= 10){
                            int min = 5000;
                            wait += (min * num);
                            Thread.sleep(wait);
                            List<UserPointsMerchandise> userPointsMerchandises = mcClient.queryUserPointMerchaseByCode(code);
                            if(userPointsMerchandises.get(0).getPayStatus() == 2){
                                break;
                            }
                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(code, "");
                            if(resultUtil.getCode() == 200 && userPointsMerchandises.get(0).getPayStatus() == 1){
                                /**
                                 * SUCCESS—支付成功,
                                 * REFUND—转入退款,
                                 * NOTPAY—未支付,
                                 * CLOSED—已关闭,
                                 * REVOKED—已撤销(刷卡支付),
                                 * USERPAYING--用户支付中,
                                 * PAYERROR--支付失败(其他原因,如银行返回失败)
                                 */
                                Map<String, String> data1 = resultUtil.getData();
                                String s = data1.get("trade_state");
                                String transaction_id = data1.get("transaction_id");
                                if("REFUND".equals(s) || "NOTPAY".equals(s) || "CLOSED".equals(s) || "REVOKED".equals(s) || "PAYERROR".equals(s) || num == 10){
                                    mcClient.deletePaymentRecord(code);
                                    break;
                                }
                                if("SUCCESS".equals(s)){
                                    for (UserPointsMerchandise userPointsMerchandise : userPointsMerchandises) {
                                        userPointsMerchandise.setPayStatus(2);
                                        userPointsMerchandise.setOrderNumber(transaction_id);
                                        userPointsMerchandise.setPayType(1);
                                        mcClient.updateDetailsUserPointMercase(userPointsMerchandise);
                                    }
                                    break;
                                }
                                if("USERPAYING".equals(s)){
                                    num++;
                                }
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return weixinpay;
    }
 
    @Override
    public ResultUtil exchangeAddPaymentCallback(String code, String orderNumber,Integer payType) {
        List<UserPointsMerchandise> userPointsMerchandises = mcClient.queryUserPointMerchaseByCode(code);
        if (userPointsMerchandises.size() > 1){
            for (int i = 0; i < userPointsMerchandises.size(); i++) {
                userPointsMerchandises.get(i).setOrderNumber(orderNumber+ "-" + (i+1));
                userPointsMerchandises.get(i).setPayType(payType);
                userPointsMerchandises.get(i).setPayStatus(2);
                mcClient.updateDetailsUserPointMercase(userPointsMerchandises.get(i));
 
                Integer pointsMerchandiseId = userPointsMerchandises.get(i).getPointsMerchandiseId();
                PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(pointsMerchandiseId);
                switch (pointsMerchandise.getType()){
                    case 2:
                        List<TCoursePackagePayment> coursePackagePaymentOfCode = paymentClient.getCoursePackagePaymentOfCode(code);
                        for (TCoursePackagePayment coursePackagePayment : coursePackagePaymentOfCode) {
                            coursePackagePayment.setPayStatus(2);
                            coursePackagePayment.setPayType(payType);
                            coursePackagePayment.setOrderNumber(orderNumber);
                            coursePackagePayment.setCashPayment(pointsMerchandise.getCash());
                            paymentClient.updatePaymentCoursePackage(coursePackagePayment);
                        }
                        break;
                    case 4:
                        UserCoupon coupon = new UserCoupon();
                        coupon.setCouponId(userPointsMerchandises.get(0).getPointsMerchandiseId());
                        coupon.setUserId(userPointsMerchandises.get(0).getUserId());
                        coupon.setStatus(1);
                        ucponClient.insertToAppuserCoupon(coupon);
                        break;
                    default:
                        break;
                }
            }
        }else {
            userPointsMerchandises.get(0).setOrderNumber(orderNumber);
            userPointsMerchandises.get(0).setPayType(payType);
            userPointsMerchandises.get(0).setPayStatus(2);
            mcClient.updateDetailsUserPointMercase(userPointsMerchandises.get(0));
 
            Integer pointsMerchandiseId = userPointsMerchandises.get(0).getPointsMerchandiseId();
            PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(pointsMerchandiseId);
            switch (pointsMerchandise.getType()){
                case 2:
                    List<TCoursePackagePayment> coursePackagePaymentOfCode = paymentClient.getCoursePackagePaymentOfCode(code);
 
                    TCoursePackagePayment packagePayment =coursePackagePaymentOfCode.get(0);
                    packagePayment.setPayStatus(2);
                    packagePayment.setPayType(payType);
                    packagePayment.setOrderNumber(orderNumber);
                    packagePayment.setCashPayment(pointsMerchandise.getCash());
                    paymentClient.updatePaymentCoursePackage(packagePayment);
                    break;
                case 4:
                    UserCoupon coupon = new UserCoupon();
                    coupon.setCouponId(userPointsMerchandises.get(0).getPointsMerchandiseId());
                    coupon.setUserId(userPointsMerchandises.get(0).getUserId());
                    coupon.setStatus(1);
                    ucponClient.insertToAppuserCoupon(coupon);
                    break;
                default:
                    break;
            }
 
        }
        return ResultUtil.success();
    }
 
    @Override
    public List<StoreResponse> queryStoresOfExchange(Integer goodsType,Integer pointsMerId) {
        List<StoreResponse> responses = new ArrayList<>();
        if (goodsType == 4){
            List<Integer> couponStoreIds = ucponClient.getCouponStoreIds(pointsMerId);
            if (couponStoreIds.size() > 0 ){
                for (Integer couponStoreId : couponStoreIds) {
                    StoreDetailOfCourse courseOfStore = storeClient.getCourseOfStore(couponStoreId);
                    if(ToolUtil.isNotEmpty(courseOfStore)){
                        StoreResponse response = new StoreResponse();
                        response.setStoreId(couponStoreId);
                        response.setStoreName(courseOfStore.getStoreName());
                        responses.add(response);
                    }
                }
            }
 
        }else {
            List<Integer> integers = mcsClient.queryPointMerStoreIds(pointsMerId);
            if (integers.size() > 0 ){
                for (Integer integer : integers) {
                    StoreDetailOfCourse courseOfStore = storeClient.getCourseOfStore(integer);
                    if(ToolUtil.isNotEmpty(courseOfStore)){
                        StoreResponse response = new StoreResponse();
                        response.setStoreId(integer);
                        response.setStoreName(courseOfStore.getStoreName());
                        responses.add(response);
                    }
                }
            }
        }
        return responses;
    }
 
 
    @Override
    public List<CourseVenue> queryWeekOfCourseDetails(Integer appUserId ,Integer stuId, String time,String longitude,String latitude) {
        List<CourseVenue> courseVenues = new ArrayList<>();
        WeeksOfCourseRest weeksOfCourseRest = new WeeksOfCourseRest();
        weeksOfCourseRest.setTime(time);
        weeksOfCourseRest.setStuId(stuId);
        weeksOfCourseRest.setAppUserId(appUserId);
        List<CourseOfStoreVo> storeOfCourses = paymentClient.getStoreOfCourses(weeksOfCourseRest);
        System.out.println(storeOfCourses);
        if (storeOfCourses.size() > 0 ){
            courseVenues = dealDatas(storeOfCourses,longitude,latitude);
        }
        return courseVenues;
    }
 
 
 
 
}