无关风月
2024-09-24 61bbd595ee2bc3c67b40878894dcc07174c6eea6
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
package com.dsh.competition.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.Student;
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.BillingRequest;
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.mapper.PaymentCompetitionMapper;
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 org.springframework.util.StringUtils;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author zhibing.pu
 * @date 2023/7/6 16:37
 */
@Service
public class PaymentCompetitionServiceImpl extends ServiceImpl<PaymentCompetitionMapper, PaymentCompetition> implements IPaymentCompetitionService {
 
    @Autowired
    private CompetitionService competitionService;
 
    @Resource
    private StoreClient storeClient;
 
 
    @Autowired
    private UserCompetitionService userCompetitionService;
 
    @Autowired
    private IParticipantService participantService;
 
    @Autowired
    private PayMoneyUtil payMoneyUtil;
 
    @Resource
    private AppUserClient appUserClient;
 
    @Resource
    private CoursePackagePaymentClient coursePackagePaymentClient;
 
    @Resource
    private StudentClient studentClient;
 
    @Resource
    private PaymentCompetitionMapper paymentCompetitionMapper;
 
 
    @Resource
    private CompetitionMapper competitionMapper;
 
    /**
     * 获取我的报名赛事记录
     *
     * @param uid
     * @param type
     * @param pageSize
     * @param pageNo
     * @return
     * @throws Exception
     */
    @Override
    public List<CompetitionListVo> queryMyCompetitionList(Integer uid, Integer type, Integer pageSize, Integer pageNo) throws Exception {
        pageNo = (pageNo - 1) * pageSize;
        if (0 == type) {
            type = null;
        }
        List<CompetitionListVo> competitionListVos = this.baseMapper.queryMyCompetitionList(uid, type, pageSize, pageNo);
        for (CompetitionListVo competitionListVo : competitionListVos) {
            Integer counts = competitionMapper.counts(competitionListVo.getPId());
            competitionListVo.setHeat(competitionListVo.getHeat() + counts);
        }
        return competitionListVos;
    }
 
 
    /**
     * 获取我报名的赛事详情
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public CompetitionInfo queryMyCompetitionInfo(Long id) throws Exception {
        PaymentCompetition paymentCompetition = this.getById(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Competition competition = competitionService.getById(paymentCompetition.getCompetitionId());
        CompetitionInfo competitionInfo = new CompetitionInfo();
        competitionInfo.setId(id);
        competitionInfo.setImgs(competition.getImgs());
        competitionInfo.setName(competition.getName());
        competitionInfo.setRegisterCondition(competition.getRegisterCondition());
        Store store = storeClient.queryStoreById(Integer.valueOf(competition.getStoreId().split(",")[0]));
        competitionInfo.setStoreName(store.getName());
        competitionInfo.setStoreAddress(store.getAddress());
        competitionInfo.setStoreLon(store.getLon());
        competitionInfo.setStoreLat(store.getLat());
        competitionInfo.setStoreCoverDrawing(store.getCoverDrawing());
        competitionInfo.setRegisterEndTime(sdf.format(competition.getRegisterEndTime()));
        competitionInfo.setStartTime(sdf.format(competition.getStartTime()));
        competitionInfo.setEndTime(sdf.format(competition.getEndTime()));
        competitionInfo.setAge(competition.getStartAge() + "-" + competition.getEndAge());
        competitionInfo.setProvince(competition.getEntryProvince());
        competitionInfo.setCity(competition.getEntryCity());
 
        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(1);
        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 store1 = storeClient.queryStoreById(Integer.valueOf(s));
                map.put("name", store1.getName());
 
 
                String str1 = store1.getAddress();
                str1 = str1.substring(str1.indexOf("省") + 1);
 
                // 去掉第一个“市”及之前的字符串
                str1 = str1.substring(str1.indexOf("市") + 1);
 
                // 去掉第一个“区”及之前的字符串
                str1 = str1.substring(str1.indexOf("区") + 1);
 
                map.put("address", str1);
                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);
 
 
        List<ParticipantVo> participant = new ArrayList<>();
        List<UserCompetition> list = userCompetitionService.list(new QueryWrapper<UserCompetition>().eq("paymentCompetitionId", paymentCompetition.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);
            participantVo.setPhone(participant1.getPhone());
            participant.add(participantVo);
        }
 
 
        for (Integer i : collect) {
            TStudent tStudent = studentClient.queryById(i);
            if (tStudent != null) {
                ParticipantVo participantVo = new ParticipantVo();
                participantVo.setId(tStudent.getId());
                participantVo.setName(tStudent.getName());
                participantVo.setIdcard(tStudent.getIdCard());
                Integer age = Integer.valueOf(sdf_year.format(new Date())) - Integer.valueOf(sdf_year.format(tStudent.getBirthday()));
                participantVo.setAge(age);
                participantVo.setPhone(tStudent.getPhone());
                participant.add(participantVo);
            }
 
        }
 
        competitionInfo.setParticipant(participant);
        competitionInfo.setStatus(competition.getStatus());
        if (paymentCompetition.getPayStatus() == 3) {
            competitionInfo.setStatus(4);
        }
        competitionInfo.setPayMoney(paymentCompetition.getAmount());
        competitionInfo.setPayType(paymentCompetition.getPayType());
        return competitionInfo;
    }
 
 
    /**
     * 取消赛事报名
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil cancelMyCompetition(Long id) throws Exception {
        PaymentCompetition paymentCompetition = this.getById(id);
        if (paymentCompetition.getPayStatus() == 3) {
            return ResultUtil.error("不能重复取消");
        }
        String code = paymentCompetition.getCode();
        Double amount = paymentCompetition.getAmount();
        Competition competition = competitionService.getById(paymentCompetition.getCompetitionId());
        if (System.currentTimeMillis() >= competition.getRegisterEndTime().getTime()) {
            return ResultUtil.error("赛事已结束报名,无法取消");
        }
 
        String payOrderNo = paymentCompetition.getPayOrderNo();
        if (paymentCompetition.getPayType() == 1) {//微信支付
            if (StringUtils.hasLength(paymentCompetition.getFenzhangNo())){
                // 是分账订单 如果分账金额不为0 那么回退分账金额
                if (paymentCompetition.getFenzhangAmount()!=null && paymentCompetition.getFenzhangAmount().compareTo(BigDecimal.ZERO)>0){
                    String randomCode = UUIDUtil.getRandomCode(16);
                    String randomCode1 = UUIDUtil.getRandomCode(16);
                    if (competition.getOperatorId()!=null && competition.getOperatorId()!=0){
                        // 微信商户号
                        String s2 =storeClient.getmerchantNumberByOperatorId(competition.getOperatorId());
                        ResultUtil resultUtil = payMoneyUtil.fenzhangRefund(paymentCompetition.getFenzhangNo(), paymentCompetition.getFenzhangAmount(), s2, randomCode, randomCode1);
                        if (!resultUtil.getCode().equals(500)){
                            System.err.println("分账回退失败 原因是:"+resultUtil.getMsg());
                        }else{
                            paymentCompetition.setFenzhangRefundNo(resultUtil.getMsg());
                            paymentCompetitionMapper.updateById(paymentCompetition);
                        }
 
                    }
                }
            }
            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"));
            }
            String refund_id = map.get("refund_id");
            paymentCompetition.setRefundOrderNo(refund_id);
            paymentCompetition.setAppUserId(null);
            this.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"));
            }
            String refund_id = map.get("trade_no");
            paymentCompetition.setRefundOrderNo(refund_id);
            paymentCompetition.setRefundTime(new Date());
            paymentCompetition.setPayStatus(3);
            paymentCompetition.setAppUserId(null);
            this.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);
            this.updateById(paymentCompetition);
 
//            competition.setApplicantsNumber(competition.getApplicantsNumber() - 1);
            competitionService.updateById(competition);
        }
        if (paymentCompetition.getPayType() == 4) {//课程支付
            List<UserCompetition> list = userCompetitionService.list(new QueryWrapper<UserCompetition>().eq("paymentCompetitionId", paymentCompetition.getId()));
            for (UserCompetition userCompetition : list) {
//                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);
            this.updateById(paymentCompetition);
 
//            competition.setApplicantsNumber(competition.getApplicantsNumber() - 1);
            competitionService.updateById(competition);
        }
        return ResultUtil.success();
    }
 
    @Override
    public List<BillingRequest> queryDatas(Integer appUserId, String monthStart, String monthEnd) {
        return this.baseMapper.queryDatas(appUserId, monthStart, monthEnd);
    }
 
    @Override
    public List<BillingRequest> queryCancelDatas(Integer appUserId, String monthStart, String monthEnd) {
        return this.baseMapper.queryCancelDatas(appUserId, monthStart, monthEnd);
    }
 
    @Override
    public List<PaymentCompetition> listAll(CompetitionQuery 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 paymentCompetitionMapper.listAll(query, STime, ETime, query.getAmount());
    }
 
    @Override
    public Integer queryByCode(String code) {
        return this.baseMapper.queryBycode(code);
    }
}