44323
2024-01-30 197431f6ce578d87a0156d2b8b13f1d327ba5e1e
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
package com.dsh.competition.service.impl;
 
import com.alibaba.nacos.common.utils.UuidUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeOrderSettleModel;
import com.alipay.api.domain.OpenApiRoyaltyDetailInfoPojo;
import com.alipay.api.domain.RoyaltyDetailInfos;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.request.AlipayTradeRoyaltyRelationBindRequest;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRoyaltyRelationBindResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsh.competition.entity.*;
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.Student;
import com.dsh.competition.feignclient.course.CoursePackagePaymentClient;
import com.dsh.competition.feignclient.course.model.PaymentDeductionClassHour;
import com.dsh.competition.feignclient.model.CompetitionUser;
import com.dsh.competition.feignclient.other.StoreClient;
import com.dsh.competition.feignclient.other.model.Store;
import com.dsh.competition.mapper.CompetitionMapper;
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.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jqs
 * @since 2023-06-26
 */
@Service
public class CompetitionServiceImpl extends ServiceImpl<CompetitionMapper, Competition> implements CompetitionService {
 
    @Resource
    private StoreClient storeClient;
 
    @Autowired
    private IPaymentCompetitionService paymentCompetitionService;
 
    @Autowired
    private UserCompetitionService userCompetitionService;
 
    @Autowired
    private IParticipantService participantService;
 
    @Resource
    private AppUserClient appUserClient;
 
    @Resource
    private StudentClient studentClient;
 
    @Resource
    private CoursePackagePaymentClient coursePackagePaymentClient;
 
    @Autowired
    private PayMoneyUtil payMoneyUtil;
 
 
    private String aliAppid = "2021004105665036";//支付宝appid
 
    private String appPrivateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCi5i9nW/hGLJ3A06cZxTQdviFC7THpdSihoTYGLr9q006hu0V26ecBMY/o4w5bvIX0Ok/yofmZsVcCJpAPvbXL/uqVrIjnRRxXiaeBFThlxoBUTdunvbUSDYfzlEhJr5NvUKI6H6lz2niXlQGx4qy8Hau4ccWit9kM8jwUvsBVQoFgJA+xrjMvooA7YLopQtpOD+UJr5thApTSf1xrnr1W12yolTLEH15JmNV372cqXrYUuqnY0QsaPtxeqJUGAOcGdVLllQ7easEznP8DFBvDdHATcmp2SHNQDUEWN6MCVPbMgY06NQVqAXxqjTAYSVh+6TRu6bofPmpYC3TZB003AgMBAAECggEBAJAcR2+PA3NBYUYHeFrqBRMS8uX8ZR19kjZ7IgoSLTFaQsP9opRylPSPXhrPVBKAE5leRQAHn4MCSlESwHvMfxo7KFjFTFAc6dffZZpipYQUOc9bGampwJh58/3e/pyBgVMG6J23CPf/HJQtNFSkjd/V9+ayb/9l2dUEL3bC0fAZ/dbx8HsxdLw8wn3fLlWLj68hOMqa2deCZe3JdSVsPbeWqkh56FFsMLug0Nd+Ar4TgRl9/jnhXF0JWiD0LmPUYLhboY7EfUBzN4w1iYbDi1P+3zvoOYsiVKAXox9GMhQ2VzOO2UcSTuizSza2e98mGpabl/GpKmCz+RDFjtkX6eECgYEA2MyCij65eO3aGIm3FUe93DULRBYTfX8qJQSJq2WOWA3mmQlEW6L3O2B5/lG2h+8WmN6iLEs9eHpgycGYp7vAqgrANEn16ACVcuyx0scFtrZfZ+kmHMzFfiUWxJjVYk/6YngsGVBLdw6ueM42C8TTP67X9tU5TdVGoGWuqEj4W98CgYEAwFqwprXOch5Pqk/RPbb49r0Ou03K/UbciWnWWKzUhFFNS8MdlQPoDvQZbMwHLeWsa2VhaKITK3x5biLQb3U+0GLOn6lTvEyrEUH+ucREyLgVYTRAvwBPtnvlrzpyxPk2HnslQjju8WrvvLLBMKWUjlTrTOzhaHT21gz3pHMiOakCgYEAhLmfaXdBITGshb054sNLDtdCkGpbgEcrzAHdLps769iGxkYQHXHFngpQZUwtTUcoNGqIKknd1jZFrv7gsD+XkgKG7PwimehRlkwmCX5ilxtLiVgJRzRt6+5U5AMVD90a0tHzXYP0z2yjj73fBJF5KtGl0a10KZxaYrQdm1UhB00CgYBZZgzx/k9rtHC8LAqIj1CYhHejT92G53c6Gkl3vyOqN4sgKhfGmSEySfrDGPRBPZxr8ZtbIPCd5mUdberH0osWGMYFaJI1UsCy7aQwvGpniz7MhZeN7dweaOjwDs8mgtjHQ96mL4XGCDhR0BZ/wIURvZ/6iaGdhbbu9unlsWj3uQKBgQCmZYdsbbZkd3ev6f8rwyvMz+DrCQyYpY44cegBYuJgrZiQnL2fJioeN7ixX0UM48SfwsZEIrzshP/LGAwnc2MdjxKUl4jLN8SEe0NAjXOnz9Zaw740+aOmLpXcLWdP4uM2gIhWsvW1tEkQZCXmm7c9s/RsU8Pmzv+YL3+fSijOzA==";//支付宝开发者应用私钥
 
    private String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAouYvZ1v4RiydwNOnGcU0Hb4hQu0x6XUooaE2Bi6/atNOobtFdunnATGP6OMOW7yF9DpP8qH5mbFXAiaQD721y/7qlayI50UcV4mngRU4ZcaAVE3bp721Eg2H85RISa+Tb1CiOh+pc9p4l5UBseKsvB2ruHHForfZDPI8FL7AVUKBYCQPsa4zL6KAO2C6KULaTg/lCa+bYQKU0n9ca569VtdsqJUyxB9eSZjVd+9nKl62FLqp2NELGj7cXqiVBgDnBnVS5ZUO3mrBM5z/AxQbw3RwE3JqdkhzUA1BFjejAlT2zIGNOjUFagF8ao0wGElYfuk0bum6Hz5qWAt02QdNNwIDAQAB";//支付宝应用公钥
 
    private String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmu8n/4yTHWbn7VOrNc9OsLtDL1bEQ8gC1dHkj8Wy5z0mkaOsjJRIG/28ze12M0V8jdCKuuDr5Z1OPKiqf+XO3ypguEh+mYUVMBM/cZodDFQfTY1TKLWjvQCuaqlA+QUTCK6f7T7stsgyQ1o9Jj0rXZDz6PM4QHSTzjrLIBaeqM5WIBvH+fy/X+QG5Utd+/UT0kc0JyvuKhZ65yVUd/C9VcwJJAPliRsAQNrqYterwAJ9zvw9tF11wj9W0XgJ8Ccu4x3gR1vrlLRJJo/OA97RmxPQ+5hSacWQZCUd1dwiBq+YCrKVHGTj14izRHXrLc0yBlRXo7tBOIqcy3IsvKVthQIDAQAB";//支付宝支付公钥
    private String smid = "2088330203191220";//平台支付宝商户号
 
    /**
     * 获取赛事列表
     *
     * @param content
     * @param registerCondition
     * @param heat
     * @return
     */
    @Override
    public List<CompetitionListVo> queryCompetitionList(String cityCode, String content, Integer registerCondition, String heat) throws Exception {
        List<CompetitionListVo> competitionListVos = this.baseMapper.queryCompetitionList(cityCode, content, registerCondition, heat);
 
        for (CompetitionListVo competitionListVo : competitionListVos) {
            Integer counts = this.baseMapper.counts(competitionListVo.getId());
            competitionListVo.setHeat(competitionListVo.getHeat() + counts);
        }
 
 
        return competitionListVos;
    }
 
 
    /**
     * 获取赛事详情
     *
     * @param uid
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public CompetitionInfo queryCompetitionInfo(Integer uid, Integer id, String lon, String lat) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Competition competition = this.getById(id);
        CompetitionInfo competitionInfo = new CompetitionInfo();
        competitionInfo.setId(competition.getId().longValue());
        competitionInfo.setImgs(competition.getImgs());
        competitionInfo.setName(competition.getName());
        competitionInfo.setRegisterCondition(competition.getRegisterCondition());
 
        // 2.0
        ArrayList<Map<String, Object>> objects = new ArrayList<>();
        if (null != competition.getStoreId()) {
            String storeId = competition.getStoreId();
            for (String s : storeId.split(",")) {
                HashMap<String, Object> map = new HashMap<>();
                Store store = storeClient.queryStoreById(Integer.valueOf(s));
                map.put("name", store.getName());
 
 
                String str = store.getAddress();
                str = str.substring(str.indexOf("省") + 1);
 
                // 去掉第一个“市”及之前的字符串
                str = str.substring(str.indexOf("市") + 1);
 
                // 去掉第一个“区”及之前的字符串
                str = str.substring(str.indexOf("区") + 1);
 
                map.put("address", str);
                map.put("storeLon", store.getLon());
                map.put("storeLat", store.getLat());
                map.put("storeCoverDrawing", store.getCoverDrawing());
                if (ToolUtil.isNotEmpty(lon) && ToolUtil.isNotEmpty(lat)) {
                    Map<String, Double> distance = GeodesyUtil.getDistance(lon + "," + lat, store.getLon() + "," + store.getLat());
                    double wgs84 = new BigDecimal(distance.get("WGS84")).divide(new BigDecimal(1000)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                    map.put("distance", wgs84);
                }
                objects.add(map);
            }
 
        }
        competitionInfo.setStoreInfos(objects);
 
 
        competitionInfo.setRegisterEndTime(sdf.format(competition.getRegisterEndTime()));
        competitionInfo.setStartTime(sdf.format(competition.getStartTime()));
        competitionInfo.setIsReal(competition.getRealName());
        competitionInfo.setEndTime(sdf.format(competition.getEndTime()));
        competitionInfo.setAge(competition.getStartAge() + "-" + competition.getEndAge());
        competitionInfo.setProvince(competition.getProvince());
        competitionInfo.setCity(competition.getCity());
        String str = competition.getAddress();
        str = str.substring(str.indexOf("省") + 1);
 
        // 去掉第一个“市”及之前的字符串
        str = str.substring(str.indexOf("市") + 1);
 
        // 去掉第一个“区”及之前的字符串
        str = str.substring(str.indexOf("区") + 1);
 
 
        competitionInfo.setAddress(str);
        competitionInfo.setCashPrice(competition.getCashPrice());
        competitionInfo.setPlayPaiCoin(competition.getPlayPaiCoin());
        competitionInfo.setClassPrice(competition.getClassPrice());
        competitionInfo.setIntroduction(competition.getIntroduction());
        competitionInfo.setRegistrationNotes(competition.getRegistrationNotes());
        competitionInfo.setApply(0);
        competitionInfo.setStatus(competition.getStatus());
        PaymentCompetition one = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>().eq("competitionId", id).eq("appUserId", uid).ne("payStatus", 1).orderByDesc("insertTime").last(" limit 1"));
        if (null != one) {
            competitionInfo.setApply(1);
            List<ParticipantVo> participant = new ArrayList<>();
            List<UserCompetition> list = userCompetitionService.list(new QueryWrapper<UserCompetition>().eq("paymentCompetitionId", one.getId()));
            List<Integer> collect = list.stream().map(UserCompetition::getParticipantId).collect(Collectors.toList());
            if (collect.size() == 0) {
                collect.add(-1);
            }
            List<Participant> participants = participantService.listByIds(collect);
            SimpleDateFormat sdf_year = new SimpleDateFormat("yyyy");
            for (Participant participant1 : participants) {
                ParticipantVo participantVo = new ParticipantVo();
                participantVo.setId(participant1.getId());
                participantVo.setName(participant1.getName());
                participantVo.setIdcard(participant1.getIdcard());
                Integer age = Integer.valueOf(sdf_year.format(new Date())) - Integer.valueOf(sdf_year.format(participant1.getBirthday()));
                participantVo.setAge(age);
                participant.add(participantVo);
            }
            competitionInfo.setParticipant(participant);
            if (one.getPayStatus() == 3) {
                competitionInfo.setStatus(4);
            }
        }
        return competitionInfo;
    }
 
 
    /**
     * 赛事报名
     *
     * @param uid
     * @param paymentCompetitionVo
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil paymentCompetition(Integer uid, PaymentCompetitionVo paymentCompetitionVo) throws Exception {
        AppUser appUser = appUserClient.queryAppUser(uid);
        String[] split = paymentCompetitionVo.getIds().split(";");
        Competition competition = this.getById(paymentCompetitionVo.getId());
 
        List<PaymentCompetition> list = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>().eq("competitionId", paymentCompetitionVo.getId()).ne("payStatus", 3));
        List<Long> pays = new ArrayList<>();
        for (PaymentCompetition paymentCompetition : list) {
            pays.add(paymentCompetition.getId());
        }
 
        int competitionId = 0;
        if (!pays.isEmpty()) {
            competitionId = userCompetitionService.count(new QueryWrapper<UserCompetition>().in("paymentCompetitionId", pays));
        }
 
 
//        int competitionId = userCompetitionService.count(new QueryWrapper<UserCompetition>().eq("competitionId", paymentCompetitionVo.getId()));
        if ((competitionId + split.length) > competition.getApplicantsNumber()) {
            return ResultUtil.error("报名人数超过最大限制");
        }
        BigDecimal money = null;
        if (paymentCompetitionVo.getPayType() == 1 || paymentCompetitionVo.getPayType() == 2) {
            money = new BigDecimal(competition.getCashPrice()).multiply(new BigDecimal(split.length)).setScale(2, RoundingMode.HALF_EVEN);
        }
        if (paymentCompetitionVo.getPayType() == 3) {//玩湃币
            money = new BigDecimal(competition.getPlayPaiCoin()).multiply(new BigDecimal(split.length)).setScale(2, RoundingMode.HALF_EVEN);
            if (money.compareTo(new BigDecimal(appUser.getPlayPaiCoins())) > 0) {
                return new ResultUtil(2, "报名失败,玩湃币不足,请充值");
            }
        }
        if (paymentCompetitionVo.getPayType() == 4) {//课程
            money = new BigDecimal(competition.getClassPrice()).multiply(new BigDecimal(split.length)).setScale(2, RoundingMode.HALF_EVEN);
            for (String s : split) {
//                Participant participant = participantService.getById(s);
//                Student student = studentClient.queryStudentByPhone(participant.getPhone());
//                if(null == student){
//                    return ResultUtil.error(participant.getName() + "不是学员,无法使用课时支付。");
//                }
                // 2.0
                Integer integer = coursePackagePaymentClient.queryResidueClassHourById(paymentCompetitionVo.getCoursePaymentId());
                if (new BigDecimal(integer).compareTo(new BigDecimal(competition.getClassPrice())) < 0) {
                    return new ResultUtil(3, "剩余课时不足,无法完成支付。");
 
                }
            }
        }
 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        PaymentCompetition paymentCompetition = new PaymentCompetition();
        String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
        paymentCompetition.setCode(code);
        paymentCompetition.setCompetitionId(paymentCompetitionVo.getId());
        paymentCompetition.setAppUserId(uid);
        paymentCompetition.setPayType(paymentCompetitionVo.getPayType());
        paymentCompetition.setAmount(money.doubleValue());
        paymentCompetition.setPayStatus(1);
        paymentCompetition.setState(1);
        paymentCompetition.setInsertTime(new Date());
        paymentCompetitionService.save(paymentCompetition);
 
        for (String s : split) {
            UserCompetition userCompetition = new UserCompetition();
            userCompetition.setAppUserId(uid);
            userCompetition.setCompetitionId(paymentCompetitionVo.getId());
            userCompetition.setParticipantId(Integer.valueOf(s));
            userCompetition.setPaymentCompetitionId(paymentCompetition.getId());
            userCompetition.setInsertTime(new Date());
            userCompetitionService.save(userCompetition);
        }
        if (paymentCompetitionVo.getPayType() == 1) {//微信
            return weChatPaymentCompetition(code, money);
        }
 
        if (paymentCompetitionVo.getPayType() == 2) {//支付宝
            // 判断当前赛事属于哪个运营商
            Competition byId = competitionService.getById(paymentCompetitionVo.getId());
            Integer operatorId = byId.getOperatorId();
            if (operatorId == null ){
                // 说明是平台
                return aliPaymentCompetition(smid,code, money);
            }
            // 获取该运营商的商户号
            String smid = storeClient.getSMIDByOperatorId(operatorId);
            return aliPaymentCompetition(smid,code, money);
        }
        if (paymentCompetitionVo.getPayType() == 3) {//玩湃币
            appUser.setPlayPaiCoins(appUser.getPlayPaiCoins() - money.intValue());
            appUserClient.updateAppUser(appUser);
 
            paymentCompetition = paymentCompetitionService.getById(paymentCompetition.getId());
            paymentCompetition.setAppUserId(null);
            paymentCompetition.setPayStatus(2);
            paymentCompetition.setPayTime(new Date());
            paymentCompetition.setPayOrderNo("");
            paymentCompetitionService.updateById(paymentCompetition);
 
//            competition.setApplicantsNumber(competition.getApplicantsNumber() + 1);
            this.updateById(competition);
        }
        if (paymentCompetitionVo.getPayType() == 4) {//课程
            for (String s : split) {
//                Participant participant = participantService.getById(s);
//                Student student = studentClient.queryStudentByPhone(participant.getPhone());
                PaymentDeductionClassHour paymentDeductionClassHour = new PaymentDeductionClassHour();
                paymentDeductionClassHour.setId(Integer.valueOf(s));
                paymentDeductionClassHour.setClassHour(competition.getClassPrice());
                paymentDeductionClassHour.setCode(code);
                paymentDeductionClassHour.setCourseId(paymentCompetitionVo.getCoursePaymentId());
                paymentDeductionClassHour.setUid(uid);
                coursePackagePaymentClient.paymentDeductionClassHour(paymentDeductionClassHour);
            }
            paymentCompetition = paymentCompetitionService.getById(paymentCompetition.getId());
            paymentCompetition.setAppUserId(null);
            paymentCompetition.setPayStatus(2);
            paymentCompetition.setPayTime(new Date());
            paymentCompetition.setPayOrderNo("");
            paymentCompetitionService.updateById(paymentCompetition);
 
            competition.setBaseNumber(competition.getBaseNumber() + 1);
            this.updateById(competition);
        }
        return ResultUtil.success();
    }
 
 
    /**
     * 赛事微信支付
     *
     * @param code
     * @param money
     * @return
     * @throws Exception
     */
    public ResultUtil weChatPaymentCompetition(String code, BigDecimal money) throws Exception {
        ResultUtil weixinpay = payMoneyUtil.weixinpay("报名赛事", "", code, money.toString(), "/base/competition/weChatPaymentCompetitionCallback", "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);
                            PaymentCompetition paymentCompetition = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>().eq("code", code).eq("payType", 1));
                            if (paymentCompetition.getPayStatus() == 2) {
                                break;
                            }
                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(code, "");
                            if (resultUtil.getCode() == 200 && paymentCompetition.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) {
                                    paymentCompetition.setAppUserId(null);
                                    paymentCompetition.setState(3);
                                    userCompetitionService.remove(new QueryWrapper<UserCompetition>().eq("paymentCompetitionId", paymentCompetition.getId()));
                                    break;
                                }
                                if ("SUCCESS".equals(s)) {
                                    paymentCompetition.setAppUserId(null);
                                    paymentCompetition.setPayStatus(2);
                                    paymentCompetition.setPayTime(new Date());
                                    paymentCompetition.setPayOrderNo(transaction_id);
                                    paymentCompetitionService.updateById(paymentCompetition);
                                    break;
                                }
                                if ("USERPAYING".equals(s)) {
                                    num++;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return weixinpay;
    }
 
 
    /**
     * 赛事支付宝支付
     *
     * @param code
     * @param money
     * @return
     * @throws Exception
     */
    public ResultUtil aliPaymentCompetition(String smid,String code, BigDecimal money) throws Exception {
        ResultUtil alipay = payMoneyUtil.alipay
                (smid,"报名赛事", "", "", code, money.toString(), "/base/competition/aliPaymentCompetitionCallback");
        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);
                            PaymentCompetition paymentCompetition = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>().eq("code", code).eq("payType", 2));
                            if (paymentCompetition.getPayStatus() == 2) {
                                break;
                            }
                            AlipayTradeQueryResponse resultUtil = payMoneyUtil.queryALIOrder(code);
                            if (resultUtil.getCode().equals("10000") && paymentCompetition.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");
                                String tradeNo = resultUtil.getTradeNo();
                                String s = resultUtil.getTradeStatus();
 
                                if ("TRADE_CLOSED".equals(s) || "TRADE_FINISHED".equals(s) || num == 10) {
                                    paymentCompetition.setAppUserId(null);
                                    paymentCompetition.setState(3);
                                    userCompetitionService.remove(new QueryWrapper<UserCompetition>().eq("paymentCompetitionId", paymentCompetition.getId()));
 
                                    break;
                                }
                                if ("TRADE_SUCCESS".equals(s)) {
                                    paymentCompetition.setAppUserId(null);
                                    paymentCompetition.setPayStatus(2);
                                    paymentCompetition.setPayTime(new Date());
                                    paymentCompetition.setPayOrderNo(tradeNo);
                                    paymentCompetitionService.updateById(paymentCompetition);
                                    // 结算资金到商户账号
                                    payMoneyUtil.confirm(smid,code,tradeNo,money.toString());
                                    //分账
//                                    moneyOut(tradeNo, tradeNo,code);
                                    break;
                                }
                                if ("WAIT_BUYER_PAY".equals(s)) {
                                    num++;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return alipay;
    }
 
//    @Autowired
//private IPaymentCompetitionService paymentCompetitionService;
 
    @Autowired
    private CompetitionService competitionService;
 
    public void moneyOut(String outNum, String tradeNo,String code) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, appPrivateKey, "json", "UTF-8", alipay_public_key, "RSA2");
        AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
        AlipayTradeOrderSettleModel model = new AlipayTradeOrderSettleModel();
        model.setOutRequestNo(outNum);
        model.setTradeNo(tradeNo);
        List<RoyaltyDetailInfos> royaltyDetailInfos = new ArrayList<>();
 
 
        AlipayTradeRoyaltyRelationBindRequest request1 = new AlipayTradeRoyaltyRelationBindRequest();
 
 
        request1.setBizContent("{" +
                "  \"receiver_list\":[" +
                "    {" +
                "      \"type\":\"loginName\"," +
                "      \"account\":\"19522115070\"," +
                "      \"name\":\"罗易胜\"," +
                "      \"memo\":\"分账给测试商户\"," +
                "    }" +
                "  ]," +
                "  \"out_request_no\":\"" + tradeNo + "\"" +
                "}");
        AlipayTradeRoyaltyRelationBindResponse response = alipayClient.execute(request1);
        if (response.isSuccess()) {
            System.out.println("绑定调用成功");
        } else {
            System.out.println("调用失败");
        }
 
 
 
 
        PaymentCompetition code1 = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>().eq("code", code));
        Competition byId1 = competitionService.getById(code1.getCompetitionId());
 
        OperatorUser operatorUser = storeClient.queryByStoreId(byId1.getOperatorId());
 
 
 
 
        OpenApiRoyaltyDetailInfoPojo op = new OpenApiRoyaltyDetailInfoPojo();
        op.setTransOutType("loginName");
        op.setTransOut("happysports@weparklife.com");
        op.setTransInType("loginName");
//        op.setTransInType("userId");
        op.setTransIn("19522115070");
//        op.setTransIn(operatorUser.getAlipayNum());
//        op.setAmountPercentage(Long.valueOf(operatorUser.getAlipayProportion()));
        op.setAmountPercentage(100L);
 
        List<OpenApiRoyaltyDetailInfoPojo> ops = new ArrayList<>();
        ops.add(op);
        model.setRoyaltyParameters(ops);
 
        request.setBizModel(model);
 
 
        AlipayTradeOrderSettleResponse response1 = alipayClient.execute(request);
        if (response1.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
 
    /**
     * 定时任务修改赛事状态
     */
 
    @Override
    public void taskSetStatus() {
        this.baseMapper.taskSetStatusStart();
        this.baseMapper.taskSetStatusEnd();
 
        Date currentTime = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentTime);
        calendar.add(Calendar.MINUTE, -10);
        Date tenMinutesAgo = calendar.getTime();
        List<PaymentCompetition> payStatus = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>().eq("payStatus", 1).le("insertTime", tenMinutesAgo));
        List<Long> pays = new ArrayList<>();
        for (PaymentCompetition status : payStatus) {
            pays.add(status.getId());
        }
        if (!pays.isEmpty()) {
            this.baseMapper.deleteTenMinutes(pays);
        }
    }
 
    @Override
    public ResultUtil paymentCompetitionCourseList(Integer uid, Integer id) {
        Competition competition = this.baseMapper.selectById(id);
        // 获取门店id  找出符合这些门店的课包
        String storeId = competition.getStoreId();
 
        List<PayCourseRes> list = coursePackagePaymentClient.paymentCompetitionCourseList(uid + "_" + storeId);
        return ResultUtil.success(list);
    }
 
    @Override
    public void moneyOut() throws AlipayApiException {
        Date date = new Date();
        List<Competition> list = competitionService.list(new QueryWrapper<Competition>().lt("endTime",date).ne("isOut",1));
        List<Integer> coms = new ArrayList<>();
        for (Competition competition : list) {
            coms.add(competition.getId());
            competition.setIsOut(1);
        }
        List<PaymentCompetition> pays = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>().in("competitionId", coms));
        for (PaymentCompetition pay : pays) {
            moneyOut(pay.getPayOrderNo(),pay.getPayOrderNo(),pay.getCode());
        }
        competitionService.updateBatchById(list);
 
 
    }
}