2021与蓝度共同重构项目,服务端
liuhaonan
2022-08-15 5c3a5b7bf75718a003de4b167cf9fc81a27f06ee
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
package com.sandu.ximon.admin.service;
 
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.pagehelper.PageHelper;
import com.sandu.common.execption.BusinessException;
import com.sandu.common.object.BaseConditionVO;
import com.sandu.common.service.impl.BaseServiceImpl;
import com.sandu.common.util.SpringContextHolder;
import com.sandu.ximon.admin.manager.iot.frame.inner.report.A5C3HeartbeatReportInnerFrame;
import com.sandu.ximon.admin.manager.iot.rrpc.enums.C3mRedisConstant;
import com.sandu.ximon.admin.pay.OrderStatusEnums;
import com.sandu.ximon.admin.pay.wx.WxFastPayService;
import com.sandu.ximon.admin.security.SecurityUtils;
import com.sandu.ximon.admin.security.order.OrderQueryListener;
import com.sandu.ximon.admin.utils.AliPayUtils;
import com.sandu.ximon.admin.utils.RedisUtils;
import com.sandu.ximon.admin.vo.C3mOrderVO;
import com.sandu.ximon.dao.bo.C3mOrderBo;
import com.sandu.ximon.dao.domain.C3mCharging;
import com.sandu.ximon.dao.domain.C3mOrder;
import com.sandu.ximon.dao.domain.Pole;
import com.sandu.ximon.dao.enums.OrderStatus;
import com.sandu.ximon.dao.enums.OrderType;
import com.sandu.ximon.dao.mapper.C3mOrderMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
 
/**
 * @Author liuhaonan
 * @Date 2022/3/10 14:24
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class C3mOrderService extends BaseServiceImpl<C3mOrderMapper, C3mOrder> {
 
    private final RedisUtils redisUtils;
    private final PoleService poleService;
    private final C3mOrderMapper c3mOrderMapper;
    private final WxFastPayService fastPayService;
    private final OrderQueryListener orderQueryListener;
    private final Snowflake snowflake;
 
    private final C3ChargingService c3ChargingService;
 
    /**
     * 退款
     *
     * @param outTradeNo
     * @return
     */
    public boolean orderRefund(String outTradeNo, Double amt) {
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        C3mOrder orderByOutTradeNo = c3mOrderMapper.getOrderByOutTradeNo(outTradeNo);
        Double refundAmount = orderByOutTradeNo.getSurplusAmount();
        if (orderByOutTradeNo.getTotalAmount() < refundAmount) {
            throw new BusinessException("退款金额错误,不能大于付款金额");
        }
        if (orderByOutTradeNo == null) {
            throw new BusinessException("未找到订单");
        } else {
            orderByOutTradeNo.setRefundAmount(refundAmount);
            return c3mOrderRefund(orderByOutTradeNo, "充电桩退款", userId, username);
        }
 
 
    }
 
 
    /**
     * 退款
     *
     * @param C3mOrder
     * @param msg
     * @param userId
     * @param username
     * @return
     */
//    @Transactional(rollbackFor = Exception.class)
    private boolean c3mOrderRefund(C3mOrder C3mOrder, String msg, Long userId, String username) {
        //  进行退款,设置订单状态为已退款
        boolean b = false;
        if (C3mOrder.getOrderType().equals(OrderType.ALIPAY.getCode())) {
            b = AliPayUtils.alipayrefund(
                    C3mOrder.getPoleId(),
                    C3mOrder.getOutTradeNo(),
                    C3mOrder.getRefundAmount());
        } else if (C3mOrder.getOrderType().equals(OrderType.WXPAY.getCode())) {
            //  进行微信退款
            b = fastPayService.refund(
                    C3mOrder.getTotalAmount(),
                    C3mOrder.getRefundAmount(),
                    C3mOrder.getOutTradeNo(),
                    C3mOrder.getPoleId()
            );
        }
        C3mOrder.setRefundTimestamp(System.currentTimeMillis());
        C3mOrder.setRefundMsg(msg);
        if (b) {
            C3mOrder.setOrderStatus(OrderStatus.REFUND.getStatus());
            c3mOrderMapper.updateRefundOrder(C3mOrder);
 
            log.error("充电桩退款 " + "{ 操作者(" + username + ")" +
                    "订单退款: " + C3mOrder.getOutTradeNo()
                    + ",订单总金额:" + C3mOrder.getTotalAmount()
                    + ",退款金额: " + C3mOrder.getRefundAmount() + "}");
            return true;
        } else {
            C3mOrder.setOrderStatus(OrderStatus.REFUND_FAILED.getStatus());
            c3mOrderMapper.updateRefundOrder(C3mOrder);
            log.error("充电桩退款 " + "{ 操作者(" + username + ")" +
                    "订单退款: " + C3mOrder.getOutTradeNo()
                    + ",订单总金额:" + C3mOrder.getTotalAmount()
                    + ",退款金额: " + C3mOrder.getRefundAmount() + "}");
            return false;
        }
    }
 
    /**
     * 创建订单
     *
     * @param streetlightId
     * @param c3m
     * @param orderType
     * @param totalAmount
     * @param subscribeChargingCapacity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public C3mOrder advancePayOrder(Long streetlightId, C3mCharging c3m, String orderType, Double totalAmount,
                                    Integer subscribeChargingCapacity, String wxCode) {
 
        //  判断该充电桩是否存在正在进行中的订单
        String chargingJson = redisUtils.get(C3mRedisConstant.C3_CHARGING_ORDER.getCode() + c3m.getC3Mac());
        if (null != chargingJson) {
            throw new BusinessException("该充电桩已存在正在进行中的订单");
        }
        //查询充电桩是否存在正在进行中的订单
        C3mOrder c3mOrder = getOne(Wrappers.lambdaQuery(C3mOrder.class)
                .eq(C3mOrder::getC3Udid, c3m.getMcuUdid()).eq(C3mOrder::getChargingStates, 0).last("limit 1"));
 
        if (c3mOrder != null && !c3mOrder.getUserCode().equals(wxCode)) {
            throw new BusinessException("该充电桩正在被别人使用");
        }
        if (c3mOrder != null) {
            throw new BusinessException("该充电桩已存在正在进行中的订单");
        }
        Pole pole = poleService.getById(streetlightId);
        if (null == pole) {
            return null;
        }
        //  生成订单,并加载到redis缓存,设置超时时间为5分钟
        C3mOrder c3mOrderEntity = new C3mOrderVO().generateOrder(
                streetlightId,
                pole.getDeviceCode(),
                c3m.getC3Mac(),
                OrderType.getOrderType(orderType),
                totalAmount,
                subscribeChargingCapacity
        );
        boolean b = true;
        c3mOrderEntity.setOrderId(snowflake.nextId());
        c3mOrderEntity.setC3Mac(c3m.getC3Name());
        c3mOrderEntity.setPoleId(streetlightId);
        c3mOrderEntity.setPoleMac(pole.getDeviceCode());
        c3mOrderEntity.setPoleName(pole.getPoleName());
        c3mOrderEntity.setC3Mac(c3m.getC3Mac());
        c3mOrderEntity.setOrderStatus(0);
        c3mOrderEntity.setUserCode(wxCode);
        c3mOrderEntity.setC3Udid(c3m.getMcuUdid());
 
        if (b) {
            this.save(c3mOrderEntity);
        }
        return b ? c3mOrderEntity : null;
    }
 
    /**
     * 微信支付回调
     */
    public Object payWechatNotify(String xmlData) {
        WxPayOrderNotifyResult wxPayOrderNotifyResult = fastPayService.parseOrderNotifyResult(xmlData);
        String orderSn = wxPayOrderNotifyResult.getOutTradeNo();
        String transactionId = wxPayOrderNotifyResult.getOutTradeNo();
        C3mOrder userOrder = getByOrderSn(orderSn);
        if (userOrder == null) {
            return WxPayNotifyResponse.fail("订单不存在 sn=" + orderSn);
        }
 
        // 检查这个订单是否已经处理过
        if (!OrderStatusEnums.UNPAID.getCode().equals(userOrder.getOrderStatus())) {
            return WxPayNotifyResponse.success("订单已经处理成功!");
        }
        userOrder.setOutTradeNo(transactionId);
        userOrder.setPayTimestamp(new Date().getTime());
        userOrder.setOrderStatus(OrderStatusEnums.PAID.getCode());
        /**
         * 调起开始充电接口
         */
        String s = c3ChargingService.startCharging(userOrder.getC3Mac(), userOrder.getSubscribeChargingCapacity(), userOrder.getTotalAmount());
        if (s.isEmpty() || s == null) {
            throw new BusinessException("开启充电失败");
        }
        //开启充电成功后,更新订单状态为充电中
        userOrder.setChargingStates(0);
        if (!updateById(userOrder)) {
            return WxPayNotifyResponse.fail("更新数据已失效");
        }
 
        return WxPayNotifyResponse.success("更新数据成功");
    }
 
    /**
     * 订单详情  by orderSn
     *
     * @param orderSn
     * @return
     */
    public C3mOrder getByOrderSn(String orderSn) {
        LambdaQueryWrapper<C3mOrder> wrapper = Wrappers.lambdaQuery(C3mOrder.class).eq(C3mOrder::getOutTradeNo, orderSn).last("limit 1");
        return getOne(wrapper);
    }
 
    /**
     * 根据c3Mac获取最近一条订单
     */
    public C3mOrder getLastOrderByC3Mac(String c3Mac) {
        LambdaQueryWrapper<C3mOrder> wrapper = Wrappers.lambdaQuery(C3mOrder.class).eq(C3mOrder::getC3Mac, c3Mac).last("limit 1");
        return getOne(wrapper);
    }
 
 
    /**
     * 根据心跳包更新订单状态
     */
    public void updateOrderStatusByHeartbeat(A5C3HeartbeatReportInnerFrame.HeartBeatDataPackage dataPackage) {
        //充电中的心跳包需要去更新订单数据,否则不处理!
        if (dataPackage.getStatusBit().equals("02")) {
            C3mOrder c3mOrder = getOne(Wrappers.lambdaQuery(C3mOrder.class).eq(C3mOrder::getC3Mac, dataPackage.getC3Mac())
                    .eq(C3mOrder::getChargingStates, 1).last("limit 1"));
            if (c3mOrder == null) {
                return;
            }
            //更新充电总量
            c3mOrder.setActualChargingCapacityHide(Double.parseDouble(dataPackage.getChargedCapacity()));
            //更新剩余金额
            c3mOrder.setSurplusAmount(Double.parseDouble(dataPackage.getRemainingAmount()));
            updateById(c3mOrder);
        }
    }
 
 
    /**
     * 订单列表
     *
     * @param baseConditionVO
     * @return
     */
    public List<C3mOrderBo> orderList(BaseConditionVO baseConditionVO, String keyword,
                                      Integer orderStatus, Integer timeType) {
        if (orderStatus != null && (orderStatus > 5 || orderStatus < 0)) {
            throw new BusinessException("订单状态不正确");
        }
        Long userId = SecurityUtils.getClientId();
        //查询近一个月的订单
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = null;
        ;
        Long startTimeStamp = null;
        Long nowTimeStamp = null;
        if (timeType != null) {
            if (timeType == 1) {
                //查询近一个月的订单
                startTime = now.minusMonths(1);
            } else if (timeType == 2) {
                //查询近三个月的订单
                startTime = now.minusMonths(3);
            } else if (timeType == 3) {
                //查询近半年的订单
                startTime = now.minusMonths(6);
            } else {
                throw new BusinessException("时间类型不正确");
            }
            //startTime转换为时间戳
            startTimeStamp = startTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            //endTime转换为时间戳
            nowTimeStamp = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        }
        PageHelper.startPage(baseConditionVO.getPageNo(), baseConditionVO.getPageSize());
        List<C3mOrderBo> list = baseMapper.orderList(userId, keyword, orderStatus, startTimeStamp, nowTimeStamp);
        return list;
    }
 
 
    /**
     * 获取创建时间超过10分钟的订单 并且没有支付的订单
     */
    public void deleteOrderListByCreateTime() {
        // 获取当前时间戳
        Long time = System.currentTimeMillis();
        //删除超过10分钟未付款的订单
        remove(Wrappers.lambdaQuery(C3mOrder.class).lt(C3mOrder::getCreateTimestamp, time).eq(C3mOrder::getOrderStatus, 0));
    }
 
    /**
     * 恢复继续充电
     *
     * @param c3Mac
     * @param mcuUdid
     */
    public void recoverContinueCharing(String c3Mac, String mcuUdid) {
        C3mOrder c3mOrder = getOne(Wrappers.lambdaQuery(C3mOrder.class).
                eq(C3mOrder::getC3Mac, c3Mac).eq(C3mOrder::getC3Udid, mcuUdid).eq(C3mOrder::getChargingStates, 0).last("limit 1"));
        if (c3mOrder != null) {
            c3mOrder.setActualChargingCapacity(c3mOrder.getActualChargingCapacityHide());
            c3mOrder.setActualChargingCapacityHide(0.00);
 
            //再次充电电量
            double electricity = c3mOrder.getSubscribeChargingCapacity() - c3mOrder.getActualChargingCapacity();
            Integer chargingCapacity = Integer.valueOf(String.valueOf(Math.floor(electricity)));
            //再次充电金额
            double chargeAmount = c3mOrder.getSurplusAmount();
            SpringContextHolder.getBean(C3ChargingService.class).startCharging(c3Mac, chargingCapacity, chargeAmount);
        }
    }
 
}