puzhibing
2023-07-19 d85000e8f03740bd68523a36e108065a8168bd6a
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
package com.dsh.other.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsh.other.entity.*;
import com.dsh.other.feignclient.account.AppUserClient;
import com.dsh.other.feignclient.account.model.AppUser;
import com.dsh.other.feignclient.activity.CouponClient;
import com.dsh.other.feignclient.activity.UserCouponClient;
import com.dsh.other.feignclient.activity.model.Coupon;
import com.dsh.other.feignclient.activity.model.UserCoupon;
import com.dsh.other.mapper.SiteMapper;
import com.dsh.other.model.*;
import com.dsh.other.service.*;
import com.dsh.other.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.*;
 
/**
 * @author zhibing.pu
 * @date 2023/7/13 16:11
 */
@Service
public class SiteServiceImpl extends ServiceImpl<SiteMapper, Site> implements ISiteService {
 
    @Autowired
    private ISiteTypeService siteTypeService;
 
    @Autowired
    private StoreService storeService;
 
    @Autowired
    private ISiteBookingService siteBookingService;
 
    @Autowired
    private ISiteLockService siteLockService;
 
    @Resource
    private AppUserClient appUserClient;
 
    @Resource
    private UserCouponClient userCouponClient;
 
    @Resource
    private CouponClient couponClient;
 
    @Autowired
    private PayMoneyUtil payMoneyUtil;
 
 
 
 
 
    /**
     * 获取场地列表
     * @param querySiteList
     * @return
     * @throws Exception
     */
    @Override
    public List<QuerySiteListVo> querySiteList(QuerySiteList querySiteList) throws Exception {
        querySiteList.setPageNum((querySiteList.getPageNum() - 1) *querySiteList.getPageSize());
        List<QuerySiteListVo> querySiteListVos = this.baseMapper.querySiteList(querySiteList);
        for (QuerySiteListVo querySiteListVo : querySiteListVos) {
            if(ToolUtil.isEmpty(querySiteList.getLon())){
                querySiteListVo.setDistance(0D);
                continue;
            }
            Map<String, Double> distance = GeodesyUtil.getDistance(querySiteList.getLon() + "," + querySiteList.getLat(), querySiteListVo.getStoreLon() + "," + querySiteListVo.getStoreLat());
            querySiteListVo.setDistance(distance.get("WGS84"));
        }
        return querySiteListVos;
    }
 
 
    /**
     * 获取场地详情
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public QuerySiteInfoVo querySiteInfo(Integer id, String lon, String lat) throws Exception {
        Site site = this.getById(id);
        SiteType siteType = siteTypeService.getById(site.getSiteTypeId());
        Store store = storeService.getById(site.getStoreId());
        QuerySiteInfoVo querySiteInfoVo = new QuerySiteInfoVo();
        querySiteInfoVo.setId(site.getId());
        querySiteInfoVo.setName(site.getName());
        querySiteInfoVo.setSiteTypeName(siteType.getName());
        querySiteInfoVo.setStoreName(store.getName());
        querySiteInfoVo.setStoreCoverDrawing(store.getCoverDrawing());
        querySiteInfoVo.setStoreAddress(store.getAddress());
        querySiteInfoVo.setStoreLon(store.getLon());
        querySiteInfoVo.setStoreLat(store.getLat());
        querySiteInfoVo.setStorePhone(store.getPhone());
        querySiteInfoVo.setDistance(0D);
        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();
            querySiteInfoVo.setDistance(wgs84);
        }
        querySiteInfoVo.setCashPrice(site.getCashPrice());
        querySiteInfoVo.setPlayPaiCoin(site.getPlayPaiCoin());
        return querySiteInfoVo;
    }
 
 
    /**
     * 获取场地预约日期数据
     * @param id
     * @param day
     * @return
     * @throws Exception
     */
    @Override
    public List<QuerySiteTimes> querySiteTimes(Integer id, String day) throws Exception {
        Site site = this.getById(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar s = Calendar.getInstance();
        s.setTime(sdf.parse(day + " " + site.getAppointmentStartTime()));
        Calendar e = Calendar.getInstance();
        e.setTime(sdf.parse(day + " " + site.getAppointmentEndTime()));
 
        int hour = e.get(Calendar.HOUR_OF_DAY);
        int minute = e.get(Calendar.MINUTE);
        List<QuerySiteTimes> list = new ArrayList<>();
        while (true){
            int s_hour = s.get(Calendar.HOUR_OF_DAY);
            int s_minute = s.get(Calendar.MINUTE);
            String start = s_hour + ":" + s_minute;
 
            s.set(Calendar.MINUTE, s.get(Calendar.MINUTE) + 30);
            int e_hour = s.get(Calendar.HOUR_OF_DAY);
            int e_minute = s.get(Calendar.MINUTE);
            String end = e_hour + ":" + e_minute;
 
            QuerySiteTimes querySiteTimes = new QuerySiteTimes();
            querySiteTimes.setTime(start + "-" + end);
            querySiteTimes.setSelectable(1);
 
            SiteBooking siteBooking = siteBookingService.getOne(new QueryWrapper<SiteBooking>().eq("siteId", id).eq("state", 1)
                    .in("status", Arrays.asList(3, 4, 5)).last(" and DATE_FORMAT(startTime, '%Y-%m-%d %H:%i') <= '" + day + " " + start + "' and DATE_FORMAT(endTime, '%Y-%m-%d %H:%i') >= '" + day + " " + end + "'"));
            if(null != siteBooking){
                querySiteTimes.setSelectable(0);
            }
            int count = siteLockService.count(new QueryWrapper<SiteLock>().eq("siteId", id).last(" and DATE_FORMAT(startTime, '%Y-%m-%d %H:%i') <= '" + day + " " + start + "' and DATE_FORMAT(endTime, '%Y-%m-%d %H:%i') >= '" + day + " " + end + "'"));
            if(count > 0){
                querySiteTimes.setSelectable(0);
            }
 
            list.add(querySiteTimes);
 
            if(e_hour == hour && minute == e_minute){
                break;
            }
        }
        return list;
    }
 
 
    /**
     * 预约场地
     * @param reservationSite
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil reservationSite(Integer uid, ReservationSite reservationSite) throws Exception {
        Site site = this.getById(reservationSite.getId());
        AppUser appUser = appUserClient.queryAppUser(uid);
        String[] split = reservationSite.getTimes().split(";");
        if(reservationSite.getPayType() == 3){
            Integer playPaiCoin = site.getPlayPaiCoin() * split.length;
            if(appUser.getPlayPaiCoins().compareTo(playPaiCoin) < 0){
                return ResultUtil.error("玩湃币不足");
            }
        }
 
        for (String s : split) {
            String day = s.split(" ")[0];
            String time = s.split(" ")[1];
            List<QuerySiteTimes> querySiteTimes = querySiteTimes(reservationSite.getId(), day);
            for (QuerySiteTimes querySiteTime : querySiteTimes) {
                if(querySiteTime.getTime().equals(time) && querySiteTime.getSelectable() == 0){
                    return ResultUtil.error("【" + s + "】时间段已被使用");
                }
            }
        }
 
 
        String s_time = split[0];
        String e_time = split[split.length - 1];
        s_time = s_time.substring(s_time.lastIndexOf("-"));
        String[] s1 = e_time.split(" ");
        e_time = s1[0] + " " + s1[1].split("-")[1];
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Double payMoney = 0D;
        if(reservationSite.getPayType() == 3){
            payMoney = new BigDecimal(site.getCashPrice()).multiply(new BigDecimal(split.length)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        }else{
            payMoney = new BigDecimal(site.getCashPrice()).multiply(new BigDecimal(split.length)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        }
 
        //校验优惠券
        Long couponId = reservationSite.getCouponId();
        if(null != couponId && reservationSite.getPayType() != 3){
            UserCoupon userCoupon = userCouponClient.queryUserCouponById(couponId);
            if(userCoupon.getStatus() == 2){
                return ResultUtil.error("优惠券已被核销");
            }
            Coupon coupon = couponClient.queryCouponById(userCoupon.getCouponId());
            long time = coupon.getEndTime().getTime();
            if(System.currentTimeMillis() >= time){
                return ResultUtil.error("优惠券已过期");
            }
            if(coupon.getType() == 1){//满减
                JSONObject jsonObject = JSON.parseObject(coupon.getContent());
                Double num1 = jsonObject.getDouble("num1");
                Double num2 = jsonObject.getDouble("num2");
                if(payMoney.compareTo(num1) <= 0){
                    return ResultUtil.error("该优惠券无法使用");
                }
 
                payMoney = new BigDecimal(payMoney).subtract(new BigDecimal(num2)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            if(coupon.getType() == 2){//代金券
                JSONObject jsonObject = JSON.parseObject(coupon.getContent());
                Double num1 = jsonObject.getDouble("num1");
                if(payMoney.compareTo(num1) <= 0){
                    return ResultUtil.error("该优惠券无法使用");
                }
                payMoney = new BigDecimal(payMoney).subtract(new BigDecimal(num1)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            userCoupon.setStatus(2);
            userCouponClient.updateUserCoupon(userCoupon);
        }
 
 
        SiteBooking siteBooking = new SiteBooking();
        siteBooking.setOrderNo(sdf.format(new Date()) + UUIDUtil.getNumberRandom(3));
        siteBooking.setProvince(site.getProvince());
        siteBooking.setProvinceCode(site.getProvinceCode());
        siteBooking.setCity(site.getCity());
        siteBooking.setCityCode(site.getCityCode());
        siteBooking.setStoreId(site.getStoreId());
        siteBooking.setSiteId(reservationSite.getId());
        siteBooking.setAppUserId(uid);
        siteBooking.setStartTime(sdf1.parse(s_time));
        siteBooking.setEndTime(sdf1.parse(e_time));
        siteBooking.setBooker(reservationSite.getBooker());
        siteBooking.setPhone(reservationSite.getPhone());
        siteBooking.setPayType(reservationSite.getPayType());
        siteBooking.setPayMoney(payMoney);
        siteBooking.setUserCouponId(reservationSite.getCouponId());
        siteBooking.setStatus(0);
        siteBooking.setState(1);
        siteBooking.setInsertTime(new Date());
        siteBookingService.save(siteBooking);
 
        if(reservationSite.getPayType() == 1){//微信支付
            return weChatPaymentSite(uid, payMoney, siteBooking);
        }
        if(reservationSite.getPayType() == 2){//支付宝支付
            return aliPaymentSite(payMoney, siteBooking);
        }
        if(reservationSite.getPayType() == 3){//玩湃币支付
            return playPaiCoinPaymentSite(appUser, payMoney, siteBooking);
        }
        return ResultUtil.success();
    }
 
 
    /**
     * 课程微信支付
     * @param uid
     * @param paymentPrice
     * @return
     * @throws Exception
     */
    public ResultUtil weChatPaymentSite(Integer uid, Double paymentPrice, SiteBooking siteBooking) throws Exception{
        String code = siteBooking.getOrderNo();
        Integer id = siteBooking.getId();
        ResultUtil weixinpay = payMoneyUtil.weixinpay("预约场地", "", code, paymentPrice.toString(), "/base/site/weChatPaymentSiteCallback", "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);
                            SiteBooking siteBooking = siteBookingService.getById(id);
                            if(siteBooking.getStatus() != 0){
                                break;
                            }
                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(siteBooking.getOrderNo(), "");
                            if(resultUtil.getCode() == 200 && siteBooking.getStatus() == 0){
                                /**
                                 * 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){
                                    siteBooking.setState(3);
                                    siteBookingService.updateById(siteBooking);
                                    if(null != siteBooking.getUserCouponId()){
                                        UserCoupon userCoupon = userCouponClient.queryUserCouponById(siteBooking.getUserCouponId());
                                        userCoupon.setStatus(1);
                                        userCouponClient.updateUserCoupon(userCoupon);
                                    }
                                    break;
                                }
                                if("SUCCESS".equals(s)){
                                    siteBooking.setPayTime(new Date());
                                    siteBooking.setStatus(1);
                                    siteBooking.setPayOrderNo(transaction_id);
                                    siteBookingService.updateById(siteBooking);
                                    break;
                                }
                                if("USERPAYING".equals(s)){
                                    num++;
                                }
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return weixinpay;
    }
 
 
    /**
     * 课程支付宝支付
     * @param paymentPrice
     * @return
     * @throws Exception
     */
    public ResultUtil aliPaymentSite(Double paymentPrice, SiteBooking siteBooking) throws Exception{
        String code = siteBooking.getOrderNo();
        Integer id = siteBooking.getId();
        ResultUtil alipay = payMoneyUtil.alipay("预约场地", "预约场地", "", code, paymentPrice.toString(), "/base/site/aliPaymentSiteCallback");
        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);
                            SiteBooking siteBooking = siteBookingService.getById(id);
                            if(siteBooking.getStatus() != 0){
                                break;
                            }
                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryALIOrder(code);
                            if(resultUtil.getCode() == 200 && siteBooking.getStatus() == 0){
                                /**
                                 * WAIT_BUYER_PAY(交易创建,等待买家付款)、
                                 * TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、
                                 * TRADE_SUCCESS(交易支付成功)、
                                 * TRADE_FINISHED(交易结束,不可退款)
                                 */
                                Map<String, String> data1 = resultUtil.getData();
                                String s = data1.get("tradeStatus");
                                String tradeNo = data1.get("tradeNo");
                                if("TRADE_CLOSED".equals(s) || "TRADE_FINISHED".equals(s) || num == 10){
                                    siteBooking.setState(3);
                                    siteBookingService.updateById(siteBooking);
                                    if(null != siteBooking.getUserCouponId()){
                                        UserCoupon userCoupon = userCouponClient.queryUserCouponById(siteBooking.getUserCouponId());
                                        userCoupon.setStatus(1);
                                        userCouponClient.updateUserCoupon(userCoupon);
                                    }
                                    break;
                                }
                                if("TRADE_SUCCESS".equals(s)){
                                    siteBooking.setPayTime(new Date());
                                    siteBooking.setStatus(1);
                                    siteBooking.setPayOrderNo(tradeNo);
                                    siteBookingService.updateById(siteBooking);
                                    break;
                                }
                                if("WAIT_BUYER_PAY".equals(s)){
                                    num++;
                                }
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return alipay;
    }
 
 
    /**
     * 玩湃币支付课程
     * @param appUser
     * @param paymentPrice
     * @return
     * @throws Exception
     */
    public ResultUtil playPaiCoinPaymentSite(AppUser appUser, Double paymentPrice, SiteBooking siteBooking) throws Exception{
        Integer playPaiCoins = appUser.getPlayPaiCoins();
        appUser.setPlayPaiCoins(playPaiCoins - paymentPrice.intValue());
        appUserClient.updateAppUser(appUser);
        siteBooking.setPayTime(new Date());
        siteBooking.setStatus(1);
        siteBookingService.updateById(siteBooking);
        return ResultUtil.success();
    }
}