puzhibing
2023-12-08 eb754c93037250419eceee17bfb526551e85f173
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
package com.dsh.competition.controller;
 
 
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsh.competition.entity.Competition;
import com.dsh.competition.entity.Participant;
import com.dsh.competition.entity.PaymentCompetition;
import com.dsh.competition.entity.UserCompetition;
import com.dsh.competition.feignclient.account.AppUserClient;
import com.dsh.competition.feignclient.account.StudentClient;
import com.dsh.competition.feignclient.account.model.AppUser;
import com.dsh.competition.feignclient.account.model.TStudent;
import com.dsh.competition.feignclient.course.CoursePackagePaymentClient;
import com.dsh.competition.feignclient.course.model.PaymentDeductionClassHour;
import com.dsh.competition.feignclient.model.*;
import com.dsh.competition.feignclient.other.StoreClient;
import com.dsh.competition.model.*;
import com.dsh.competition.service.CompetitionService;
import com.dsh.competition.service.IParticipantService;
import com.dsh.competition.service.IPaymentCompetitionService;
import com.dsh.competition.service.UserCompetitionService;
import com.dsh.competition.util.PayMoneyUtil;
import com.dsh.competition.util.ResultUtil;
import com.dsh.competition.util.TokenUtil;
import com.dsh.competition.util.ToolUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
 
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletionService;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jqs
 * @since 2023-06-26
 */
@RestController
@RequestMapping("")
public class CompetitionController {
 
 
    @Autowired
    private CompetitionService cttService;
 
    @Autowired
    private UserCompetitionService ucttService;
 
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");
 
    @Autowired
    private TokenUtil tokenUtil;
 
    @Autowired
    private PayMoneyUtil payMoneyUtil;
 
    @Autowired
    private IPaymentCompetitionService paymentCompetitionService;
 
    @Autowired
    private IParticipantService participantService;
 
    @Autowired
    private AppUserClient appUserClient;
 
    /**
     * 根据门店ids 获取对应的赛事 根据赛事支付记录获取用户ids
     */
    @ResponseBody
    @PostMapping("/base/competition/getUserIds")
    public List<Integer> getUserIds(@RequestBody ListQuery query) {
        List<Competition> list = cttService.list(new QueryWrapper<Competition>());
        // 赛事id集合
        List<Integer> comIds = new ArrayList<>();
 
        for (Integer id : query.getIds()) {
            for (Competition competition : list) {
                if (competition.getStoreId().contains(id.toString())) {
                    comIds.add(competition.getId());
                }
            }
        }
        // 获取到赛事id集合 去重
        List<Integer> collect = comIds.stream().distinct().collect(Collectors.toList());
        // 根据赛事id 查询赛事支付记录 获取用户ids
        if (collect.size() == 0) {
            return new ArrayList<>();
        } else {
            List<Integer> userIds = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>()
                    .in("competitionId", collect)).stream()
                    .map(PaymentCompetition::getAppUserId).collect(Collectors.toList());
            return userIds;
        }
 
    }
 
    /**
     * 获取赛事报名记录
     */
    @ResponseBody
    @RequestMapping("/base/competition/listAllPayment")
    public List<PaymentCompetition> listAllPayment(@RequestBody CompetitionQuery query) {
        Integer operatorId1 = query.getOperatorId();
        if (operatorId1 != null) {
            // 赛事集合id
            List<Integer> operatorId = cttService.list(new QueryWrapper<Competition>()
                    .eq("operatorId", operatorId1)).stream().map(Competition::getId).collect(Collectors.toList());
            query.setUserIds(operatorId);
        }
        List<PaymentCompetition> paymentCompetitions = paymentCompetitionService.listAll(query);
        List<PaymentCompetition> result = new ArrayList<>();
        if (query.getOperatorId() != null) {
            for (PaymentCompetition paymentCompetition : paymentCompetitions) {
                Integer competitionId = paymentCompetition.getCompetitionId();
                Competition byId = cttService.getById(competitionId);
                if (byId != null) {
                    Integer operatorId = byId.getOperatorId();
                    if (operatorId != null) {
                        if (operatorId == query.getOperatorId()) {
                            result.add(paymentCompetition);
                        }
                    }
                }
            }
            return result;
        } else if (query.getStoreId() != null) {
            for (PaymentCompetition paymentCompetition : paymentCompetitions) {
                Integer competitionId = paymentCompetition.getCompetitionId();
                Competition byId = cttService.getById(competitionId);
                if (byId != null) {
                    String storeId = byId.getStoreId();
                    if (storeId.contains(query.getStoreId().toString())) {
                        result.add(paymentCompetition);
                    }
                }
            }
            return result;
        }
        return paymentCompetitions;
    }
 
    @ResponseBody
    @PostMapping("/base/competition/getPayedCompetitions")
    public BillingRequestVo getAllCompetitionPayRecord(@RequestBody BillingDataRequestVo requestVo) {
        BillingRequestVo billingRequestVo = new BillingRequestVo();
        List<BillingRequest> integers = new ArrayList<>();
        integers = paymentCompetitionService.queryDatas(requestVo.getAppUserId(), requestVo.getMonthStart(), requestVo.getMonthEnd());
        System.out.println(integers);
        if (integers.size() > 0) {
            billingRequestVo.setRequests(integers);
        }
        return billingRequestVo;
    }
 
    @ResponseBody
    @PostMapping("/base/competition/getCancelOrderOfUserPay")
    public BillingRequestVo getCancelOrderOfUserPayRecord(@RequestBody BillingDataRequestVo requestVo) {
        BillingRequestVo billingRequestVo = new BillingRequestVo();
        List<BillingRequest> integers = new ArrayList<>();
        integers = paymentCompetitionService.queryCancelDatas(requestVo.getAppUserId(), requestVo.getMonthStart(), requestVo.getMonthEnd());
        System.out.println(integers);
        if (integers.size() > 0) {
            billingRequestVo.setRequests(integers);
        }
        return billingRequestVo;
    }
 
 
    @PostMapping("/base/competition/getPlayPaiFGoldPayRecord")
    public List<PaymentCompetition> getPlayPaiFGoldPayRecord(@RequestBody Integer appUserId) {
        ArrayList<Integer> integers = new ArrayList<>();
//        integers.add(1);
//        integers.add(2);
        integers.add(3);
 
        ArrayList<Integer> pays = new ArrayList<>();
        pays.add(2);
        pays.add(3);
 
        return paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>()
                .in("payType", integers)
                .eq("appUserId", appUserId)
                .in("payStatus", pays));
    }
 
 
    @PostMapping("/base/competition/queryByCode")
    public Integer queryByCode(@RequestBody String code) {
 
        return paymentCompetitionService.queryByCode(code);
    }
 
 
    @PostMapping("/base/competition/getCompetitionsDetails")
    public List<PurchaseRecordVo> getStuSourseList(@RequestBody GetStuSourseList sourseList) {
 
        List<PurchaseRecordVo> recordVos = new ArrayList<>();
 
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(1);
        integers.add(2);
        List<PaymentCompetition> list = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>()
                .in("payType", integers)
                .eq("appUserId", sourseList.getAppUserId())
                .eq("state", 1));
        if (list.size() > 0) {
            List<Long> comIds = list.stream().map(PaymentCompetition::getId).collect(Collectors.toList());
            List<UserCompetition> userCompetitions = ucttService.list(new QueryWrapper<UserCompetition>()
                    .between("insertTime", sourseList.getStartTime(), sourseList.getEndTime())
                    .eq("appUserId", sourseList.getAppUserId())
                    .in("paymentCompetitionId", comIds));
            if (userCompetitions.size() > 0) {
                userCompetitions.forEach(coms -> {
                    PurchaseRecordVo recordVo = new PurchaseRecordVo();
                    recordVo.setPurchaseType("报名赛事");
                    recordVo.setPurchaseTime(dateFormat.format(coms.getInsertTime()));
                    PaymentCompetition paymentCompetition = paymentCompetitionService.getById(coms.getPaymentCompetitionId());
                    recordVo.setPurchaseAmount("-" + paymentCompetition.getAmount());
                    recordVos.add(recordVo);
                });
            }
        }
 
        return recordVos;
    }
 
 
    @PostMapping("/base/competition/getCompetitionsDetails1")
    public List<PurchaseRecordVo> getStuSourseList1(@RequestBody GetStuSourseList sourseList) {
 
        List<PurchaseRecordVo> recordVos = new ArrayList<>();
 
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(4);
        List<PaymentCompetition> list = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>()
                .in("payType", integers)
                .eq("appUserId", sourseList.getAppUserId())
                .eq("state", 1));
        if (list.size() > 0) {
            List<Long> comIds = list.stream().map(PaymentCompetition::getId).collect(Collectors.toList());
            List<UserCompetition> userCompetitions = ucttService.list(new QueryWrapper<UserCompetition>()
                    .between("insertTime", sourseList.getStartTime(), sourseList.getEndTime())
                    .eq("appUserId", sourseList.getAppUserId())
                    .in("paymentCompetitionId", comIds));
            if (userCompetitions.size() > 0) {
                userCompetitions.forEach(coms -> {
                    PurchaseRecordVo recordVo = new PurchaseRecordVo();
                    recordVo.setPurchaseType("报名赛事");
                    recordVo.setPurchaseTime(dateFormat.format(coms.getInsertTime()));
                    PaymentCompetition paymentCompetition = paymentCompetitionService.getById(coms.getPaymentCompetitionId());
                    recordVo.setPurchaseAmount("-" + paymentCompetition.getAmount());
                    recordVos.add(recordVo);
                });
            }
        }
 
        return recordVos;
    }
 
 
    @ResponseBody
    @PostMapping("/base/competition/queryCompetitionList")
    @ApiOperation(value = "获取赛事列表", tags = {"APP-赛事活动列表"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "城市code", name = "cityCode", dataType = "string", required = false),
            @ApiImplicitParam(value = "搜索内容", name = "content", dataType = "string", required = false),
            @ApiImplicitParam(value = "报名条件(1=全部用户,2=仅限年度会员参与,3=仅限学员参与)", name = "registerCondition", dataType = "int", required = false),
            @ApiImplicitParam(value = "排序(asc=正序,desc=倒序)", name = "heat", dataType = "String", required = false),
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....")
    })
    public ResultUtil<List<CompetitionListVo>> queryCompetitionList(String cityCode, String content, Integer registerCondition, String heat) {
        try {
            List<CompetitionListVo> competitionListVos = cttService.queryCompetitionList(cityCode, content, registerCondition, heat);
            List<CompetitionListVo> filteredList = competitionListVos.stream()
                    .filter(vo -> vo.getStatus() == 1 || vo.getStatus() == 2)
                    .collect(Collectors.toList());
 
            return ResultUtil.success(filteredList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    @ResponseBody
    @PostMapping("/base/competition/queryCompetitionInfo")
    @ApiOperation(value = "获取赛事详情", tags = {"APP-赛事活动列表"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛事id", name = "id", dataType = "int", required = true),
            @ApiImplicitParam(value = "经度", name = "lon", dataType = "string", required = false),
            @ApiImplicitParam(value = "纬度", name = "lat", dataType = "string", required = false),
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....")
    })
    public ResultUtil<CompetitionInfo> queryCompetitionInfo(Integer id, String lon, String lat) {
        try {
            Integer uid = tokenUtil.getUserIdFormRedis();
            if (null == uid) {
                return ResultUtil.tokenErr();
            }
            CompetitionInfo competitionInfo = cttService.queryCompetitionInfo(uid, id, lon, lat);
 
 
            String dateString = competitionInfo.getRegisterEndTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = sdf.parse(dateString);
            if (new Date().after(date)) {
                competitionInfo.setHasPass(1);
            } else {
                competitionInfo.setHasPass(0);
 
            }
 
 
            return ResultUtil.success(competitionInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    @Autowired
    private CompetitionService competitionService;
    @Resource
    private CoursePackagePaymentClient coursePackagePaymentClient;
 
 
    @ResponseBody
    @PostMapping("/api/competition/paymentCompetition")
    @ApiOperation(value = "赛事报名", tags = {"APP-赛事活动列表"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....")
 
    })
 
    public synchronized ResultUtil paymentCompetition(PaymentCompetitionVo paymentCompetitionVo) {
        try {
            Competition byId = competitionService.getById(paymentCompetitionVo.getId());
            Date date = byId.getEndTime();
            // Assuming you have a Date object
            // Check if the date is past the current time
            boolean isPast = date.after(new Date());
            if (!isPast) {
                return new ResultUtil(0, "已超过截至报名时间");
            }
            Integer uid = tokenUtil.getUserIdFormRedis();
            if (null == uid) {
                return ResultUtil.tokenErr();
            }
            if (byId.getRegisterCondition() == 3) {
                Integer counts = coursePackagePaymentClient.isHave(paymentCompetitionVo.getIds());
                if (counts == 0) {
                    return new ResultUtil(0, "当前赛事仅限已购课学员报名");
                }
            }
            if (byId.getRegisterCondition() == 2) {
                AppUser appUser = appUserClient.queryAppUser(uid);
                if (appUser.getIsVip() == 0) {
                    return new ResultUtil(0, "当前赛事仅限年度会员报名");
                } else {
                    Date vipEndTime = appUser.getVipEndTime();
                    Date currentTime = new Date(); // Current time
                    if (vipEndTime.before(currentTime)) {
                        return new ResultUtil(0, "您的年度会员已过期,请续费");
                    }
                }
            }
            return cttService.paymentCompetition(uid, paymentCompetitionVo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    @ResponseBody
    @PostMapping("/api/competition/paymentCompetitionCourseList")
    @ApiOperation(value = "赛事报名--支付可用课时列表", tags = {"APP-赛事活动列表"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9....."),
            @ApiImplicitParam(value = "赛事id", name = "id", dataType = "int", required = true),
    })
    public ResultUtil paymentCompetitionCourseList(Integer id) {
        try {
            Integer uid = tokenUtil.getUserIdFormRedis();
            if (null == uid) {
                return ResultUtil.tokenErr();
            }
            return cttService.paymentCompetitionCourseList(uid, id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    /**
     * 报名赛事微信支付回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/competition/weChatPaymentCompetitionCallback")
    public void weChatPaymentCompetitionCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.weixinpayCallback(request);
            if (null != map) {
                String code = map.get("out_trade_no");
                String transaction_id = map.get("transaction_id");
                String result = map.get("result");
 
                PaymentCompetition paymentCompetition = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>().eq("code", code).eq("payType", 1));
                if (paymentCompetition.getPayStatus() == 1) {
                    paymentCompetition.setAppUserId(null);
                    paymentCompetition.setPayStatus(2);
                    paymentCompetition.setPayTime(new Date());
                    paymentCompetition.setPayOrderNo(transaction_id);
                    paymentCompetitionService.updateById(paymentCompetition);
 
                    Competition competition = cttService.getById(paymentCompetition.getCompetitionId());
                    competition.setApplicantsNumber(competition.getApplicantsNumber() + 1);
                    cttService.updateById(competition);
                }
 
                PrintWriter out = response.getWriter();
                out.write(result);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    /**
     * 报名赛事支付宝支付回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/competition/aliPaymentCompetitionCallback")
    public void aliPaymentCompetitionCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.alipayCallback(request);
            if (null != map) {
                String code = map.get("out_trade_no");
                String trade_no = map.get("trade_no");
                PaymentCompetition paymentCompetition = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>().eq("code", code).eq("payType", 2));
                if (paymentCompetition.getPayStatus() == 1) {
                    paymentCompetition.setAppUserId(null);
                    paymentCompetition.setPayStatus(2);
                    paymentCompetition.setPayTime(new Date());
                    paymentCompetition.setPayOrderNo(trade_no);
                    paymentCompetitionService.updateById(paymentCompetition);
                    Competition competition = cttService.getById(paymentCompetition.getCompetitionId());
                    competition.setApplicantsNumber(competition.getApplicantsNumber() + 1);
                    cttService.updateById(competition);
                }
                PrintWriter out = response.getWriter();
                out.write("success");
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    @ResponseBody
    @PostMapping("/api/competition/queryMyCompetitionList")
    @ApiOperation(value = "获取已报名赛事列表", tags = {"APP-赛事活动列表"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "类型(0=全部,1=未开始,2=进行中,3=已结束,4=已取消)", name = "type", dataType = "int", required = true),
            @ApiImplicitParam(value = "页条数", name = "pageSize", dataType = "int", required = true),
            @ApiImplicitParam(value = "页码,首页1", name = "pageNo", dataType = "int", required = true),
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....")
    })
    public ResultUtil<List<CompetitionListVo>> queryMyCompetitionList(Integer type, Integer pageSize, Integer pageNo) {
        try {
            Integer uid = tokenUtil.getUserIdFormRedis();
            if (null == uid) {
                return ResultUtil.tokenErr();
            }
            List<CompetitionListVo> competitionListVos = paymentCompetitionService.queryMyCompetitionList(uid, type, pageSize, pageNo);
            return ResultUtil.success(competitionListVos);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    @ResponseBody
    @PostMapping("/api/competition/queryMyCompetitionInfo")
    @ApiOperation(value = "获取已报名赛事详情", tags = {"APP-赛事活动列表"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛事id", name = "id", dataType = "int", required = true),
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....")
    })
    public ResultUtil<CompetitionInfo> queryMyCompetitionInfo(Long id) {
        try {
            CompetitionInfo competitionInfo = paymentCompetitionService.queryMyCompetitionInfo(id);
            return ResultUtil.success(competitionInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    @ResponseBody
    @PostMapping("/api/competition/cancelMyCompetition")
    @ApiOperation(value = "取消报名的赛事", tags = {"APP-赛事活动列表"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛事id", name = "id", dataType = "int", required = true),
            @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....")
    })
    public ResultUtil cancelMyCompetition(Long id) {
        try {
            ResultUtil resultUtil = paymentCompetitionService.cancelMyCompetition(id);
            return resultUtil;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
 
    /**
     * 取消已报名赛事后微信回退金额回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/competition/weChatCancelPaymentCompetitionCallback")
    public void weChatCancelPaymentCompetitionCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.wxRefundCallback(request);
            if (null != map) {
                String code = map.get("out_refund_no");
                String refund_id = map.get("refund_id");
                String result = map.get("result");
                PaymentCompetition paymentCompetition = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>().eq("code", code).eq("payType", 1));
                if (paymentCompetition.getPayStatus() == 1) {
                    paymentCompetition.setPayStatus(3);
                    paymentCompetition.setRefundTime(new Date());
                    paymentCompetition.setRefundOrderNo(refund_id);
                    paymentCompetition.setAppUserId(null);
                    paymentCompetitionService.updateById(paymentCompetition);
 
                    Competition competition = cttService.getById(paymentCompetition.getCompetitionId());
                    competition.setApplicantsNumber(competition.getApplicantsNumber() - 1);
                    cttService.updateById(competition);
                }
                PrintWriter out = response.getWriter();
                out.write(result);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    @PostMapping("/base/competition/queryById")
    public Competition queryById(@RequestBody Integer id) {
        try {
            return cttService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    @PostMapping("/base/competition/list")
    public Page<Competition> list(@RequestBody ListQuery listQuery) {
        try {
            Page<Competition> competitionPage = new Page<>(listQuery.getOffset(), listQuery.getLimit());
            LambdaQueryWrapper<Competition> wrapper = new LambdaQueryWrapper<>();
            if (ToolUtil.isNotEmpty(listQuery.getProvinceCode())) {
                wrapper.eq(Competition::getProvinceCode, listQuery.getProvinceCode());
            }
            if (ToolUtil.isNotEmpty(listQuery.getCityCode())) {
                wrapper.eq(Competition::getProvinceCode, listQuery.getCityCode());
            }
            if (ToolUtil.isNotEmpty(listQuery.getEventName())) {
                wrapper.like(Competition::getName, listQuery.getEventName());
            }
            if (ToolUtil.isNotEmpty(listQuery.getTime())) {
                wrapper.lt(Competition::getStartTime, listQuery.getTime().split(" - ")[0] + " 00:00:00");
                wrapper.gt(Competition::getEndTime, listQuery.getTime().split(" - ")[1] + " 23:59:59");
            }
            if(ToolUtil.isNotEmpty(listQuery.getRegisterCondition())){
                wrapper.eq(Competition::getRegisterCondition,listQuery.getRegisterCondition());
            }
            // 平台查询审核通过的赛事
            if (listQuery.getObj()==1){
                wrapper.eq(Competition::getAuditStatus,2);
            }
            // 赛事审核
            if (listQuery.getObj()==-1){
                wrapper.ne(Competition::getAuditStatus,2);
            }
            wrapper.in(Competition::getStoreId,listQuery.getIds());
            wrapper.orderByDesc(Competition::getInsertTime);
            Page<Competition> page = cttService.page(competitionPage, wrapper);
            for (Competition record : page.getRecords()) {
                // 查询当前赛事有多少人报名了
                List<UserCompetition> competitionId = ucttService.list(new QueryWrapper<UserCompetition>()
                        .eq("competitionId", record.getId()));
                // 报名数量
                int temp = competitionId.size();
                String value = String.valueOf(temp);
                record.setCount(record.getApplicantsNumber() + "-" + value);
            }
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            return new Page<Competition>();
        }
    }
 
    @PostMapping("/base/competition/listAudit")
    public Page<Competition> listAudit(@RequestBody ListQuery listQuery) {
        try {
            Page<Competition> competitionPage = new Page<>(listQuery.getOffset(), listQuery.getLimit());
            LambdaQueryWrapper<Competition> wrapper = new LambdaQueryWrapper<>();
            if (ToolUtil.isNotEmpty(listQuery.getProvinceCode())) {
                wrapper.eq(Competition::getProvinceCode, listQuery.getProvinceCode());
            }
            if (ToolUtil.isNotEmpty(listQuery.getCityCode())) {
                wrapper.eq(Competition::getCityCode, listQuery.getCityCode());
            }
            if (ToolUtil.isNotEmpty(listQuery.getEventName())) {
                wrapper.like(Competition::getName, listQuery.getEventName());
            }
            if (ToolUtil.isNotEmpty(listQuery.getState())) {
                wrapper.eq(Competition::getAuditStatus, listQuery.getState());
            }
            if (ToolUtil.isNotEmpty(listQuery.getRegisterCondition())) {
                wrapper.eq(Competition::getRegisterCondition, listQuery.getRegisterCondition());
            }
            wrapper.in(Competition::getStoreId, listQuery.getIds());
            ArrayList<Integer> integers = new ArrayList<>();
            integers.add(1);
            integers.add(3);
            wrapper.in(Competition::getAuditStatus, integers);
            wrapper.orderByDesc(Competition::getInsertTime);
 
            Page<Competition> page = cttService.page(competitionPage, wrapper);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            return new Page<Competition>();
        }
    }
 
 
    @PostMapping("/base/competition/add")
    public void add(@RequestBody Competition competition) {
        try {
            if (competition.getStartTime().after(new Date())) {
                competition.setStatus(1);
            }
            if (competition.getStartTime().before(new Date())) {
                if (competition.getEndTime().after(new Date())) {
                    competition.setStatus(2);
                } else {
                    competition.setStatus(3);
                }
            }
            competition.setInsertTime(new Date());
            cttService.save(competition);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @PostMapping("/base/competition/update")
    public void update(@RequestBody Competition competition) {
        try {
            if (competition.getStartTime().after(new Date())) {
                competition.setStatus(1);
            }
            if (competition.getStartTime().before(new Date())) {
                if (competition.getEndTime().after(new Date())) {
                    competition.setStatus(2);
                } else {
                    competition.setStatus(3);
                }
            }
            cttService.updateById(competition);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Resource
    private StoreClient storeClient;
 
    @Autowired
    private UserCompetitionService userCompetitionService;
 
 
    @PostMapping("/base/competition/cancel")
    public void cancel(@RequestBody Integer id) {
        try {
            Competition byId = cttService.getById(id);
            byId.setStatus(4);
            cttService.updateById(byId);
            List<PaymentCompetition> list = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>().eq("competitionId", byId.getId()).eq("payStatus", 2));
            for (PaymentCompetition pay : list) {
                PaymentCompetition paymentCompetition = pay;
 
                String code = paymentCompetition.getCode();
                Double amount = paymentCompetition.getAmount();
                Competition competition = competitionService.getById(paymentCompetition.getCompetitionId());
 
 
                String payOrderNo = paymentCompetition.getPayOrderNo();
                if (paymentCompetition.getPayType() == 1) {//微信支付
                    Map<String, String> map = payMoneyUtil.wxRefund(payOrderNo, code, amount.toString(), amount.toString(), "/base/competition/weChatCancelPaymentCompetitionCallback");
                    String return_code = map.get("return_code");
                    if (!"SUCCESS".equals(return_code)) {
//                        return ResultUtil.error(map.get("return_msg"));
                        continue;
                    }
                    String refund_id = map.get("refund_id");
                    paymentCompetition.setRefundOrderNo(refund_id);
                    paymentCompetitionService.updateById(paymentCompetition);
 
                    storeClient.addBackRecord(paymentCompetition.getAmount() + "_" + paymentCompetition.getAppUserId());
 
 
                }
                if (paymentCompetition.getPayType() == 2) {//支付宝支付
                    Map<String, String> map = payMoneyUtil.aliRefund(payOrderNo, amount.toString());
                    String return_code = map.get("code");
                    if (!"10000".equals(return_code)) {
//                        return ResultUtil.error(map.get("msg"));
                        continue;
                    }
                    String refund_id = map.get("trade_no");
                    paymentCompetition.setRefundOrderNo(refund_id);
                    paymentCompetition.setRefundTime(new Date());
                    paymentCompetition.setPayStatus(3);
                    paymentCompetition.setAppUserId(null);
                    paymentCompetitionService.updateById(paymentCompetition);
 
//            competition.setApplicantsNumber(competition.getApplicantsNumber() - 1);
                    competitionService.updateById(competition);
                }
                if (paymentCompetition.getPayType() == 3) {//玩湃币支付
                    AppUser appUser = appUserClient.queryAppUser(paymentCompetition.getAppUserId());
                    appUser.setPlayPaiCoins(appUser.getPlayPaiCoins() + amount.intValue());
                    appUserClient.updateAppUser(appUser);
 
                    paymentCompetition.setRefundOrderNo("");
                    paymentCompetition.setRefundTime(new Date());
                    paymentCompetition.setPayStatus(3);
                    paymentCompetition.setAppUserId(null);
                    paymentCompetitionService.updateById(paymentCompetition);
 
//            competition.setApplicantsNumber(competition.getApplicantsNumber() - 1);
                    competitionService.updateById(competition);
                }
                if (paymentCompetition.getPayType() == 4) {//课程支付
                    List<UserCompetition> list1 = userCompetitionService.list(new QueryWrapper<UserCompetition>().eq("paymentCompetitionId", paymentCompetition.getId()));
                    for (UserCompetition userCompetition : list1) {
//                Participant participant = participantService.getById(userCompetition.getId());
//                Student student = studentClient.queryStudentByPhone(participant.getPhone());
                        PaymentDeductionClassHour paymentDeductionClassHour = new PaymentDeductionClassHour();
                        paymentDeductionClassHour.setId(userCompetition.getParticipantId());
                        paymentDeductionClassHour.setClassHour(competition.getClassPrice());
                        paymentDeductionClassHour.setCode(code);
                        coursePackagePaymentClient.rollbackPaymentDeductionClassHour(paymentDeductionClassHour);
                    }
 
                    paymentCompetition.setRefundOrderNo("");
                    paymentCompetition.setRefundTime(new Date());
                    paymentCompetition.setPayStatus(3);
                    paymentCompetition.setAppUserId(null);
                    paymentCompetitionService.updateById(paymentCompetition);
 
//            competition.setApplicantsNumber(competition.getApplicantsNumber() - 1);
                    competitionService.updateById(competition);
                }
 
 
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    @PostMapping("/base/competition/getPeopleFromId")
    public Page<CompetitionUser> getPeopleFromId(@RequestBody GetPeopleQuery getPeopleQuery) {
        try {
            Page<UserCompetition> participantPage = new Page<>(getPeopleQuery.getOffset(), getPeopleQuery.getLimit());
            Page<CompetitionUser> page = participantService.getPeopleFromId(participantPage, getPeopleQuery.getId(), getPeopleQuery.getState());
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    @Resource
    private StudentClient studentClient;
    @PostMapping("/base/competition/getPeopleFromId1")
    public List<CompetitionUser> getPeopleFromId1(@RequestBody GetPeopleQuery getPeopleQuery) {
        try {
            Page<UserCompetition> participantPage = new Page<>(getPeopleQuery.getOffset(), getPeopleQuery.getLimit());
            List<CompetitionUser> page = participantService.getPeopleFromId1(participantPage, getPeopleQuery.getId(), getPeopleQuery.getState());
 
            List<CompetitionUser> users = new ArrayList<>();
            List<UserCompetition> coms = userCompetitionService.list(new QueryWrapper<UserCompetition>().eq("competitionId", getPeopleQuery.getId()));
            for (UserCompetition com : coms) {
                int number = com.getParticipantId();
                String numberString = Integer.toString(number);
                int digitCount = numberString.length();
                if (digitCount!=9){
                    TStudent tStudent = studentClient.queryById(number);
                    CompetitionUser competitionUser = new CompetitionUser();
                    competitionUser.setName(tStudent.getName());
                    competitionUser.setPhone(tStudent.getPhone());
                    competitionUser.setSex(tStudent.getSex());
                    competitionUser.setIdCard(tStudent.getIdCard());
                    competitionUser.setState(tStudent.getState());
                    users.add(competitionUser);
                }
            }
            page.addAll(users);
 
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    @PostMapping("/base/competition/getPeoples")
    @ResponseBody
    public List<CompetitionUser> getPeoples(@RequestBody GetPeopleQuery getPeopleQuery) {
        List<CompetitionUser> list = participantService.getPeoples(
                getPeopleQuery.getId(), getPeopleQuery.getState());
        return list;
    }
 
 
    @PostMapping("/base/competition/queryFee")
    public Double queryFee(@RequestBody QueryDataFee queryDataFee) {
        HashMap<String, Object> map = new HashMap<>();
        String data = queryDataFee.getData();
        List<Integer> ids = queryDataFee.getIds();
        if (ids.size() == 0) {
            ids.add(-1);
        }else{
            List<Competition> list1 = competitionService.list(new QueryWrapper<Competition>().in("storeId", ids).eq("auditStatus", 2).eq("state", 1).ne("status", 4));
            ids = list1.stream().map(Competition::getId).collect(Collectors.toList());
            if (ids.size() == 0) {
                ids.add(-1);
            }
        }
 
        LambdaQueryWrapper<PaymentCompetition> vipPaymentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (ToolUtil.isNotEmpty(data)) {
            String stime = data.split(" - ")[0] + " 00:00:00";
            String etime = data.split(" - ")[1] + " 23:59:59";
            vipPaymentLambdaQueryWrapper.between(PaymentCompetition::getInsertTime, stime, etime);
        }
        vipPaymentLambdaQueryWrapper.in(PaymentCompetition::getCompetitionId, ids);
        vipPaymentLambdaQueryWrapper.eq(PaymentCompetition::getPayStatus, 2);
        ArrayList<Integer> objects = new ArrayList<>();
        objects.add(1);
        objects.add(2);
        vipPaymentLambdaQueryWrapper.in(PaymentCompetition::getPayType, objects);
        List<PaymentCompetition> list = paymentCompetitionService.list(vipPaymentLambdaQueryWrapper);
        double sum = list.stream().mapToDouble(PaymentCompetition::getAmount).sum();
        return sum;
    }
 
 
    @ResponseBody
    @PostMapping("/base/competition/actPt")
    public HashMap<String, Object> actPt(@RequestBody List<Integer> ids) {
        HashMap<String, Object> map = new HashMap<>();
        if (ids.size() == 0) {
            ids.add(-1);
        }
        ArrayList<Object> integers = new ArrayList<>();
        int year = DateUtil.year(new Date());
 
        for (int i = 0; i < 10; i++) {
            integers.add(year - i);
        }
        List<Object> collect = integers.stream().sorted().collect(Collectors.toList());
        // 年
        ArrayList<Integer> years = new ArrayList<>();
        ArrayList<Integer> yearsUser = new ArrayList<>();
        for (Object o : collect) {
            String s = o.toString();
            int count = cttService.count(new LambdaQueryWrapper<Competition>().like(Competition::getInsertTime, s));
            int count1 = ucttService.count(new LambdaQueryWrapper<UserCompetition>().in(UserCompetition::getAppUserId, ids).like(UserCompetition::getInsertTime, s));
            years.add(count);
            yearsUser.add(count1);
        }
        map.put("yearData", years);
        map.put("yearsUser", yearsUser);
        // 月
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        ArrayList<Integer> months = new ArrayList<>();
        ArrayList<Integer> monthsUser = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            double sum = 0.0;
            String m = i + "";
            if (i < 10) {
                m = "0" + i;
            }
            String s = year + "-" + m;
            int count = cttService.count(new LambdaQueryWrapper<Competition>().like(Competition::getInsertTime, s));
            int count1 = ucttService.count(new LambdaQueryWrapper<UserCompetition>().in(UserCompetition::getAppUserId, ids).like(UserCompetition::getInsertTime, s));
            months.add(count);
            monthsUser.add(count1);
        }
        map.put("monthData", months);
        map.put("monthsUser", monthsUser);
 
        return map;
 
 
    }
 
    @ResponseBody
    @PostMapping("/base/competition/actYys")
    public HashMap<String, Object> actYys(@RequestBody CompetionVO vo) {
        HashMap<String, Object> map = new HashMap<>();
        if (vo.getIds().size() == 0) {
            vo.getIds().add(-1);
        }
        ArrayList<Object> integers = new ArrayList<>();
        int year = DateUtil.year(new Date());
 
        for (int i = 0; i < 10; i++) {
            integers.add(year - i);
        }
        List<Object> collect = integers.stream().sorted().collect(Collectors.toList());
        // 年
        ArrayList<Integer> years = new ArrayList<>();
        ArrayList<Integer> yearsUser = new ArrayList<>();
        Integer operatorId = vo.getOperatorId();
        List<Integer> operatorId1 = cttService.list(new QueryWrapper<Competition>().eq("operatorId", operatorId))
                .stream().map(Competition::getId).collect(Collectors.toList());
        for (Object o : collect) {
            String s = o.toString();
            int count = cttService.count(new LambdaQueryWrapper<Competition>().like(Competition::getInsertTime, s).eq(Competition::getOperatorId, vo.getOperatorId()));
            int count1 = ucttService.count(new LambdaQueryWrapper<UserCompetition>().in(UserCompetition::getAppUserId, vo.getIds()).like(UserCompetition::getInsertTime, s));
            years.add(count);
            yearsUser.add(count1);
        }
        map.put("yearData", years);
        map.put("yearsUser", yearsUser);
        // 月
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        ArrayList<Integer> months = new ArrayList<>();
        ArrayList<Integer> monthsUser = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            double sum = 0.0;
            String m = i + "";
            if (i < 10) {
                m = "0" + i;
            }
            String s = year + "-" + m;
            int count = cttService.count(new LambdaQueryWrapper<Competition>().like(Competition::getInsertTime, s).eq(Competition::getOperatorId, operatorId));
            int count1 = ucttService.count(new LambdaQueryWrapper<UserCompetition>().in(UserCompetition::getAppUserId, vo.getIds()).like(UserCompetition::getInsertTime, s));
            months.add(count);
            monthsUser.add(count1);
        }
        map.put("monthData", months);
        map.put("monthsUser", monthsUser);
 
        return map;
    }
 
 
    @ResponseBody
    @PostMapping("/base/competition/queryAppUserId")
    public List<Integer> queryAppUserId(@RequestBody List<Integer> storeIds){
        List<Competition> list = competitionService.list(new QueryWrapper<Competition>().in("storeId", storeIds).eq("auditStatus", 2).eq("state", 1));
        List<Integer> collect = list.stream().map(Competition::getId).collect(Collectors.toList());
        List<PaymentCompetition> list1 = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>().eq("payStatus", 2).eq("state", 1).in("competitionId", collect));
        return list1.stream().map(PaymentCompetition::getAppUserId).collect(Collectors.toList());
    }
}