admin
2019-11-08 ae6bf015031bd6579cc719ee7689d8160e3d92d2
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
package com.yeshi.fanli.service.impl.shop;
 
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
 
import javax.annotation.Resource;
 
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.yeshi.utils.exception.WXOrderException;
 
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.transaction.LocalTransactionExecuter;
import com.aliyun.openservices.ons.api.transaction.TransactionProducer;
import com.aliyun.openservices.ons.api.transaction.TransactionStatus;
import com.google.gson.Gson;
import com.yeshi.fanli.dao.mybatis.shop.BanLiShopOrderGoodsMapper;
import com.yeshi.fanli.dao.mybatis.shop.BanLiShopOrderMapper;
import com.yeshi.fanli.dto.mq.order.OrderTopicTagEnum;
import com.yeshi.fanli.dto.mq.order.body.BanLiShopOrderMQMsg;
import com.yeshi.fanli.entity.mq.MQUnSendInfo;
import com.yeshi.fanli.entity.redpack.RedPackDetail;
import com.yeshi.fanli.entity.shop.BanLiShopGoods;
import com.yeshi.fanli.entity.shop.BanLiShopGoodsClass;
import com.yeshi.fanli.entity.shop.BanLiShopGoodsSets;
import com.yeshi.fanli.entity.shop.BanLiShopGoodsSetsPay;
import com.yeshi.fanli.entity.shop.BanLiShopOrder;
import com.yeshi.fanli.entity.shop.BanLiShopOrderGoods;
import com.yeshi.fanli.exception.mq.MQUnSendInfoException;
import com.yeshi.fanli.exception.redpack.RedPackBalanceException;
import com.yeshi.fanli.exception.redpack.RedPackDetailException;
import com.yeshi.fanli.exception.shop.BanLiShopOrderException;
import com.yeshi.fanli.service.inter.mq.MQUnSendInfoService;
import com.yeshi.fanli.service.inter.redpack.RedPackBalanceService;
import com.yeshi.fanli.service.inter.shop.BanLiShopGoodsClassService;
import com.yeshi.fanli.service.inter.shop.BanLiShopGoodsService;
import com.yeshi.fanli.service.inter.shop.BanLiShopGoodsSetPayService;
import com.yeshi.fanli.service.inter.shop.BanLiShopGoodsSetService;
import com.yeshi.fanli.service.inter.shop.BanLiShopOrderService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.factory.RedPackDetailFactory;
import com.yeshi.fanli.util.rocketmq.MQTopicName;
import com.yeshi.fanli.util.shop.BanLiShopOrderUtil;
import com.yeshi.fanli.util.wx.BanLiShopWXPayUtil;
 
@Service
public class BanLiShopOrderServiceImpl implements BanLiShopOrderService {
 
    @Resource
    private BanLiShopOrderMapper banLiShopOrderMapper;
 
    @Resource
    private BanLiShopGoodsSetService banLiShopGoodsSetService;
 
    @Resource
    private BanLiShopGoodsSetPayService banLiShopGoodsSetPayService;
 
    @Resource
    private BanLiShopGoodsService banLiShopGoodsService;
 
    @Resource
    private BanLiShopGoodsClassService banLiShopGoodsClassService;
 
    @Resource
    private RedPackBalanceService redPackBalanceService;
 
    @Resource(name = "producer")
    private Producer producer;
 
    @Resource
    private MQUnSendInfoService mqUnSendInfoService;
 
    @Resource
    private BanLiShopOrderGoodsMapper banLiShopOrderGoodsMapper;
 
    @Resource(name = "orderTransactionProducer")
    private TransactionProducer orderTransactionProducer;
 
    @Resource(name = "transactionManager")
    private DataSourceTransactionManager transactionManager;
 
    @Transactional
    @Override
    public void addOrder(BanLiShopOrder order) throws BanLiShopOrderException {
        // 查询必要的参数是否添加
        if (order.getGoodsSet() == null || order.getGoodsSet().getId() == null || order.getGoods() == null
                || order.getGoods().getId() == null)
            throw new BanLiShopOrderException(1, "未选择商品");
 
        if (order.getUid() == null)
            throw new BanLiShopOrderException(1, "缺少用户ID");
 
        if (order.getHongBaoPayment() == null && order.getBalancePayment() == null && order.getMoneyPayment() == null) {
            throw new BanLiShopOrderException(1, "未选择支付方式");
        }
 
        if (order.getHongBaoPayment() != null) {
            order.setHongBaoPaymentState(BanLiShopOrder.PAY_STATE_NOPAY);
        }
 
        if (order.getBalancePayment() != null) {
            order.setBalancePaymentState(BanLiShopOrder.PAY_STATE_NOPAY);
        }
 
        if (order.getMoneyPayment() != null) {
            order.setMoneyPaymentState(BanLiShopOrder.PAY_STATE_NOPAY);
        }
 
        order.setState(BanLiShopOrder.STATE_NO_PAY);
        // 判断商品套餐是否存在
        BanLiShopGoodsSets set = banLiShopGoodsSetService.selectByPrimaryKey(order.getGoodsSet().getId());
        if (set == null) {
            throw new BanLiShopOrderException(1, "商品套餐不存在");
        }
 
        BanLiShopGoods goods = banLiShopGoodsService.selectByPrimaryKey(order.getGoods().getId());
        if (goods == null) {
            throw new BanLiShopOrderException(1, "商品已下线");
        }
 
        if (goods.getCreateTime() == null)
            goods.setCreateTime(new Date());
 
        // 插入商品
        BanLiShopOrderGoods orderGoods = getOrderGoods(goods, set);
        order.setOrderGoods(orderGoods);
        banLiShopOrderMapper.insertSelective(order);
 
        // 添加订单号
        String orderNo = BanLiShopOrderUtil.createOrderNo(order.getId());
        // 更新订单号
        BanLiShopOrder update = new BanLiShopOrder();
        update.setId(order.getId());
        update.setOrderNo(orderNo);
        order.setOrderNo(orderNo);
        banLiShopOrderMapper.updateByPrimaryKeySelective(update);
 
        // 增加销量
        banLiShopGoodsSetService.addSalesCount(order.getGoodsSet().getId(), 1);
        banLiShopGoodsService.addSalesCount(order.getGoods().getId(), 1);
 
        // 订单添加成功 ,延时通知后续
        sendPlaceOrderMsg(order.getId(), order.getUid());
    }
 
    private BanLiShopOrderGoods getOrderGoods(BanLiShopGoods goods, BanLiShopGoodsSets set) {
        BanLiShopOrderGoods orderGoods = new BanLiShopOrderGoods();
        orderGoods.setCreateTime(new Date());
        orderGoods.setGoodsId(goods.getId());
        orderGoods.setGoodsName(goods.getTitle());
        orderGoods.setGoodsSetId(set.getId());
        orderGoods.setSetName(set.getName());
        orderGoods.setState(set.getState());
        orderGoods.setZkPrice(set.getZkPrice());
        orderGoods.setPicture(goods.getSquarePicture());
        banLiShopOrderGoodsMapper.insertSelective(orderGoods);
        return orderGoods;
    }
 
    private void sendPlaceOrderMsg(Long orderId, Long uid) {
 
        Message msg = new Message(MQTopicName.TOPIC_ORDER.name(), OrderTopicTagEnum.banLiShopOrderDelay.name(),
                new Gson().toJson(new BanLiShopOrderMQMsg(orderId, uid)).getBytes());
        msg.setKey(orderId + "");
        long delayTime = System.currentTimeMillis() + (Constant.IS_TEST ? 1000 * 30L : 1000 * 60 * 10);// 10分钟后通知
        msg.setStartDeliverTime(delayTime);
        SendResult sendResult = producer.send(msg);
        if (sendResult == null) {
            MQUnSendInfo info = new MQUnSendInfo();
            info.setBody(new String(msg.getBody()));
            if (msg.getStartDeliverTime() > 0)
                info.setDeliverTime(new Date(msg.getStartDeliverTime()));
            info.setKey(msg.getKey());
            info.setTag(msg.getTag());
            info.setTopic(msg.getTopic());
            try {
                mqUnSendInfoService.addMQUnSendInfo(info);
            } catch (MQUnSendInfoException e) {
                e.printStackTrace();
            }
        }
 
    }
 
    @Override
    public List<BanLiShopOrder> listByUid(Long uid, int page, int pageSize) {
 
        return banLiShopOrderMapper.listByUidAndState(null, uid, (page - 1) * pageSize, pageSize);
    }
 
    @Override
    public long countByUid(Long uid) {
        return banLiShopOrderMapper.countByUidAndState(null, uid);
    }
 
    @Override
    public BanLiShopOrder selectByPrimaryKey(Long id) {
        return banLiShopOrderMapper.selectByPrimaryKey(id);
    }
 
    @Override
    public void udpateSelectiveByPrimaryKey(BanLiShopOrder order) {
        if (order == null || order.getId() == null)
            return;
        if (order.getUpdateTime() == null)
            order.setUpdateTime(new Date());
        banLiShopOrderMapper.updateByPrimaryKeySelective(order);
    }
 
    @Transactional
    @Override
    public void payOrderByHongBao(Long orderId) throws BanLiShopOrderException, RedPackBalanceException {
        BanLiShopOrder order = banLiShopOrderMapper.selectByPrimaryKeyForUpdate(orderId);
        if (order == null) {
            throw new BanLiShopOrderException(1, "订单不存在");
        }
        if (order.getHongBaoPayment() == null)
            throw new BanLiShopOrderException(2, "不需要采用红包支付");
 
        if (order.getHongBaoPaymentState() != null && order.getHongBaoPaymentState() == BanLiShopOrder.PAY_STATE_PAID) {
            throw new BanLiShopOrderException(3, "重复支付");
        }
 
        BanLiShopGoods goods = banLiShopGoodsService.selectByPrimaryKey(order.getGoods().getId());
        BanLiShopGoodsClass goodsClass = banLiShopGoodsClassService.selectByPrimaryKey(goods.getGoodsClass().getId());
        BanLiShopGoodsSets set = banLiShopGoodsSetService.selectByPrimaryKey(order.getGoodsSet().getId());
        RedPackDetail detail = null;
        try {
            detail = RedPackDetailFactory.createUseByShopOrder(orderId, order.getUid(), goodsClass.getName(),
                    set.getName(), order.getHongBaoPayment());
        } catch (RedPackDetailException e) {
            e.printStackTrace();
        }
 
        if (detail == null)
            throw new RedPackBalanceException(4, "红包详情失败");
        redPackBalanceService.subRedPack(order.getUid(), order.getHongBaoPayment(), detail);
 
        BanLiShopOrder update = new BanLiShopOrder();
        update.setHongBaoPaymentState(BanLiShopOrder.PAY_STATE_PAID);
        // 判断其他待支付项是否已经支付
        update.setUpdateTime(new Date());
        order.setHongBaoPaymentState(update.getHongBaoPaymentState());
        update.setState(getOrderPayState(order));
        banLiShopOrderMapper.updateByPrimaryKeySelective(update);
    }
 
    private int getOrderPayState(BanLiShopOrder order) {
        int needPayCount = 0;
        int paidCount = 0;
        // 获取订单付款状态
        if (order.getHongBaoPayment() != null) {
            needPayCount++;
            if (order.getHongBaoPaymentState() != null
                    && order.getHongBaoPaymentState() == BanLiShopOrder.PAY_STATE_PAID)
                paidCount++;
        }
 
        if (order.getBalancePayment() != null) {
            needPayCount++;
            if (order.getBalancePaymentState() != null
                    && order.getBalancePaymentState() == BanLiShopOrder.PAY_STATE_PAID)
                paidCount++;
        }
 
        if (order.getMoneyPayment() != null) {
            needPayCount++;
            if (order.getMoneyPaymentState() != null && order.getMoneyPaymentState() == BanLiShopOrder.PAY_STATE_PAID)
                paidCount++;
        }
 
        if (needPayCount == paidCount)
            return BanLiShopOrder.STATE_PAID;
        else {
            if (paidCount == 0)
                return BanLiShopOrder.STATE_NO_PAY;
            else
                return BanLiShopOrder.STATE_PART_PAY;
        }
    }
 
    @Override
    public void payOrderByMoney(Long orderId, BigDecimal money) throws BanLiShopOrderException {
        BanLiShopOrder order = banLiShopOrderMapper.selectByPrimaryKeyForUpdate(orderId);
        if (order == null) {
            throw new BanLiShopOrderException(1, "订单不存在");
        }
        if (order.getMoneyPayment() == null)
            throw new BanLiShopOrderException(2, "不需要采用现金支付");
 
        if (order.getMoneyPaymentState() != null && order.getMoneyPaymentState() == BanLiShopOrder.PAY_STATE_PAID) {
            throw new BanLiShopOrderException(3, "重复支付");
        }
 
        if (order.getMoneyPayment().compareTo(money) > 0) {
            throw new BanLiShopOrderException(4, "支付金额不够");
        }
 
        // 支付成功
        BanLiShopOrder update = new BanLiShopOrder();
        update.setId(orderId);
        update.setMoneyPaymentState(BanLiShopOrder.PAY_STATE_PAID);
        // 判断其他待支付项是否已经支付
        update.setUpdateTime(new Date());
        order.setMoneyPaymentState(update.getMoneyPaymentState());
        update.setState(getOrderPayState(order));
        banLiShopOrderMapper.updateByPrimaryKeySelective(update);
    }
 
    @Override
    public BanLiShopOrder selectByPrimaryKeyForUpdate(Long id) {
        return banLiShopOrderMapper.selectByPrimaryKeyForUpdate(id);
    }
 
    @Override
    public void invalidOrderByOrderId(Long id, String desc) {
        // 判断订单是否存在
        BanLiShopOrder order = banLiShopOrderMapper.selectByPrimaryKeyForUpdate(id);
        if (order == null)
            return;
 
        // 判断是否处于未付款
        if (order.getState() == BanLiShopOrder.STATE_NO_PAY) {
            /**
             * 查询是否已经微信支付
             */
            if (order.getMoneyPayment() != null) {
                try {
                    boolean isS = BanLiShopWXPayUtil.isPaySuccess(order.getOrderNo());
                    if (isS)// 支付成功,重新发送支付成功消息
                    {
                        BanLiShopOrderMQMsg msg = new BanLiShopOrderMQMsg(order.getId(), order.getUid());
                        Message message = new Message(MQTopicName.TOPIC_ORDER.name(),
                                OrderTopicTagEnum.banLiShopOrderPaid.name(), new Gson().toJson(msg).getBytes());
                        producer.send(message);
                        return;
                    }
 
                } catch (WXOrderException e) {
                    e.printStackTrace();
                } catch (Exception e) {
 
                }
            }
 
            BanLiShopOrder update = new BanLiShopOrder();
            update.setId(id);
            update.setStateDesc(desc);
            update.setState(BanLiShopOrder.STATE_INVALID);
            update.setUpdateTime(new Date());
            banLiShopOrderMapper.updateByPrimaryKeySelective(update);
        }
    }
 
    @Override
    public void rejectOrder(Long id, String msg) throws BanLiShopOrderException {
        // 判断订单是否处于付款状态
        BanLiShopOrder order = banLiShopOrderMapper.selectByPrimaryKey(id);
        if (order == null)
            throw new BanLiShopOrderException(1, "订单不存在");
 
        if (order.getState() != BanLiShopOrder.STATE_PAID)
            throw new BanLiShopOrderException(1, "订单未处于待审核状态");
 
        Message message = new Message(MQTopicName.TOPIC_ORDER.name(), OrderTopicTagEnum.banLiShopOrderRefund.name(),
                new Gson().toJson(new BanLiShopOrderMQMsg(order.getId(), order.getUid())).getBytes());
        try {
            orderTransactionProducer.send(message, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    rejectOrderLocal(id, msg);
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {// 消息发送失败
            throw new BanLiShopOrderException(2, "MQ发送失败");
        }
    }
 
    private void rejectOrderLocal(Long id, String msg) {
        // 手动开启事务
        org.springframework.transaction.TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition());
        try {
            BanLiShopOrder order = banLiShopOrderMapper.selectByPrimaryKeyForUpdate(id);
            BanLiShopOrder update = new BanLiShopOrder();
            update.setId(order.getId());
            update.setState(BanLiShopOrder.STATE_REJECT);
            update.setStateDesc(msg);
            update.setUpdateTime(new Date());
            update.setRejectTime(new Date());
            banLiShopOrderMapper.updateByPrimaryKeySelective(update);
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            transactionManager.rollback(transactionStatus);
        }
    }
 
    @Override
    public BanLiShopOrder createOrder(Long goodsSetPayId, String chargeAccount, Long uid)
            throws BanLiShopOrderException {
        BanLiShopGoodsSetsPay pay = banLiShopGoodsSetPayService.selectByPrimaryKey(goodsSetPayId);
        if (pay == null || pay.getGoodsSet() == null) {
            throw new BanLiShopOrderException(21, "支付方式已下线");
        }
 
        BanLiShopGoodsSets set = banLiShopGoodsSetService.selectByPrimaryKey(pay.getGoodsSet().getId());
        if (set == null || set.getState() == BanLiShopGoodsSets.STATE_OFFLINE) {
            throw new BanLiShopOrderException(21, "商品已下线");
        }
 
        BanLiShopGoods goods = banLiShopGoodsService.selectByPrimaryKey(set.getGoods().getId());
        if (goods == null || goods.getState() == BanLiShopGoods.STATE_OFFLINE) {
            throw new BanLiShopOrderException(22, "商品已下线");
        }
 
        if (pay.getHongBaoPrice() != null && pay.getHongBaoPrice().compareTo(new BigDecimal(0)) > 0) {
            BigDecimal money = redPackBalanceService.getBalance(uid);
            if (money.compareTo(pay.getHongBaoPrice()) < 0) {
                throw new BanLiShopOrderException(24, "红包余额不足");
            }
        }
 
        if (set.getStock() <= 0)
            throw new BanLiShopOrderException(23, "商品库存不足");
 
        BanLiShopOrder order = new BanLiShopOrder();
        order.setChargeAccount(chargeAccount);
        order.setChargeAccountType(goods.getChargeType());
        order.setCreateTime(new Date());
        order.setGoods(goods);
        order.setGoodsSet(set);
        if (pay.getHongBaoPrice() != null && pay.getHongBaoPrice().compareTo(new BigDecimal(0)) > 0) {
            order.setHongBaoPayment(pay.getHongBaoPrice());
            order.setHongBaoPaymentState(BanLiShopOrder.STATE_NO_PAY);
        }
 
        if (pay.getMoneyPrice() != null && pay.getMoneyPrice().compareTo(new BigDecimal(0)) > 0) {
            order.setMoneyPayment(pay.getMoneyPrice());
            order.setMoneyPaymentState(BanLiShopOrder.STATE_NO_PAY);
        }
 
        order.setState(BanLiShopOrder.STATE_NO_PAY);
        order.setStateDesc("未付款");
        order.setUid(uid);
 
        return order;
    }
 
    @Override
    public BanLiShopOrder selectByOrderNo(String orderNo) {
        return banLiShopOrderMapper.selectByOrderNo(orderNo);
    }
 
    @Override
    public List<BanLiShopOrder> listByUidAndState(Long uid, List<Integer> stateList, int page, int pageSize) {
        return banLiShopOrderMapper.listByUidAndState(stateList, uid, (page - 1) * pageSize, pageSize);
    }
 
    @Override
    public long countByUidAndState(Long uid, List<Integer> stateList) {
        return banLiShopOrderMapper.countByUidAndState(stateList, uid);
    }
 
}