nickchange
2023-11-17 a9564eae9f0169ca39329b2f14a8f13d13358a0a
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
package com.dsh.account.service.impl;
 
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsh.account.entity.RechargeRecords;
import com.dsh.account.entity.TAppUser;
import com.dsh.account.entity.VipPayment;
import com.dsh.account.enums.RechargeRecordEnum;
import com.dsh.account.feignclient.competition.DeductionCompetitionsClient;
import com.dsh.account.feignclient.competition.model.PaymentCompetition;
import com.dsh.account.feignclient.course.CoursePaymentClient;
import com.dsh.account.feignclient.course.model.CouponPaymentVo;
import com.dsh.account.feignclient.course.model.TCoursePackagePayment;
import com.dsh.account.feignclient.other.RechargeConfigClient;
import com.dsh.account.feignclient.other.SiteClient;
import com.dsh.account.feignclient.other.model.SiteBooking;
import com.dsh.account.mapper.RechargeRecordsMapper;
import com.dsh.account.mapper.TAppUserMapper;
import com.dsh.account.model.IncomeQuery;
import com.dsh.account.model.query.RechargeRecordsQuery;
import com.dsh.account.model.vo.RechargeRecordsVO;
import com.dsh.account.model.vo.userBenefitDetail.RechargeDetailsVo;
import com.dsh.account.model.vo.userBenefitDetail.RechargePayRequest;
import com.dsh.account.model.vo.userBenefitDetail.RechargesDetail;
import com.dsh.account.service.RechargeRecordsService;
import com.dsh.account.util.*;
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.util.StringUtils;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 充值记录 服务实现类
 * </p>
 *
 * @author jqs
 * @since 2023-07-07
 */
@Service
public class RechargeRecordsServiceImpl extends ServiceImpl<RechargeRecordsMapper, RechargeRecords> implements RechargeRecordsService {
 
    @Resource
    private RechargeRecordsMapper rereMapper;
 
 
    @Resource
    private TAppUserMapper tappMapper;
 
    @Autowired
    private CoursePaymentClient cpClient;
 
    @Autowired
    private DeductionCompetitionsClient deducClient;
 
    @Autowired
    private PayMoneyUtil payMoneyUtil;
 
    @Resource
    private SiteClient stClient;
 
 
    @Resource
    private RechargeConfigClient reconMapper;
    @Autowired
    private RechargeRecordsMapper rechargeRecordsMapper;
 
 
    @Override
    public List<RechargesDetail> getAppUserRechargeRecord(String yearMonth, Integer recordId, Integer appUserId,Integer pageNum,Integer pageSize) {
        List<RechargesDetail> details = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
 
        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();
        }
 
//            1.赛事报名
        List<PaymentCompetition> playPaiFGoldPayRecord = deducClient.getPlayPaiFGoldPayRecord(appUserId);
        if (playPaiFGoldPayRecord.size() > 0 ){
            for (PaymentCompetition competition : playPaiFGoldPayRecord) {
                RechargesDetail consumeDetail = new RechargesDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.EVENT_REGISTRATION.getMsg() );
                consumeDetail.setConsumeTime(simpleDateFormat.format(competition.getInsertTime()));
                consumeDetail.setConsumeAmount("-" + competition.getAmount());
                consumeDetail.setRecordId(2);
                details.add(consumeDetail);
            }
        }
//            2.课包购买
        List<CouponPaymentVo> appuserCourseList = cpClient.getAppuserCourseList(appUserId);
        if (appuserCourseList.size() > 0){
            for (CouponPaymentVo tCoursePackagePayment : appuserCourseList) {
                RechargesDetail consumeDetail = new RechargesDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.COURSE_PACKAGE_PURCHASE.getMsg() );
                consumeDetail.setConsumeTime(tCoursePackagePayment.getTime());
                consumeDetail.setConsumeAmount("-" + tCoursePackagePayment.getAmount());
                consumeDetail.setRecordId(2);
                details.add(consumeDetail);
            }
        }
//            3.场地预约
        List<SiteBooking> siteBookings = stClient.wanpaiGoldSiteBookingList(appUserId);
        if (siteBookings.size() > 0 ){
            for (SiteBooking booking : siteBookings) {
                RechargesDetail consumeDetail = new RechargesDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.VENUE_RESERVATION.getMsg());
                consumeDetail.setConsumeTime(simpleDateFormat.format(booking.getInsertTime()));
                consumeDetail.setConsumeAmount("-" + booking.getPayMoney());
                consumeDetail.setRecordId(2);
                details.add(consumeDetail);
            }
        }
        //    4.智慧球场
        List<Map<String,Object>> list = stClient.game(appUserId);
        if (list.size() > 0 ){
            for (Map<String,Object> booking : list) {
                RechargesDetail consumeDetail = new RechargesDetail();
                consumeDetail.setConsumeName("激战游戏");
                consumeDetail.setConsumeTime(simpleDateFormat.format(new Date(Long.valueOf(booking.get("time").toString()))));
                consumeDetail.setConsumeAmount("-"+String.valueOf(booking.get("money")));
                consumeDetail.setRecordId(2);
                details.add(consumeDetail);
            }
        }
 
 
       //  5.充值
        List<RechargeRecords> rechargeRecords = this.baseMapper.selectList(new QueryWrapper<RechargeRecords>()
                .eq("payStatus", 2)
                .eq("appUserId", appUserId)
                .between("insertTime", monthStart, monthEnd));
        if (rechargeRecords.size() > 0) {
            for (RechargeRecords rechargeRecord : rechargeRecords) {
                RechargesDetail consumeDetail = new RechargesDetail();
                consumeDetail.setConsumeName(RechargeRecordEnum.RECHARGE.getMsg() + ":¥" + rechargeRecord.getAmount());
                consumeDetail.setConsumeTime(simpleDateFormat.format(rechargeRecord.getInsertTime()));
                consumeDetail.setConsumeAmount("+" + rechargeRecord.getPlayPaiCoins());
                consumeDetail.setRecordId(1);
                details.add(consumeDetail);
            }
        }
        if (ToolUtil.isNotEmpty(recordId)){
            details = details.stream()
                    .filter(record -> record.getRecordId().equals(recordId))
                    .collect(Collectors.toList());
        }
        if (details.size() > 0 ){
            Collections.sort(details, new Comparator<RechargesDetail>() {
                @Override
                public int compare(RechargesDetail o1, RechargesDetail o2) {
                    try {
                        Date date1 = simpleDateFormat.parse(o1.getConsumeTime());
                        Date date2 = simpleDateFormat.parse(o2.getConsumeTime());
                        return date2.compareTo(date1); // 降序排序
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    return 0;
                }
            });
        }
        //当前第几页
        int pageNo = pageNum;
        //一页五条
        int size = pageSize;
 
 
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<RechargesDetail> filteredList = new ArrayList<>();
        for (RechargesDetail detail : details) {
            try {
                Date consumeTime = dateFormat.parse(detail.getConsumeTime());
                if (consumeTime.after(monthStart) && consumeTime.before(monthEnd)) {
                    String substring = detail.getConsumeTime().substring(5);
                    detail.setConsumeTime(substring);
                    filteredList.add(detail);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
 
 
 
        //分页
        filteredList = filteredList.stream().skip((pageNo - 1) * size).limit(size).
                collect(Collectors.toList());
 
        return filteredList;
    }
 
    @Override
    public ResultUtil rechargeCenPayment(Integer userIdFormRedis, RechargePayRequest request) {
        TAppUser tAppUser = tappMapper.selectById(userIdFormRedis);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
        RechargeRecords rechargeRecords = new RechargeRecords();
        rechargeRecords.setCode(code);
        rechargeRecords.setAppUserId(userIdFormRedis);
 
        List<Map<String, Object>> rechargeConfig = reconMapper.getRechargeConfig();
        BigDecimal amount = BigDecimal.ZERO;
        if (rechargeConfig.size() > 0){
            for (Map<String, Object> stringObjectMap : rechargeConfig) {
                double o = (double) stringObjectMap.get("money");
                if (BigDecimal.valueOf(o).compareTo(request.getAmount()) == 0) {
                    amount = BigDecimal.valueOf(o);
                    rechargeRecords.setAmount(BigDecimal.valueOf(o));
                    if (tAppUser.getIsVip() == 1) {
                        rechargeRecords.setPlayPaiCoins((Integer) stringObjectMap.get("MemberCoins"));
                    } else {
                        rechargeRecords.setPlayPaiCoins((Integer) stringObjectMap.get("usersCoins"));
                    }
                }
            }
        }
        rechargeRecords.setPayStatus(1);
        rechargeRecords.setState(1);
        rechargeRecords.setInsertTime(new Date());
        this.baseMapper.insert(rechargeRecords);
        try {
            switch (request.getPayType()){
                case 1:
                    return WeChatPayment(code,amount);
                case 2:
                    return AlipayPayment(code,amount);
                default:
                    break;
            }
        }catch (Exception e){
            ResultUtil.runErr();
        }
        return ResultUtil.success();
    }
 
 
 
    private ResultUtil AlipayPayment(String code,BigDecimal amount) {
        ResultUtil alipay = payMoneyUtil.alipay("玩湃币充值", "玩湃币充值", "", code, amount.toString(),
                "/base/recharge/alipayRechargeCallback");
        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);
 
                            RechargeRecords records = rereMapper.selectOne(new QueryWrapper<RechargeRecords>()
                                    .eq("code",code));
                            if(records.getPayStatus() == 2){
                                break;
                            }
                            AlipayTradeQueryResponse resultUtil = payMoneyUtil.queryALIOrder(code);
 
                            if(resultUtil.getCode().equals("10000")&& records.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 tradeStatus = resultUtil.getTradeStatus();
                                System.out.println("ssssss"+tradeStatus);
                                if("TRADE_CLOSED".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus) || num == 10){
                                    records.setState(3);
                                    rereMapper.deleteById(records.getId());
                                    break;
                                }
                                if("TRADE_SUCCESS".equals(tradeStatus)){
                                    records.setAppUserId(null);
                                    records.setPayStatus(2);
                                    records.setPayTime(new Date());
                                    records.setOrderNumber(tradeNo);
                                    rereMapper.updateById(records);
 
//                                    RechargeRecords rechargeRecords = rereMapper.selectOne(new QueryWrapper<RechargeRecords>()
//                                            .eq("code", code));
//                                    if (rechargeRecords.getPayStatus() == 2){
//                                        break;
//                                    }
//
//                                    TAppUser tAppUser = tappMapper.selectById(rechargeRecords.getAppUserId());
//                                    tAppUser.setPlayPaiCoins(null == tAppUser.getPlayPaiCoins()? rechargeRecords.getPlayPaiCoins(): tAppUser.getPlayPaiCoins() +rechargeRecords.getPlayPaiCoins() );
//                                    tappMapper.updateById(tAppUser);
 
 
                                    break;
                                }
                                if("WAIT_BUYER_PAY".equals(tradeStatus)){
                                    num++;
                                }
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return alipay;
    }
 
    private ResultUtil WeChatPayment(String code,BigDecimal amount) throws Exception {
        ResultUtil weixinpay = payMoneyUtil.weixinpay("玩湃币充值", "", code, amount.toString(),
                "/base/recharge/wechatRechargeCallback", "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);
                            RechargeRecords records = rereMapper.selectOne(new QueryWrapper<RechargeRecords>()
                                    .eq("code",code));
                            if(records.getPayStatus() == 2){
                                break;
                            }
                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(code, "");
                            if(resultUtil.getCode() == 200 && records.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){
                                    records.setState(3);
                                    rereMapper.deleteById(records.getId());
                                    break;
                                }
                                if("SUCCESS".equals(s)){
                                    records.setPayStatus(2);
                                    records.setOrderNumber(transaction_id);
                                    rereMapper.updateById(records);
                                    break;
                                }
                                if("USERPAYING".equals(s)){
                                    num++;
                                }
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return weixinpay;
 
    }
 
    @Override
    public ResultUtil addRechargeCallbackPay(String code, String orderNumber) {
        RechargeRecords rechargeRecords = this.baseMapper.selectOne(new QueryWrapper<RechargeRecords>()
                .eq("code", code));
        if (rechargeRecords.getPayStatus() == 2){
            return  ResultUtil.success();
        }
        rechargeRecords.setAppUserId(null);
        rechargeRecords.setPayStatus(2);
        rechargeRecords.setPayTime(new Date());
        rechargeRecords.setOrderNumber(orderNumber);
        this.baseMapper.updateById(rechargeRecords);
 
        TAppUser tAppUser = tappMapper.selectById(rechargeRecords.getAppUserId());
        tAppUser.setPlayPaiCoins(null == tAppUser.getPlayPaiCoins()? rechargeRecords.getPlayPaiCoins(): tAppUser.getPlayPaiCoins() +rechargeRecords.getPlayPaiCoins() );
        tappMapper.updateById(tAppUser);
        return null;
    }
 
    @Override
    public List<RechargeRecordsVO> rechargeList(RechargeRecordsQuery query) {
        String STime = null;
        String ETime = null;
        if (StringUtils.hasLength(query.getTime())) {
            STime = query.getTime().split(" - ")[0] + " 00:00:00";
            ETime = query.getTime().split(" - ")[1] + " 23:59:59";
        }
 
        return  rechargeRecordsMapper.rechargeList(query,STime,ETime);
 
    }
 
    @Override
    public List<VipPayment> listAll(IncomeQuery query) {
        String STime = null;
        String ETime = null;
        if (StringUtils.hasLength(query.getTime())) {
            STime = query.getTime().split(" - ")[0] + " 00:00:00";
            ETime = query.getTime().split(" - ")[1] + " 23:59:59";
        }
        return rechargeRecordsMapper.listAll(query,STime,ETime,query.getAmount(),query.getInsertType());
    }
    public static <T> List<T> pageList(List<T> list, int pageNum, int pageSize) {
        //计算总页数
        int page = list.size() % pageSize == 0 ? list.size() / pageSize : list.size() / pageSize + 1;
        //兼容性分页参数错误
        pageNum = pageNum <= 0 ? 1 : pageNum;
        pageNum = pageNum >= page ? page : pageNum;
        // 开始索引
        int begin = 0;
        // 结束索引
        int end = 0;
        if (pageNum != page) {
            begin = (pageNum - 1) * pageSize;
            end = begin + pageSize;
        } else {
            begin = (pageNum - 1) * pageSize;
            end = list.size();
        }
        return list.subList(begin, end);
    }
 
}