zhouxiang
2023-02-23 bec88badaeb0341a1d5429b31357eb37c0b16fb0
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
package com.hx.phip.controller.order;
 
/**
 * 订单控制器
 *
 * @Author: zhouxiang
 * @Date: 2022/09/19/11:53
 * @Description:
 */
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hx.common.BaseController;
import com.hx.common.service.CommonService;
import com.hx.mybatisTool.SqlSentence;
import com.hx.phiappt.common.*;
import com.hx.phiappt.common.PlatformConstants;
import com.hx.phiappt.constants.tool.ConsultantCashReportTool;
import com.hx.phiappt.constants.tool.PerformanceInfoTool;
import com.hx.phiappt.constants.tool.UserStatusTool;
import com.hx.phiappt.dao.mapper.CouponNumberMapper;
import com.hx.phiappt.model.*;
import com.hx.phiappt.model.coupon.Coupon;
import com.hx.phiappt.model.coupon.CouponNumber;
import com.hx.phiappt.model.order.*;
import com.hx.phiappt.model.performance.PerformanceInfo;
import com.hx.phiappt.model.userStatus.UserStatusLog;
import com.hx.phip.config.CustomParameter;
import com.hx.phip.dao.mapper.*;
import com.hx.phip.service.ShopService;
import com.hx.phip.service.UserMoneyService;
import com.hx.phip.service.UserService;
import com.hx.phip.service.order.OrderService;
import com.hx.phip.service.order.OrderServiceV2;
import com.hx.phip.util.api.*;
import com.hx.util.StringUtils;
import com.hz.his.dto.order.OrderPHisDto;
import com.hz.his.dto.order.PayDto;
import com.hz.his.feign.service.sync.SyncOrderService;
import com.platform.constants.LoginConstant;
import com.platform.entity.ThirtApplication;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import com.platform.resultTool.PlatformResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
/**
 * 订单控制器
 * @USER: zhouxiang
 * @DATE: 2021/12/03
 */
@RestController
@RequestMapping("/order")
public class OrderControllerV2 extends BaseController {
 
    //log4j日志
    private static Logger logger = LoggerFactory.getLogger(OrderControllerV2.class.getName());
    // 固定线程池
    //ExecutorService threadPool = Executors.newFixedThreadPool(10);
 
    //订单类型集合(充值,转增充值)
    private static List<String> orderTypeList= Arrays.asList(OrderTotalConstants.TYPE_RECHARGE,OrderTotalConstants.TYPE_TURN_RECHARGE);
    @Resource
    private OrderServiceV2 orderServiceV2;
    @Resource
    private OrderService orderService;
    @Resource
    private ShopService shopService;
    @Resource
    private UserMoneyService userMoneyService;
    @Resource
    private CustomParameter customParameter;
    @Resource
    private UserService userService;
    @Resource
    private SyncOrderService syncOrderService;
    /**
     * 开单接口
     */
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public PlatformResult orderCreate(HttpServletRequest request, @RequestBody OrderPHisDto dto) {
        //校验请求参数是否为空
        if(dto==null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传订单参数");
        }
        //校验签名
        ThirtApplication thirtApplication= (ThirtApplication) request.getSession().getAttribute(LoginConstant.LOGIN_APPLY);
        if(thirtApplication==null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"签名失败,请检查签名!");
        }
 
        //打印请求参数
        logger.info("前打印新开单接口请求所有参数:{}", JSONObject.toJSONString(dto));
 
        //解析请求参数,并校验参数必填值,赋予默认值等操作
        JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(dto));
        //解析总订单对象
        OrdersTotal orderTotal = JSONObject.parseObject(object.getString("orderTotal"), OrdersTotal.class);
        //校验总订单参数
        orderTotal = OrderCreateUtil.checkOrderTotalParam(orderTotal);
 
        //获取订单的子订单
        List<OrderItem> orderItem = JSONObject.parseArray(object.getString("orderItem"), OrderItem.class);
        //校验子订单参数
        orderItem=OrderCreateUtil.checkOrderItem(orderItem,orderTotal.getType());
        //获取开发人员集合
        List<OrderDeveloper> orderDeveloperList = JSONObject.parseArray(object.getString("orderDeveloper"), OrderDeveloper.class);
        //操作人id,没有默认填订单用户标识
        String operatorId = StringUtils.isEmpty(object.getString("operatorId"))?orderTotal.getUserId():object.getString("operatorId");
        //操作类型,0:草稿 1:创建订单 2:创建订单+结账(目前结账和创建是分开的),默认1
        Integer type =object.getInteger("type")==null?1:object.getInteger("type");
        //获取操作人门店标识
        String shopId = object.getString("shopId");//操作人的门店id
 
        //查询需求要的信息,并且判空(例如查询门店、用户、用户资金等信息)
        //查询操作人门店信息
        Shop shop = shopService.selectOneByKey(shopId);
        if(shop==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到门店信息,操作人门店标识:{}",shopId);
        }
        //获取用户资金信息,用于订单快照存储用户资金信息
        UserMoney userMoney = userMoneyService.selectUserId(orderTotal.getUserId());
        if(userMoney==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找用户资金信息,订单用户标识:{}"+orderTotal.getUserId());
        }
        //获取用户信息
        User user = commonService.selectOneByKey(UserMapper.class,orderTotal.getUserId());
        if(user==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找用户信息,订单用户标识:{}"+orderTotal.getUserId());
        }
        //获取订单销售平台信息
        PlatformApplication platformApplication = OrderCreateUtil.getPlatformApplication(orderTotal, commonService);
        //获取操作人信息
        Map<String, String> operator = ApiOrderUtil.getOperator(commonService, operatorId);
 
        //默认总订单参数
        OrderCreateUtil.setDefaultOrderTotal(orderTotal,thirtApplication.getAppId(),thirtApplication.getAppIdCode(),user,commonService);
 
 
        //执行开单方法
        Map<String, Object> map = orderServiceV2.orderCreate(orderTotal, orderItem, type, orderDeveloperList, operator, shop,userMoney,user,platformApplication,commonService);
 
        //返回phis订单号、phis订单id
        return  PlatformResult.success(map);
    }
 
    /**
     * 结账
     */
    @RequestMapping(value = "/payMoney",method = RequestMethod.POST)
    public synchronized PlatformResult orderPayMoney(HttpServletRequest request,@RequestBody PayDto dto) {
        //校验请求参数是否为空
        if(dto==null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传订单参数");
        }
        //校验签名
        ThirtApplication thirtApplication= (ThirtApplication) request.getSession().getAttribute(LoginConstant.LOGIN_APPLY);
        if(thirtApplication==null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"签名失败,请检查签名!");
        }
 
        //打印请求参数
        logger.info("前打印新结账订单请求所有参数:{}",JSONObject.toJSONString(dto));
 
        //解析请求参数,并校验参数必填值,赋予默认值等操作
        JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(dto));
        //是否是按项目付款,0:否,1:是
        Integer type = object.getInteger("type");
        //订单id
        String orderId = object.getString("orderId");
        //应付的总金额
        String total = object.getString("total");
        //用户真正支付的金额集合
        JSONArray amountList = object.getJSONArray("amount");
        //操作人员id
        String operatorId = object.getString("operatorId");
 
        //优惠券id集合
        JSONArray userCouponIds = new JSONArray();
        String userCouponId = object.getString("userCouponId");
        JSONArray couponIds = object.getJSONArray("userCouponIds");
 
        if(StringUtils.noNull(userCouponId)){
            userCouponIds.add(userCouponId);
        }
        if(couponIds!=null && couponIds.size()>0){
            userCouponIds.addAll(couponIds);
        }
 
        //查询需求要的信息,并且判空(例如查询门店、订单信息、一级子订单、用户资金等信息)
        OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
        User user = userService.selectOneByKey(ordersTotal.getUserId());
        UserMoney userMoney=userMoneyService.selectUserId(ordersTotal.getUserId());
        Shop shop = shopService.selectOneByKey(ordersTotal.getDeveloperShopId());
        //判断订单状态是否正确
        if(OrderTotalConstants.STATUS_WAIT_PAY!=ordersTotal.getStatus()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单总状态不正确,只有待支付才能进行结账!");
        }
 
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> objectMap=new HashMap<>();
        sqlSentence.setM(objectMap);
        objectMap.put("id",orderId);
        //获取订单其他信息(orderInfo)
        sqlSentence.setSqlSentence("SELECT * FROM orders_info where orderId=#{m.id}");
        OrderInfo info = commonService.selectOne(OrderInfoMapper.class,sqlSentence);
        //获取一级子订单信息,注意:充值和转增充值订单没有一级子订单集合
        sqlSentence.setSqlSentence("select * from order_item where isDel=0 and orderId=#{m.id}");
        List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
        //获取操作人信息map
        Map<String, String> operator = ApiOrderUtil.getOperator(commonService, operatorId);
        //判断优惠券叠加使用,项目券或者现金券+生日券
        if(userCouponIds!=null && userCouponIds.size()>0){
            checkCoupon(userCouponIds,commonService);
        }
 
        //判断是否非空,订单、用户、用户资金、门店、订单其他信息(orderInfo)、订单标识、应付总金额、用户支付金额、操作人标识信息是否为空
        checkIsNull(ordersTotal, user, userMoney, shop,info,orderItemList,orderId,total,amountList,operatorId);
        ordersTotal.setOrderInfo(info);
        //收银员id
        String cashier = object.getString("cashier");
        if(PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())){
            cashier=ordersTotal.getUserId();
        }
        if(StringUtils.noNull(cashier)){
            Employee employee=commonService.selectOneByKeyBlob(EmployeeMapper.class,cashier);
            if(employee!=null){
                ordersTotal.setCashierId(employee.getId());
                ordersTotal.setCashierName(StringUtils.isEmpty(employee.getCnName())?"":employee.getCnName());
            }else{
                User cashierUser=commonService.selectOneByKeyBlob(UserMapper.class,cashier);
                if(cashierUser!=null){
                    ordersTotal.setCashierId(cashierUser.getId());
                    ordersTotal.setCashierName(StringUtils.isEmpty(cashierUser.getName())?"":cashierUser.getName());
                }
            }
        }
        //收银员门店
        String cashierShopId = object.getString("cashierShopId");
        if(PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())){
            cashierShopId=ordersTotal.getDeveloperShopId();
        }
        if(StringUtils.noNull(cashierShopId)){
            Shop cashierShop=commonService.selectOneByKeyBlob(ShopMapper.class,cashierShopId);
            if(cashierShop!=null){
                ordersTotal.setCashierShopId(cashierShop.getId());
                ordersTotal.setCashierShopName(StringUtils.isEmpty(cashierShop.getName())?"":cashierShop.getName());
            }
        }
 
        User payUser = null;
        //支付用户
        if(StringUtils.noNull(dto.getPayUserId())){
            payUser = userService.selectOneByKey(dto.getPayUserId());
            if(payUser == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"支付人标识错误!");
            }
        }
        if(payUser == null){
            payUser = user;
        }
 
        //执行结账方法
        Map<String, Object> map = orderServiceV2.orderPayMoney(type, ordersTotal,user,payUser,shop,info,orderItemList,operator,userMoney,total, amountList,userCouponIds,null);
 
        if(map!=null && map.containsKey("orderId")){
            OrdersTotal sucOrdersTotal=commonService.selectOneByKey(OrdersTotalMapper.class,map.get("orderId"));
            if(OrderTotalConstants.PAY_STATUS_SUC==sucOrdersTotal.getPayStatus()){
                //处理老带新
                JSONObject commissionObject = handOrderOldNew(amountList, ordersTotal, user, map);
 
                //更新用户最后下单时间
                updateUserLastTime(ordersTotal, user);
 
                //需求: 1.HIS助手结账成功:要通知客户所属顾问,发送企业微信通知 ,如果没有所属顾问发送给门店运营客服(三少说目前不处理crm已处理) -异步
                try {
                    orderServiceV2.sendUserConsultant(ordersTotal.getUserId(),ordersTotal.getOrderNo(),ordersTotal.getId(),commissionObject,commonService);
                }catch (Exception e){
                    logger.info("要通知客户所属顾问,发送企业微信通知异常 -异步:{}",e.getMessage(),e);
                }
                //记录收入确认表
                try{
                    orderServiceV2.statementPerformanceInfo((String) map.get("orderId"));
                }catch (Exception e) {
                    logger.info("记录收入确认表,异常:{}", e.getMessage(), e);
                    // 添加错误日志
                    PerformanceInfoTool.addErrorLog(commonService, map.get("orderId").toString(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_ORDER, e.getMessage());
                }
                //咨询师现金业绩报表
                try{
                    orderServiceV2.statementConsultantCash((String) map.get("orderId"));
                }catch (Exception e){
                    logger.info("咨询师现金业绩报表,异常:{}",e.getMessage(),e);
                }
            }
 
            //异步获取未执行划扣信息,测试环境先放开,荣爷说,记得写重发
//            if(user!=null && StringUtils.noNull(user.getApiId())){
//                try {
//                    orderService.getExecution(map.get("orderId"),user);
//                }catch (Exception e){
//                    logger.info("异步获取未执行划扣信信失败!订单标识:{},用户信息:{}",map.get("orderId"),JSONObject.toJSONString(user));
//                }
//            }
            //获取领建订单号
//            if(map.containsKey("hisOrderId")){
//                try {
//                    Map<String,Object> paramMap=new HashMap<>();
//                    sqlSentence.setM(paramMap);
//                    paramMap.put("orderId",map.get("orderId"));
//                    paramMap.put("isDel",BaseEntity.NO);
//                    String hisOrderId = orderService.getHisOrderId((String) map.get("hisOrderId"), (String) map.get("orderId"), sqlSentence, paramMap, syncOrderService, commonService);
//                    map.put("hisOrderNo", hisOrderId);
//                }catch (Exception e){
//                    logger.info("获取领建订单号失败!订单标识:{}",map.get("orderId"));
//                }
//            }
//            OrdersTotal orderSum=commonService.selectOneByKey(OrdersTotalMapper.class,map.get("orderId"));
//            if(orderSum!=null && StringUtils.noNull(orderSum.getHisOrderId())){
//                //同步卡包标识,暂时由同步中心处理,以后切掉领建由预约处理新增卡包
//                if(StringUtils.isEmpty(ordersTotal.getKoapOrderId())){
//                    SynOrderUtil.synGetUserCard(orderSum,customParameter,commonService);
//                }
//            }
            //根据订单用户标识同步当前用户所有未执行划扣数据,弃用
//            if(user!=null && StringUtils.noNull(user.getApiId())){
//                JSONObject data = new JSONObject();
//                data.put("endTime", DateUtil.formatDate_3(new Date()));
//                data.put("startTime",DateUtil.formatDate_3(new Date()));
//                data.put("customerId",user.getApiId());
//                ApiPlatformUtil.sysnExecution(customParameter,data.toJSONString());
//            }
 
 
        }
//        //优惠券id  单张使用优惠券废弃
//        String userCouponId = object.getString("userCouponId");
//        //查询优惠券信息
//        if(StringUtils.noNull(userCouponId)){
//            //查看用户是否有优惠券
//            couponNumber = commonService.selectOneByKey(CouponNumberMapper.class, userCouponId);
//            if(couponNumber==null){
//                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷:该用户没有该优惠券");
//            }
//            //查看用户是否有优惠券
//            coupon = commonService.selectOneByKey(CouponMapper.class, couponNumber.getCouponId());
//            if(coupon==null){
//                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷:未找到优惠券信息");
//            }
//        }
 
//        //结账成功发送公众号通知给用户
//        threadPool.execute(() -> orderServiceV2.sendPublicNo(ordersTotal.getId(),commonService));
//        //需求: 1.HIS助手结账成功:要通知客户所属顾问,发送企业微信通知
//        threadPool.execute(() -> orderService.sendUserConsultant(ordersTotal.getUserId(),ordersTotal.getOrderNo(),ordersTotal.getId(),commonService));
 
        //返回phis订单号、phis订单id、领建订单号、领建订单id
        return  PlatformResult.success(map);
    }
 
    /**
     * 结账判断是否为空
     * @param ordersTotal                       总订单标识
     * @param user                              用户信息
     * @param userMoney                         用户资金
     * @param shop                              门店信息
     * @param info                              订单其他信息(orderInfo)
     * @param orderItemList                     一级子订单集合
     * @param orderId                           订单标识
     * @param total                             应付总金额
     * @param amountList                        用户支付集合
     * @param operatorId                        操作人标识
     */
    private void checkIsNull(OrdersTotal ordersTotal, User user, UserMoney userMoney, Shop shop,OrderInfo info,List<OrderItem> orderItemList,
                             String orderId,String total,JSONArray amountList,String operatorId) {
        if(StringUtils.isEmpty(orderId)){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传订单id");
        }
 
        if(StringUtils.isEmpty(total)){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传应付的总金额");
        }
 
        if(amountList ==null || amountList.size()==0){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传用户真实付款金额");
        }
 
        if(StringUtils.isEmpty(operatorId)){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传用户操作人标识");
        }
 
        if(ordersTotal!=null){
//            //同步用户资金信息
//            UserMoneyUtil.syncHisUserMoney(commonService,customParameter,ordersTotal.getUserId());
        }else{
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单不存在");
        }
 
        if(user==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账:未找到该用户信息");
        }
 
        if(userMoney ==null ){
            //没有用户资金信息,抛错,资金全部交给用户资金全权处理
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到用户资金信息!");
        }
 
        if(shop==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账时:订单门店不存在");
        }
 
        if(info==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"根据总订单未找到订单其他信息");
        }
 
        if(!orderTypeList.contains(ordersTotal.getType()) && (orderItemList ==null || orderItemList.size()==0)){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"没有对应的子订单");
        }
    }
 
    /**
     * 检查优惠券是否符合一张项目券或者一张现金券+生日优惠券
     * 判断思路说明:
     *      1、只要统计用户使用优惠券集合的项目券或者现金券的张数
     *      2、如果项目或者现金券大于1张肯定是不给使用的
     *      3、如果都没有项目券或者现金券,代表专门使用生日优惠券,生日优惠券不进行判断限制,无限使用
     @param userCouponIds
     */
    public static void checkCoupon(JSONArray userCouponIds, CommonService commonService) {
        CouponNumber couponNumber=null;
        Coupon coupon=null;
        //统计项目券张数
        Integer projectCoupon=0;
        //统计现金券张数
        Integer cashCoupon=0;
        for(int i=0;i<userCouponIds.size();i++){
            String couponId = userCouponIds.getString(i);
            //查看用户是否有优惠券
            couponNumber = commonService.selectOneByKey(CouponNumberMapper.class, couponId);
            if(couponNumber==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷:该用户没有该优惠券");
            }
            //查看用户是否有优惠券
            coupon = commonService.selectOneByKey(CouponMapper.class, couponNumber.getCouponId());
            if(coupon==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷:未找到优惠券信息");
            }
            if(coupon.getIsBirthday()== BaseEntity.NO && (coupon.getUseProjectType()==Coupon.USE_TYPE_PROJECT || coupon.getUseProjectType()==Coupon.USE_TYPE_PROJECT_CLASSIFY)){
                projectCoupon=projectCoupon+1;
            }else if(coupon.getIsBirthday()==BaseEntity.NO &&(coupon.getUseGoodsType()==Coupon.USE_TYPE_GOODS || coupon.getUseGoodsType()==Coupon.USE_TYPE_GOODS_CLASSIFY)){
                projectCoupon=projectCoupon+1;
            }else if(coupon.getIsBirthday()==BaseEntity.NO &&(coupon.getUsePromotionType()==Coupon.USE_TYPE_PROMOTION || coupon.getUsePromotionType()==Coupon.USE_TYPE_PROMOTION_CLASSIFY)){
                projectCoupon=projectCoupon+1;
            }else if(coupon.getIsBirthday()==BaseEntity.NO &&(coupon.getUseCardType()==Coupon.USE_TYPE_CARD || coupon.getUseCardType()==Coupon.USE_TYPE_CARD_CLASSIFY)){
                projectCoupon=projectCoupon+1;
            }else if(coupon.getIsBirthday()==BaseEntity.NO && coupon.getCommodityType()==Coupon.USE_TYPE_TYPE_COMMODITY){
 
            }else if(coupon.getIsBirthday()==BaseEntity.NO && coupon.getIntegralType()==Coupon.USE_TYPE_CRM_GOODS){
 
            }else if(coupon.getIsBirthday()==BaseEntity.NO &&(coupon.getUseProjectType()==Coupon.USE_TYPE_PROJECT_ALL || coupon.getUseGoodsType()==Coupon.USE_TYPE_GOODS_ALL||
                    coupon.getUsePromotionType()==Coupon.USE_TYPE_PROMOTION_ALL || coupon.getUseCardType()==Coupon.USE_TYPE_CARD_ALL || coupon.getCommodityType()==Coupon.USE_TYPE_COMMODITY_ALL ||
                    coupon.getIntegralType()==Coupon.USE_TYPE_CRM_GOODS_ALL)){
                cashCoupon=cashCoupon+1;
            }
        }
        if(cashCoupon>1){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"叠加优惠卷提示:一张订单只能使用一张现金券");
        }
        if(projectCoupon>1){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"叠加优惠卷提示:一张订单只能使用一张项目券");
        }
    }
 
    /**
     * 更新用户最后一次下单时间
     * @param ordersTotal
     * @param user
     */
    public void updateUserLastTime(OrdersTotal ordersTotal, User user) {
        try {
            SqlSentence sqlSentence = new SqlSentence();
            Map<String, Object> sqlValues = new HashMap<>();
            sqlValues.put("lastPayOrderTime", new Date());
            sqlValues.put("editTime", new Date());
            sqlValues.put("isLoss", BaseEntity.NO);
            sqlValues.put("isDel", BaseEntity.NO);
            sqlValues.put("id", user.getId());
            StringBuilder sql = new StringBuilder();
            sql.append(" lastPayOrderTime=#{m.lastPayOrderTime},editTime=#{m.editTime},isLoss=#{m.isLoss}");
            // 会员有消费和执行就是活跃会员
            String status = null;
            if (!UserStatusConstants.USER_STATUS_NON_MEMBER.equals(user.getUserStatus())) {
                status = UserStatusConstants.USER_STATUS_ACTIVE_MEMBER;
                sqlValues.put("userStatus", status);
                sql.append(",userStatus=#{m.userStatus}");
            }
            sql.append(" WHERE id=#{m.id} AND isDel=#{m.isDel}");
            sqlSentence.sqlSentence(sql.toString(), sqlValues);
            commonService.updateWhere(UserMapper.class, sqlSentence);
            // 添加调整用户状态日志 调整了用户等级在写入日志
            if (!StringUtils.isEmpty(status)) {
                UserStatusTool.addUserStatusLog(commonService, user, UserStatusLog.CHANGE_STATUS_TYPE_ORDER, ordersTotal.getId(), UserStatusConstants.USER_STATUS_ACTIVE_MEMBER);
            }
        } catch (Exception e) {
            logger.info("更新用户最后下单时间,异常:{}", e.getMessage(), e);
        }
    }
 
    /**
     * 处理老带新
     * @param amountList
     * @param ordersTotal
     * @param user
     * @param map
     * @return
     */
    private JSONObject handOrderOldNew(JSONArray amountList, OrdersTotal ordersTotal, User user, Map<String, Object> map) {
        /**
         * 处理老带新(禅道为准,禅道号176)
         *      1.准会员、普卡、银卡:
         *          邀请人增值金百分比:8%
         *          被邀请人增值金百分比:2%
         *     2.金卡、钻卡、黑卡:
         *          邀请人增值金百分比:10%
         *          被邀请人增值金百分比:5%
         */
        SqlSentence sql = new SqlSentence();
        Map<String,Object> paramMap=new HashMap<>();
        sql.setM(paramMap);
        JSONObject commissionObject =new JSONObject();
        JSONArray hisPayList=new JSONArray();
        StringBuilder orderNodeBuilder = new StringBuilder();
        if(ordersTotal.getOrderInfo().getIsOldBringNew() !=null && ordersTotal.getOrderInfo().getIsOldBringNew()== BaseEntity.YES){
            JSONObject hisPay ;
            for(int i=0;i<amountList.size();i++) {
                JSONObject jsonObject = amountList.getJSONObject(i);
                String amount = jsonObject.getString("amount");//用户实际支付金额
                String method = jsonObject.getString("method");//用户支付编码
 
                hisPay = new JSONObject();
 
                //根据支付编码,上架的支付方式,并判空
                paramMap.put("method", method);
                paramMap.put("isDel", BaseEntity.NO);
                paramMap.put("isUp", BaseEntity.YES);
                sql.setSqlSentence("select * from payment_method where numberNo=#{m.method} and isDel=#{m.isDel} and isUp=#{m.isUp}");
                PaymentMethod paymentMethod = commonService.selectOne(PaymentMethodMapper.class, sql);
                if (paymentMethod != null) {
                    //添加用户支付方式金额、以及方法,用于同步到his系统
                    hisPay.put("amount",amount);
                    hisPay.put("methodCode",paymentMethod.getNumberNo());
                    hisPay.put("isMoneyPay",paymentMethod.getIsMoneyPay());
                    hisPayList.add(hisPay);
                }
            }
                try {
                orderNodeBuilder.append("-开始处理老带新");
                commissionObject = OrderPayMoneyUtil.handPayOldNew(ordersTotal, user, hisPayList, commonService);
                orderNodeBuilder.append("-结束处理老带新");
            }catch (Exception e){
                String snapshot="处理老带新失败";
                orderNodeBuilder.append("-处理老带新失败,异常原因:"+e.getMessage());
                logger.error("处理老带新失败:" + e.getMessage(),e);
                //发送企业微信通知给工作人员
                SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
            }
 
            paramMap.put("orderId",map.get("orderId"));
            sql.setSqlSentence("select * from orders_node_log where orderId=#{m.orderId} and isDel=0 order by createTime desc LIMIT 1");
            OrdersNodeLog ordersNodeLog=commonService.selectOne(OrdersNodeLogMapper.class,sql);
            if(ordersNodeLog!=null ){
                String concat = ordersNodeLog.getContent().concat(orderNodeBuilder.toString());
                paramMap.put("concat",concat);
                paramMap.put("id",ordersNodeLog.getId());
                sql.setSqlSentence(" content=#{m.concat} where id=#{m.id} ");
                commonService.updateWhere(OrdersNodeLogMapper.class,sql);
            }
        }
        return commissionObject;
    }
}