package com.hai.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.XmlUtil;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.security.AESEncodeUtil;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.IDGenerator;
import com.hai.common.utils.WxUtils;
import com.hai.config.*;
import com.hai.dao.*;
import com.hai.entity.*;
import com.hai.enum_type.*;
import com.hai.model.*;
import com.hai.msg.entity.MsgTopic;
import com.hai.service.*;
import com.hai.service.pay.impl.GoodsOrderServiceImpl;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/26 23:06
 */
@Service("highOrderService")
public class HighOrderServiceImpl implements HighOrderService {

    @Resource
    private HighOrderMapper highOrderMapper;

    @Resource
    private HighDeviceService deviceService;

    @Resource
    private BsRequestRecordService bsRequestRecordService;

    @Resource
    private HighUserPayPasswordService highUserPayPasswordService;

    @Resource
    private ThirdProductConfig thirdProductConfig;

    @Resource
    private HighOrderMapperExt highOrderMapperExt;

    @Resource
    private HighUserCardService highUserCardService;

    @Resource
    private HighChildOrderMapper highChildOrderMapper;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private ApiProductService apiProductService;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private HighGasOrderPushMapper highGasOrderPushMapper;

    @Resource
    private HighCouponHandselService highCouponHandselService;

    @Resource
    private HighCouponCodeOtherMapper highCouponCodeOtherMapper;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighUserCouponMapper highUserCouponMapper;

    @Resource
    private HighDiscountUserRelMapper highDiscountUserRelMapper;

    @Resource
    private HighDiscountUserRelService highDiscountUserRelService;

    @Resource
    private HighDiscountAgentCodeService highDiscountAgentCodeService;

    @Resource
    private HighDiscountPackageService discountPackageService;

    @Resource
    private HighDiscountPackageRecordService discountPackageRecordService;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighOrderPreService highOrderPreService;

    @Resource
    private HighActivityInfoService highActivityInfoService;

    @Resource
    private HighActivityUserLotteryNumService highActivityUserLotteryNumService;

    @Resource
    private HighDiscountPackageActualService discountPackageActualService;

    @Resource
    private HighDiscountPackageDiscountActualService discountPackageDiscountActualService;

    @Resource
    private HuiLianTongConfig huiLianTongConfig;

    @Resource
    private HighOilCardService oilCardService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private GoodsOrderServiceImpl goodsOrderService;

    @Resource
    private MqttProviderConfig mqttProviderConfig;

    @Resource
    private BaiduVoiceService baiduVoiceService;

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private ApiAmountRecordService apiAmountRecordService;

    @Resource
    private ApiOrderRecordService apiOrderRecordService;

    @Resource
    private ApiMemberProductService apiMemberProductService;

    @Resource
    private ShellGroupService shellGroupService;

    @Resource
    private JinZhuJiaYouService jinZhuJiaYouService;

    @Override
    @Transactional(
            isolation = Isolation.SERIALIZABLE,
            propagation = Propagation.REQUIRES_NEW)
    public void insertOrder(HighOrder highOrder) throws Exception {
        highOrderMapper.insert(highOrder);

        // 使用优惠券
        if (highOrder.getMemDiscountId() != null) {
            HighDiscountUserRel discountUserRel = highDiscountUserRelService.getRelById(highOrder.getMemDiscountId());
            discountUserRel.setUseTime(new Date()); // 使用时间
            discountUserRel.setStatus(2);  //状态  0:已过期  1：未使用  2：已使用
            highDiscountUserRelService.updateDiscountUserRel(discountUserRel);

            HighDiscountAgentCode code = highDiscountAgentCodeService.getCodeById(discountUserRel.getDiscountAgentCodeId());
            code.setStatus(3);
            highDiscountAgentCodeService.updateCode(code);
        }

        for (int i = 0; i < highOrder.getHighChildOrderList().size(); i++) {
            HighChildOrder childOrder = highOrder.getHighChildOrderList().get(i);
            childOrder.setOrderId(highOrder.getId());
            highChildOrderMapper.insert(childOrder);

            // 商品类型   1:卡卷
            if (childOrder.getGoodsType() == 1) {
                // 查询卡券
                HighCoupon couponDetail = highCouponService.getCouponDetail(childOrder.getGoodsId());
                if (couponDetail.getCouponSource() != 4) {
                    // 查询待销售
                    List<HighCouponCode> list = highCouponCodeService.getNoSaleCode(childOrder.getGoodsId());
                    if (list == null || list.size() == 0) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_STOCK_INSUFFICIENT, "");
                    }
                    list.get(0).setChildOrderId(childOrder.getId());
                    list.get(0).setStatus(99);  // 状态：1.待销售 2.未使用 3.已使用  99.预支付
                    highCouponCodeService.updateCouponCode(list.get(0));
                    childOrder.setExt1(list.get(0).getExt1());
                    highChildOrderMapper.updateByPrimaryKey(childOrder);
                }

                if (couponDetail.getCouponSource().equals(4)) {
                    String code = String.valueOf(new Random().nextInt(899999) + 100000);
                    // 下单请求
                    JSONObject jsonObject = HuiLianTongConfig.recharge(highOrder.getOrderNo() + "_"+code,
                            childOrder.getSaleCount(),
                            couponDetail.getCouponKey(),
                            highOrder.getMemPhone());
                    System.out.println(jsonObject);
                    if (!jsonObject.getString("respCode").equals("0000")) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "下单失败");
                    }
                    JSONObject response = HuiLianTongUnionCardConfig.resolveResponse(jsonObject.getString("data"));
                    if (!response.getString("respCode").equals("0000")) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response.getString("msg"));
                    }
                    childOrder.setExt2(response.getJSONObject("data").getString("rechargeOrderId"));
                    highChildOrderMapper.updateByPrimaryKey(childOrder);
                }

                if (!childOrder.getGiveawayType()) {
                    // 查看是否需要赠送卡卷
                    List<HighCouponHandselModel> handselListByCoupon = highCouponHandselService.getHandselListByCoupon(childOrder.getGoodsId());
                    if (handselListByCoupon != null && handselListByCoupon.size() > 0) {
                        for (HighCouponHandsel highCouponHandsel : handselListByCoupon) {
                            // 查询卡卷信息
                            HighCoupon coupon = highCouponService.getCouponById(highCouponHandsel.getHandselCouponId());
                            if (coupon == null) {
                                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
                            }

                            // 查询赠送卡卷 是否有库存，没有就不赠送
                            if (highCouponCodeService.getStockCountByCoupon(coupon.getId()) > 0) {
                                HighChildOrder highChildOrder = new HighChildOrder();
                                highChildOrder.setOrderId(highOrder.getId());
                                highChildOrder.setGoodsType(1);
                                highChildOrder.setGoodsId(coupon.getId());
                                highChildOrder.setGoodsName(coupon.getCouponName());
                                highChildOrder.setGoodsImg(coupon.getCouponImg());
                                highChildOrder.setGoodsSpecName("默认");
                                highChildOrder.setGoodsPrice(new BigDecimal(0));
                                highChildOrder.setGoodsActualPrice(new BigDecimal("0"));
                                highChildOrder.setSaleCount(1);
                                highChildOrder.setTotalPrice(new BigDecimal(0));
                                highChildOrder.setGiveawayType(true);  // 是否是赠品  0：否   1：是
                                highChildOrder.setChildOrdeStatus(1);   // 1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
                                highChildOrder.setPraiseStatus(0);
                                highOrder.getHighChildOrderList().add(highChildOrder);
                            }
                        }
                    }
                }
            }

            if (childOrder.getGoodsType() == 3) {
                 // 加油站详情
                HighMerchantStore store = highMerchantStoreService.getDetailById(childOrder.getGoodsId());
                if (store == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
                }

                if (store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                    // 查询金猪油品数据
                    JinZhuJiaYouOilNo jzOilNo = JinZhuJiaYouOilNo.getDataByOilNo(Integer.valueOf(childOrder.getGasOilNo()));
                    if (jzOilNo == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法提交订单，未知的油品");
                    }
                    // 创建金猪订单
                    JSONObject jzOrderObject = jinZhuJiaYouService.createOrder(highOrder.getOrderNo(),
                            highOrder.getTotalPrice(),
                            store.getStoreKey(),
                            jzOilNo.getOilNoCode(),
                            childOrder.getGasGunNo(),
                            highOrder.getMemPhone()
                    );
                    childOrder.setGasOrderNo(jzOrderObject.getJSONObject("data").getString("systemOrderNo"));
                    childOrder.setGasPriceChannelPay(jzOrderObject.getJSONObject("data").getBigDecimal("paymentAmount"));
                    highChildOrderMapper.updateByPrimaryKey(childOrder);
                }

            }

            if (childOrder.getGoodsType() == 7) {
                // 查询库存
                List<HighDiscountPackageActual> list = discountPackageActualService.getListByPackageId(childOrder.getGoodsId().intValue(), 1);
                if (list == null || list.size() == 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_STOCK_INSUFFICIENT, "");
                }
                list.get(0).setUserId(highOrder.getMemId().intValue());
                list.get(0).setChildOrderId(childOrder.getId());
                list.get(0).setStatus(2);  // 状态： 1: 待分配 2:预分配（售卖）3:已分配
                discountPackageActualService.updateHighDiscountPackageActual(list.get(0));
            }
        }

        // 积分抵扣，卡券除外
        if (!highOrder.getHighChildOrderList().get(0).getGoodsType().equals(1) && highOrder.getPayGold() != null) {
            // 积分转换成金额
            BigDecimal goldPrice = new BigDecimal(highOrder.getPayGold().toString()).divide(new BigDecimal(100));

            // 积分金额大于应付金额
            if (goldPrice.compareTo(highOrder.getPayablePrice()) == 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付的积分金额大于支付金额");
            }

            // 应付金额 减去 积分抵扣金额 = 支付金额
            highOrder.setPayPrice(highOrder.getPayablePrice().subtract(goldPrice));

            // 积分金额小于应付金额
            if (goldPrice.compareTo(highOrder.getPayablePrice()) == -1) {
                updateOrderDetail(highOrder);

                // 扣除用户积分
                highUserService.goldHandle(highOrder.getMemId(), highOrder.getPayGold(), 2, 2, highOrder.getId(),
                        "抵扣积分订单：" + highOrder.getOrderNo() + "，使用积分:" + highOrder.getPayGold());
            }

            // 积分金额等于应付金额
            if (goldPrice.compareTo(highOrder.getPayablePrice()) == 0) {
                if (StringUtils.isBlank(highOrder.getPayPwd())) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_ENTER_USER_PAY_PWD, "");
                }
                // 查询用户密码
                HighUserPayPassword userPayPwd = highUserPayPasswordService.getDetailByUser(highOrder.getMemId());
                if (userPayPwd == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_SET_USER_PAY_PWD, "");
                }
                // 校验支付密码是否正确
                if (!userPayPwd.getPassword().equals(AESEncodeUtil.aesEncrypt(highOrder.getPayPwd()))) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PAY_PWD_ERROR, "");
                }
                // 扣除用户积分
                highUserService.goldHandle(highOrder.getMemId(), highOrder.getPayGold(), 2, 2, highOrder.getId(),
                        "抵扣积分订单：" + highOrder.getOrderNo() + "，使用积分:" + highOrder.getPayGold());

                highOrder.setOrderStatus(OrderStatusEnum.type3.getType());
                highOrder.setPayRealPrice(highOrder.getPayPrice());
                highOrder.setPayTime(new Date());

                for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                    childOrder.setChildOrdeStatus(3);
                }
                updateOrder(highOrder);

                // 订单完成业务处理
                orderBusinessTransaction(highOrder);
            }
        }

    }

    @Override
    public void updateChildOrder(HighChildOrder highChildOrder) {
        highChildOrderMapper.updateByPrimaryKey(highChildOrder);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void goldPayOrder(Long userId, Long orderId) throws Exception {
        HighOrder highOrder = getOrderById(orderId);
        if (highOrder == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
        }

        // 查询用户
        HighUser highUser = highUserService.findByUserId(highOrder.getMemId());

        // 金币 1：100
        Integer goldNum = new BigDecimal(highOrder.getPayPrice().toString()).multiply(new BigDecimal("100")).intValue();

        String remark = "订单" + highOrder.getOrderNo() + "下单，使用积分：" +  goldNum;
        highUserService.goldHandle(userId, goldNum, 2, 2, highOrder.getId() , remark);

        highOrder.setPayTime(new Date()); // 支付时间
        highOrder.setPayModel(1);         // 支付模式：1 金币，2 第三方平台，3 混合
        highOrder.setPayType(3);          // 支付方式： 1：支付宝  2：微信  3：金币
        highOrder.setPayGold(goldNum);
        highOrder.setPayRealPrice(highOrder.getPayPrice());
        highOrder.setOrderStatus(2);      // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

        for (HighChildOrder highChildOrder : highOrder.getHighChildOrderList()) {
            highChildOrder.setChildOrdeStatus(2);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

            // 商品类型   商品类型   1:卡卷   2:金币充值
            if (highChildOrder.getGoodsType() == 1) {
                // 查询卡券
                HighCoupon coupon = highCouponService.getCouponDetail(highChildOrder.getGoodsId());

                // 是否预约
                if (coupon.getReserveStatus() == true) {
                    HighOrderPre orderPre = new HighOrderPre();
                    orderPre.setCompanyId(coupon.getCompanyId());
                    orderPre.setMerchantId(coupon.getMerchantId());
                    orderPre.setMerchantStoreId(highChildOrder.getStoreId());
                    orderPre.setPreOrderNo(System.currentTimeMillis() + "");
                    orderPre.setOrderId(highOrder.getId());
                    orderPre.setOrderNo(highOrder.getOrderNo());
                    orderPre.setChildOrderId(highChildOrder.getId());
                    orderPre.setPayRealPrice(highOrder.getPayPrice());
                    orderPre.setGoodsType(1);
                    orderPre.setGoodsName(coupon.getCouponName());
                    orderPre.setGoodsId(coupon.getId());
                    orderPre.setPreUserId(highOrder.getMemId());
                    orderPre.setPreUserName(highOrder.getMemName());
                    orderPre.setPreUserPhone(highOrder.getMemPhone());
                    orderPre.setPreUserRemark(highOrder.getRemarks());
                    orderPre.setStatus(1);
                    highOrderPreService.insertOrderPre(orderPre);
                }
                // 贵州高速
                if (coupon.getCouponSource() == 4) {
                    Map<String,Object> push = new HashMap<>();
                    push.put("couTypeCode", coupon.getCouponKey());
                    push.put("distCouCount", highChildOrder.getSaleCount());
                    push.put("userPhone", highUser.getPhone());
                    push.put("thirdUserId", highUser.getUnionId());

                    // 推送给高速
                    JSONObject returnParam = HuiLianTongConfig.costRechargeOrder(highChildOrder.getExt2());
                    System.out.println(returnParam);
                    // 推送记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type6.getType());
                    highGasOrderPush.setOrderNo(highOrder.getOrderNo());
                    highGasOrderPush.setCreateTime(new Date());
                    highGasOrderPush.setCode(returnParam.getString("respCode"));
                    highGasOrderPush.setRequestContent(JSONObject.toJSONString(push));
                    highGasOrderPush.setReturnContent(returnParam.toJSONString());
                    highGasOrderPushMapper.insert(highGasOrderPush);

                    if (returnParam != null && returnParam.getString("respCode").equals("0000")) {
                        // 解密
                        JSONObject jsonObject = HuiLianTongUnionCardConfig.resolveResponse(returnParam.getString("data"));
                        JSONArray dataArray = JSONObject.parseObject(jsonObject.getString("data"), JSONArray.class);
                        for (Object data : dataArray) {
                            JSONObject dataObject = (JSONObject) data;
                            HighCouponCodeOther couponCodeOther = new HighCouponCodeOther();
                            couponCodeOther.setType(1);
                            couponCodeOther.setOrderId(highOrder.getId());
                            couponCodeOther.setChildOrderId(highChildOrder.getId());
                            couponCodeOther.setCouTypeCode(dataObject.getString("couTypeCode"));
                            couponCodeOther.setCouNo(dataObject.getString("couNo"));
                            couponCodeOther.setActiveTime(dataObject.getDate("activeTime"));
                            couponCodeOther.setValidStartDate(dataObject.getDate("validStartDate"));
                            couponCodeOther.setValidEndDate(dataObject.getDate("validEndDate"));
                            couponCodeOther.setStatus(20);
                            couponCodeOther.setCreateTime(new Date());
                            highCouponCodeOtherMapper.insert(couponCodeOther);

                            // 卡卷关联用户
                            HighUserCoupon highUserCoupon = new HighUserCoupon();
                            highUserCoupon.setMerchantId(coupon.getMerchantId());
                            highUserCoupon.setCouponId(coupon.getId());
                            highUserCoupon.setUserId(highOrder.getMemId());
                            highUserCoupon.setCreateTime(new Date());
                            highUserCoupon.setQrCodeImg(dataObject.getString("couNo"));
                            highUserCoupon.setUseEndTime(dataObject.getDate("validEndDate"));
                            highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                            highUserCouponMapper.insert(highUserCoupon);
                        }
                    }
                } else {
                    HighCouponCode code = highCouponCodeService.getCouponCodeByOrderId(highChildOrder.getId());
                    code.setStatus(2);  // 状态：1.待销售 2.未使用 3.已使用  99.预支付
                    code.setReceiveTime(new Date());
                    highCouponCodeService.updateCouponCode(code);

                    // 卡卷关联用户
                    HighUserCoupon highUserCoupon = new HighUserCoupon();
                    highUserCoupon.setMerchantId(code.getMerchantId());
                    highUserCoupon.setCouponId(code.getCouponId());
                    highUserCoupon.setUserId(highOrder.getMemId());
                    highUserCoupon.setCouponCodeId(code.getId());
                    highUserCoupon.setCreateTime(new Date());
                    highUserCoupon.setQrCodeImg(code.getExt1());

                    // 计算使用有效期
                    Calendar userEndTime = Calendar.getInstance();
                    userEndTime.setTime(new Date());
                    userEndTime.set(Calendar.HOUR_OF_DAY, 23);
                    userEndTime.set(Calendar.MINUTE, 59);
                    userEndTime.set(Calendar.SECOND, 59);
                    userEndTime.add(Calendar.DATE, coupon.getRecycleDay());

                    if (userEndTime.getTime().compareTo(code.getUseEndTime()) == 1) {
                        highUserCoupon.setUseEndTime(code.getUseEndTime());
                    } else {
                        highUserCoupon.setUseEndTime(userEndTime.getTime());
                    }
                    highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                    highUserCouponMapper.insert(highUserCoupon);
                }

                // 查询卡券是否有活动
                Map<String, Object> activity = highActivityInfoService.getNewActivityByCouponId(coupon.getId());
                if (activity != null && MapUtils.getLong(activity, "id") != null) {
                    highActivityUserLotteryNumService.addLotteryNum(MapUtils.getLong(activity, "id"), highOrder.getMemId(), 1);
                }
            }

            if (highChildOrder.getGoodsType() == 3) {
                highChildOrder.setChildOrdeStatus(3);
                highOrder.setOrderStatus(3);
                HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(highChildOrder.getGoodsId());

                // 来源类型  1：平台自建   2：团油
                if (store.getSourceType().equals(MerchantStoreSourceType.type1.getNumber())) {

                    // 预存类型  0：非预存  1：预存门店
                    if (store.getPrestoreType() != null && store.getPrestoreType().equals(1)) {
                        Map<String, Object> pushParam = new HashMap<>();
                        pushParam.put("businessType", MerStoreAmountTypeEnum.type2.getType());
                        pushParam.put("storeId", highChildOrder.getGoodsId());
                        pushParam.put("price", highOrder.getTotalPrice());
                        pushParam.put("sourceType", MerStoreAmountSourceTypeEnum.type2.getType());
                        pushParam.put("sourceId", highOrder.getId());
                        pushParam.put("sourceContent", "订单号：" + highOrder.getOrderNo() + ",加油金额：￥" + highOrder.getTotalPrice());
                        pushParam.put("opUserId", highOrder.getMemId());
                        pushParam.put("opUserName", highOrder.getMemName());
                        // 扣预存款
                        this.redisTemplate.boundListOps(MsgTopic.MerStoreAccount.getName()).leftPush(pushParam);
                    }
                } else if (store.getSourceType().equals(MerchantStoreSourceType.type2.getNumber())) {
                    // 推送团油订单
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("gasId", store.getStoreKey());
                    paramMap.put("oilNo", highChildOrder.getGasOilNo());
                    paramMap.put("gunNo", highChildOrder.getGasGunNo());
                    BigDecimal priceGun = highChildOrder.getGasPriceGun();
                    BigDecimal priceVip = highChildOrder.getGasPriceVip();
                    paramMap.put("priceGun", priceGun);  // 枪单价
                    paramMap.put("priceVip", priceVip);  // 优惠价
                    paramMap.put("driverPhone", highOrder.getMemPhone());
                    paramMap.put("thirdSerialNo", highOrder.getOrderNo());
                    paramMap.put("refuelingAmount", highChildOrder.getTotalPrice());

                    // 油品类型 1:汽油:2:柴油;3:天然气
                    if (highChildOrder.getGasOilType() == 1) {
                        paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouGasolineAccount());
                    } else if (highChildOrder.getGasOilType() == 2) {
                        paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouDieselAccount());
                    }
                    JSONObject orderPushObject = TuanYouConfig.refuelingOrderPush(paramMap);
                    // 推送团油订单记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type1.getType());
                    highGasOrderPush.setOrderNo(highOrder.getOrderNo());
                    highGasOrderPush.setCreateTime(new Date());
                    highGasOrderPush.setCode(orderPushObject.getString("code"));
                    highGasOrderPush.setRequestContent(JSONObject.toJSONString(paramMap));
                    highGasOrderPush.setReturnContent(orderPushObject.toJSONString());
                    highGasOrderPushMapper.insert(highGasOrderPush);

                    if (orderPushObject != null && orderPushObject.getString("code").equals("200")) {
                        highChildOrder.setGasOrderNo(orderPushObject.getJSONObject("result").getString("orderNo"));
                    }
                } else if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {

                    // 推送加好油
                    shellGroupService.gasSyncPayment(highOrder.getOrderNo(),
                            store.getStoreKey(),
                            highOrder.getPayTime(),
                            highChildOrder.getTotalPrice(),
                            highChildOrder.getGasOilNo(),
                            highChildOrder.getGasGunNo(),
                            highOrder.getPayablePrice(),
                            highOrder.getDeductionPrice()
                    );

                } else if (store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                    // 推送金猪加油
                    jinZhuJiaYouService.payOrder(highOrder.getOrderNo(), highChildOrder.getGasPriceChannelPay());
                }
            }

            if (highChildOrder.getGoodsType() == 7) {
                HighDiscountPackageActual actual = discountPackageActualService.getDetailByChildOrderId(highChildOrder.getId());
                if (actual != null) {
                    List<HighDiscountPackageDiscountActual> discountList = discountPackageDiscountActualService.getHighDiscountPackageDiscountActualList(actual.getId());
                    for (HighDiscountPackageDiscountActual discount : discountList) {
                        highDiscountUserRelService.receiveDiscount(highOrder.getMemId(), discount.getAgentDiscountCodeId());
                    }
                    HighDiscountPackage discountPackage = discountPackageService.findDiscountPackageById(actual.getDiscountPackageId());
                    HighDiscountPackageRecord record = new HighDiscountPackageRecord();
                    record.setDiscountPackageId(discountPackage.getId());
                    record.setDiscountPackageTitle(discountPackage.getTitle());
                    record.setUsingAttribution(discountPackage.getUsingAttribution());
                    record.setCompanyId(discountPackage.getCompanyId());
                    record.setOrderId(highOrder.getId().intValue());
                    record.setChildOrderId(highChildOrder.getId().intValue());
                    record.setRecordNo(System.currentTimeMillis() + "");
                    record.setSalesType(1);
                    record.setPrice(highOrder.getPayPrice());
                    record.setUserId(highOrder.getMemId().intValue());
                    discountPackageRecordService.insertRecord(record);
                    actual.setAllocationTime(new Date());
                    actual.setStatus(3);  // 状态： 1: 待分配 2:预分配（售卖）3:已分配
                    discountPackageActualService.updateHighDiscountPackageActual(actual);
                }
            }
        }

        updateOrder(highOrder);

        new Thread(() -> {
            if (highOrder.getHighChildOrderList().get(0).getGoodsType().equals(3)) {
                printGasOrder(highOrder.getHighChildOrderList().get(0).getGoodsId(), highOrder, false);

                Map<String, Object> pushMsg = new HashMap<>();
                pushMsg.put("userId", highOrder.getHighChildOrderList().get(0).getGoodsId());

                Map<String, Object> msgContent = new HashMap<>();
                msgContent.put("order", highOrderService.getGasOrderDetail(highOrder.getOrderNo()));
                msgContent.put("voice", baiduVoiceService.text2audio(highOrder.getHighChildOrderList().get(0).getGoodsName() + "，收款：" + highOrder.getTotalPrice() + "元"));
                pushMsg.put("message", JSONObject.toJSONString(msgContent));
                HttpsUtils.doPost("http://127.0.0.1:9901/msg/websocket/websocket", pushMsg, new HashMap<>());
            }
        }).start();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void oilCardPayOrder(Long userCardId, Long orderId) throws Exception {
        HighUserCard userCard = highUserCardService.getDetailById(userCardId);
        if (userCard == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到用户绑定的卡号信息");
        }
        if (!userCard.getType().equals(UserCardType.type2.getType())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "卡片类型");
        }
        // 查询订单信息
        HighOrder order = getOrderById(orderId);
        if (order == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
        }
        if (!order.getOrderStatus().equals(1)) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "订单不处于待支付状态");
        }
        // 油卡扣款
        Map<String, Object> consumeMap = new HashMap<>();
        consumeMap.put("sourceType", OilCardRecordSourceTypeEnum.type2.getType());
        consumeMap.put("sourceId", order.getId());
        consumeMap.put("sourceOrderNo", order.getOrderNo());
        consumeMap.put("sourceContent", "订单号：" + order.getOrderNo() + ",消费：￥" + order.getPayPrice());
        oilCardService.consume(userCard.getCardNo(), order.getPayPrice(), consumeMap);

        order.setMemCardType(userCard.getType());
        order.setMemCardId(userCard.getId());
        order.setMemCardNo(userCard.getCardNo());
        order.setPayTime(new Date()); // 支付时间
        order.setPayModel(OrderPayModelEnum.type4.getType());         // 支付模式：1 金币，2 第三方平台，3 混合
        order.setPayType(OrderPayTypeEnum.type7.getType());          // 支付方式： 1：支付宝  2：微信  3：金币
        order.setPayRealPrice(order.getPayPrice());
        order.setOrderStatus(2);      // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

        // 查询用户
        HighUser highUser = highUserService.findByUserId(order.getMemId());

        for (HighChildOrder highChildOrder : order.getHighChildOrderList()) {
            if (!highChildOrder.getGoodsType().equals(1) && !highChildOrder.getGoodsType().equals(3)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "不支持支付该商品");
            }

            // 商品类型   商品类型   1:卡卷   2:金币充值
            if (highChildOrder.getGoodsType() == 1) {
                highChildOrder.setChildOrdeStatus(2);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

                HighCoupon coupon = highCouponService.getCouponById(highChildOrder.getGoodsId());

                // 是否预约
                if (coupon.getReserveStatus() == true) {
                    HighOrderPre orderPre = new HighOrderPre();
                    orderPre.setCompanyId(coupon.getCompanyId());
                    orderPre.setMerchantId(coupon.getMerchantId());
                    orderPre.setMerchantStoreId(highChildOrder.getStoreId());
                    orderPre.setPreOrderNo(System.currentTimeMillis() + "");
                    orderPre.setOrderId(order.getId());
                    orderPre.setOrderNo(order.getOrderNo());
                    orderPre.setChildOrderId(highChildOrder.getId());
                    orderPre.setPayRealPrice(order.getPayRealPrice());
                    orderPre.setGoodsType(1);
                    orderPre.setGoodsName(coupon.getCouponName());
                    orderPre.setGoodsId(coupon.getId());
                    orderPre.setPreUserId(order.getMemId());
                    orderPre.setPreUserName(order.getMemName());
                    orderPre.setPreUserPhone(order.getMemPhone());
                    orderPre.setPreUserRemark(order.getRemarks());
                    orderPre.setStatus(1);
                    highOrderPreService.insertOrderPre(orderPre);
                }

                // 贵州中石化
                if (coupon.getCouponSource() == 4) {
                    Map<String,Object> push = new HashMap<>();
                    push.put("couTypeCode", coupon.getCouponKey());
                    push.put("distCouCount", highChildOrder.getSaleCount());
                    push.put("userPhone", highUser.getPhone());
                    push.put("thirdUserId", highUser.getUnionId());

                    // 推送给高速
                    JSONObject returnParam = HuiLianTongConfig.costRechargeOrder(highChildOrder.getExt2());
                    if (returnParam != null && returnParam.getString("respCode").equals("0000")) {
                        // 解密
                        JSONObject jsonObject = HuiLianTongUnionCardConfig.resolveResponse(returnParam.getString("data"));
                        JSONArray dataArray = JSONObject.parseObject(jsonObject.getString("data"), JSONArray.class);
                        for (Object data : dataArray) {
                            JSONObject dataObject = (JSONObject) data;
                            HighCouponCodeOther couponCodeOther = new HighCouponCodeOther();
                            couponCodeOther.setType(1);
                            couponCodeOther.setOrderId(order.getId());
                            couponCodeOther.setChildOrderId(highChildOrder.getId());
                            couponCodeOther.setCouTypeCode(dataObject.getString("couTypeCode"));
                            couponCodeOther.setCouNo(dataObject.getString("couNo"));
                            couponCodeOther.setActiveTime(dataObject.getDate("activeTime"));
                            couponCodeOther.setValidStartDate(dataObject.getDate("validStartDate"));
                            couponCodeOther.setValidEndDate(dataObject.getDate("validEndDate"));
                            couponCodeOther.setStatus(20);
                            couponCodeOther.setCreateTime(new Date());
                            highCouponCodeOtherMapper.insert(couponCodeOther);

                            // 卡卷关联用户
                            HighUserCoupon highUserCoupon = new HighUserCoupon();
                            highUserCoupon.setMerchantId(coupon.getMerchantId());
                            highUserCoupon.setCouponId(coupon.getId());
                            highUserCoupon.setUserId(order.getMemId());
                            highUserCoupon.setCreateTime(new Date());
                            highUserCoupon.setQrCodeImg(dataObject.getString("couNo"));
                            highUserCoupon.setUseEndTime(dataObject.getDate("validEndDate"));
                            highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                            highUserCouponMapper.insert(highUserCoupon);
                        }
                    }

                    // 推送记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type6.getType());
                    highGasOrderPush.setOrderNo(order.getOrderNo());
                    highGasOrderPush.setCreateTime(new Date());
                    highGasOrderPush.setCode(returnParam.getString("result"));
                    highGasOrderPush.setRequestContent(JSONObject.toJSONString(push));
                    highGasOrderPush.setReturnContent(returnParam.toJSONString());
                    highGasOrderPushMapper.insert(highGasOrderPush);

                } else {
                    HighCouponCode code = highCouponCodeService.getCouponCodeByOrderId(highChildOrder.getId());
                    code.setStatus(2);  // 状态：1.待销售 2.未使用 3.已使用  99.预支付
                    code.setReceiveTime(new Date());
                    highCouponCodeService.updateCouponCode(code);

                    // 卡卷关联用户
                    HighUserCoupon highUserCoupon = new HighUserCoupon();
                    highUserCoupon.setMerchantId(code.getMerchantId());
                    highUserCoupon.setCouponId(code.getCouponId());
                    highUserCoupon.setUserId(order.getMemId());
                    highUserCoupon.setCouponCodeId(code.getId());
                    highUserCoupon.setCreateTime(new Date());
                    highUserCoupon.setQrCodeImg(code.getExt1());

                    // 计算使用有效期
                    Calendar userEndTime = Calendar.getInstance();
                    userEndTime.setTime(new Date());
                    userEndTime.set(Calendar.HOUR_OF_DAY, 23);
                    userEndTime.set(Calendar.MINUTE, 59);
                    userEndTime.set(Calendar.SECOND, 59);
                    userEndTime.add(Calendar.DATE, coupon.getRecycleDay());
                    if (userEndTime.getTime().compareTo(code.getUseEndTime()) == 1) {
                        highUserCoupon.setUseEndTime(code.getUseEndTime());
                    } else {
                        highUserCoupon.setUseEndTime(userEndTime.getTime());
                    }
                    highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                    highUserCouponMapper.insert(highUserCoupon);
                }

                // 查询卡券是否有活动
                Map<String, Object> activity = highActivityInfoService.getNewActivityByCouponId(coupon.getId());
                if (activity != null && MapUtils.getLong(activity, "id") != null) {
                    highActivityUserLotteryNumService.addLotteryNum(MapUtils.getLong(activity, "id"), order.getMemId(), 1);
                }
            }

            if (highChildOrder.getGoodsType() == 3) {
                highChildOrder.setChildOrdeStatus(3);
                order.setOrderStatus(3);
                HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(highChildOrder.getGoodsId());

                // 来源类型  1：平台自建   2：团油
                if (store.getSourceType().equals(1)) {

                    // 预存类型  0：非预存  1：预存门店
                    if (store.getPrestoreType() != null && store.getPrestoreType().equals(1)) {
                        Map<String, Object> pushParam = new HashMap<>();
                        pushParam.put("businessType", MerStoreAmountTypeEnum.type2.getType());
                        pushParam.put("storeId", highChildOrder.getGoodsId());
                        pushParam.put("price", order.getTotalPrice());
                        pushParam.put("sourceType", MerStoreAmountSourceTypeEnum.type2.getType());
                        pushParam.put("sourceId", order.getId());
                        pushParam.put("sourceContent", "订单号：" + order.getOrderNo() + ",加油金额：￥" + order.getTotalPrice());
                        pushParam.put("opUserId", order.getMemId());
                        pushParam.put("opUserName", order.getMemName());
                        // 扣预存款
                        this.redisTemplate.boundListOps(MsgTopic.MerStoreAccount.getName()).leftPush(pushParam);
                    }

                } else if (store.getSourceType().equals(2)) {
                    // 推送团油订单
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("gasId", store.getStoreKey());
                    paramMap.put("oilNo", highChildOrder.getGasOilNo());
                    paramMap.put("gunNo", highChildOrder.getGasGunNo());
                    BigDecimal priceGun = highChildOrder.getGasPriceGun();
                    BigDecimal priceVip = highChildOrder.getGasPriceVip();
                    paramMap.put("priceGun", priceGun);  // 枪单价
                    paramMap.put("priceVip", priceVip);  // 优惠价
                    paramMap.put("driverPhone", order.getMemPhone());
                    paramMap.put("thirdSerialNo", order.getOrderNo());
                    paramMap.put("refuelingAmount", highChildOrder.getTotalPrice());

                    // 油品类型 1:汽油:2:柴油;3:天然气
                    if (highChildOrder.getGasOilType() == 1) {
                        paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouGasolineAccount());
                    } else if (highChildOrder.getGasOilType() == 2) {
                        paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouDieselAccount());
                    }
                    JSONObject orderPushObject = TuanYouConfig.refuelingOrderPush(paramMap);
                    // 推送团油订单记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type1.getType());
                    highGasOrderPush.setOrderNo(order.getOrderNo());
                    highGasOrderPush.setCreateTime(new Date());
                    highGasOrderPush.setCode(orderPushObject.getString("code"));
                    highGasOrderPush.setRequestContent(JSONObject.toJSONString(paramMap));
                    highGasOrderPush.setReturnContent(orderPushObject.toJSONString());
                    highGasOrderPushMapper.insert(highGasOrderPush);

                    if (orderPushObject != null && orderPushObject.getString("code").equals("200")) {
                        highChildOrder.setGasOrderNo(orderPushObject.getJSONObject("result").getString("orderNo"));
                    }
                } else if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {

                    // 推送加好油
                    shellGroupService.gasSyncPayment(order.getOrderNo(),
                            store.getStoreKey(),
                            order.getPayTime(),
                            highChildOrder.getTotalPrice(),
                            highChildOrder.getGasOilNo(),
                            highChildOrder.getGasGunNo(),
                            order.getPayablePrice(),
                            order.getDeductionPrice()
                    );
                } else if (store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                    // 推送金猪加油
                    jinZhuJiaYouService.payOrder(order.getOrderNo(), highChildOrder.getGasPriceChannelPay());
                }
            }

        }

        updateOrder(order);

        new Thread(() -> {
            if (order.getHighChildOrderList().get(0).getGoodsType().equals(3)) {

                printGasOrder(order.getHighChildOrderList().get(0).getGoodsId(), order, false);

                Map<String, Object> pushMsg = new HashMap<>();
                pushMsg.put("userId", order.getHighChildOrderList().get(0).getGoodsId());

                Map<String, Object> msgContent = new HashMap<>();
                msgContent.put("order", highOrderService.getGasOrderDetail(order.getOrderNo()));
                msgContent.put("voice", baiduVoiceService.text2audio(order.getHighChildOrderList().get(0).getGoodsName() + "，收款：" + order.getTotalPrice() + "元"));
                pushMsg.put("message", JSONObject.toJSONString(msgContent));
                HttpsUtils.doPost("http://127.0.0.1:9901/msg/websocket/websocket", pushMsg, new HashMap<>());
            }
        }).start();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void hltUnionCardPay(Long userCardId, Long orderId) throws Exception {
        HighUserCard userCard = highUserCardService.getDetailById(userCardId);
        if (userCard == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到用户绑定的卡号信息");
        }
        // 查询订单信息
        HighOrder order = getOrderById(orderId);
        if (order == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
        }
        String goodsDesc = "";
        String tranDesc = "";
        String instCode = "11101527";
        String businessType = "hisen_consume";

        if (order.getHighChildOrderList().get(0).getGoodsType() == 1) {
            instCode = "11101526";
            businessType = "sinopec_oil_code";
            goodsDesc = "购买加油券";
            tranDesc = order.getHighChildOrderList().get(0).getGoodsName();

        } else if (order.getHighChildOrderList().get(0).getGoodsType() == 2) {
            goodsDesc = "积分充值" + order.getPayPrice() + "元";
            tranDesc = "嗨森逛积分充值" + order.getPayPrice() + "元";

        } else if (order.getHighChildOrderList().get(0).getGoodsType() == 3) {
            // 查询团油账号余额
            JSONObject accountInfo2JD = TuanYouConfig.queryCompanyAccountInfo2JD();
            JSONArray result = accountInfo2JD.getJSONArray("result");
            for (Object accountObject : result) {
                JSONObject account = (JSONObject) accountObject;
                // 1:汽油:2:柴油;3:天然气
                if (account.getInteger("energyType").equals(order.getHighChildOrderList().get(0).getGasOilType())) {
                    // 支付金额 大于 团油账号余额
                    if (order.getPayPrice().compareTo(account.getBigDecimal("accountBalance")) == 1) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法进行支付，请联系平台客服");
                    }
                }
            }
            goodsDesc = "加油站加" + order.getPayPrice() + "元油";
            tranDesc = "【" + order.getHighChildOrderList().get(0).getGoodsName() + "】加油" + order.getPayPrice() + "元";

        } else if (order.getHighChildOrderList().get(0).getGoodsType() == 7) {
            goodsDesc = "购买优惠券包";
            tranDesc = "购买" + order.getHighChildOrderList().get(0).getGoodsName() + "优惠券包";

        } else {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法支付，请使用其他支付方式");
        }

        // 工会卡支付
        JSONObject consumption = HuiLianTongUnionCardConfig.consumption(order.getOrderNo(), userCard.getCardNo(), order.getPayPrice(), businessType, instCode, goodsDesc, tranDesc);
        System.out.println("工会卡支付响应参数" + consumption.toJSONString());

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orderNo", order.getOrderNo());
        dataMap.put("cardType", "ghk");
        dataMap.put("cardNo", userCard.getCardNo());
        dataMap.put("checkPassword", "N");
        dataMap.put("tranAmount", order.getPayPrice());
        dataMap.put("tranChannel", "HiSen");
        dataMap.put("businessType", businessType);
        dataMap.put("instCode", instCode);
        dataMap.put("goodsDesc", goodsDesc);
        dataMap.put("tranDesc", tranDesc);
        HighGasOrderPush payPush = new HighGasOrderPush();
        payPush.setType(OrderPushType.type5.getType());
        payPush.setOrderNo(userCard.getCardNo());
        payPush.setCreateTime(new Date());
        payPush.setCode(consumption.getString("respCode"));
        payPush.setRequestContent(JSON.toJSONString(dataMap));
        payPush.setReturnContent(consumption.toJSONString());
        highGasOrderPushMapper.insert(payPush);

        if (!consumption.getString("respCode").equals("0000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumption.getString("respMessage"));
        }
        JSONObject consumptionResult = HuiLianTongUnionCardConfig.resolveResponse(consumption.getString("data"));
        if (consumptionResult.getBoolean("success") != true) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumptionResult.getString("message"));
        }

        // 查询用户
        HighUser highUser = highUserService.findByUserId(order.getMemId());

        order.setMemCardId(userCard.getId());
        order.setMemCardNo(userCard.getCardNo());
        order.setMemCardType(userCard.getType());
        order.setPaySerialNo(consumptionResult.getString("orderId")); // 支付流水号
        order.setPayRealPrice(order.getPayPrice()); // 实付金额
        order.setPayTime(new Date()); // 支付时间
        order.setPayModel(2);         // 支付模式：1 金币，2 第三方平台，3 混合
        order.setPayType(4);          // 支付方式： 1：支付宝  2：微信  3：金币  4:汇联通支工会卡
        order.setOrderStatus(2);      // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

        for (HighChildOrder highChildOrder : order.getHighChildOrderList()) {
            // 商品类型   商品类型   1:卡卷   2:金币充值
            if (highChildOrder.getGoodsType() == 1) {
                highChildOrder.setChildOrdeStatus(2);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

                HighCoupon coupon = highCouponService.getCouponById(highChildOrder.getGoodsId());

                // 是否预约
                if (coupon.getReserveStatus() == true) {
                    HighOrderPre orderPre = new HighOrderPre();
                    orderPre.setCompanyId(coupon.getCompanyId());
                    orderPre.setMerchantId(coupon.getMerchantId());
                    orderPre.setMerchantStoreId(highChildOrder.getStoreId());
                    orderPre.setPreOrderNo(System.currentTimeMillis() + "");
                    orderPre.setOrderId(order.getId());
                    orderPre.setOrderNo(order.getOrderNo());
                    orderPre.setChildOrderId(highChildOrder.getId());
                    orderPre.setPayRealPrice(order.getPayRealPrice());
                    orderPre.setGoodsType(1);
                    orderPre.setGoodsName(coupon.getCouponName());
                    orderPre.setGoodsId(coupon.getId());
                    orderPre.setPreUserId(order.getMemId());
                    orderPre.setPreUserName(order.getMemName());
                    orderPre.setPreUserPhone(order.getMemPhone());
                    orderPre.setPreUserRemark(order.getRemarks());
                    orderPre.setStatus(1);
                    highOrderPreService.insertOrderPre(orderPre);
                }

                // 贵州中石化
                if (coupon.getCouponSource() == 4) {
                    Map<String,Object> push = new HashMap<>();
                    push.put("couTypeCode", coupon.getCouponKey());
                    push.put("distCouCount", highChildOrder.getSaleCount());
                    push.put("userPhone", highUser.getPhone());
                    push.put("thirdUserId", highUser.getUnionId());

                    // 推送给高速
                    JSONObject returnParam = HuiLianTongConfig.costRechargeOrder(highChildOrder.getExt2());
                    if (returnParam != null && returnParam.getString("respCode").equals("0000")) {
                        // 解密
                        JSONObject jsonObject = HuiLianTongUnionCardConfig.resolveResponse(returnParam.getString("data"));
                        JSONArray dataArray = JSONObject.parseObject(jsonObject.getString("data"), JSONArray.class);
                        for (Object data : dataArray) {
                            JSONObject dataObject = (JSONObject) data;
                            HighCouponCodeOther couponCodeOther = new HighCouponCodeOther();
                            couponCodeOther.setType(1);
                            couponCodeOther.setOrderId(order.getId());
                            couponCodeOther.setChildOrderId(highChildOrder.getId());
                            couponCodeOther.setCouTypeCode(dataObject.getString("couTypeCode"));
                            couponCodeOther.setCouNo(dataObject.getString("couNo"));
                            couponCodeOther.setActiveTime(dataObject.getDate("activeTime"));
                            couponCodeOther.setValidStartDate(dataObject.getDate("validStartDate"));
                            couponCodeOther.setValidEndDate(dataObject.getDate("validEndDate"));
                            couponCodeOther.setStatus(20);
                            couponCodeOther.setCreateTime(new Date());
                            highCouponCodeOtherMapper.insert(couponCodeOther);

                            // 卡卷关联用户
                            HighUserCoupon highUserCoupon = new HighUserCoupon();
                            highUserCoupon.setMerchantId(coupon.getMerchantId());
                            highUserCoupon.setCouponId(coupon.getId());
                            highUserCoupon.setUserId(order.getMemId());
                            highUserCoupon.setCreateTime(new Date());
                            highUserCoupon.setQrCodeImg(dataObject.getString("couNo"));
                            highUserCoupon.setUseEndTime(dataObject.getDate("validEndDate"));
                            highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                            highUserCouponMapper.insert(highUserCoupon);
                        }
                    }

                    // 推送记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type6.getType());
                    highGasOrderPush.setOrderNo(order.getOrderNo());
                    highGasOrderPush.setCreateTime(new Date());
                    highGasOrderPush.setCode(returnParam.getString("result"));
                    highGasOrderPush.setRequestContent(JSONObject.toJSONString(push));
                    highGasOrderPush.setReturnContent(returnParam.toJSONString());
                    highGasOrderPushMapper.insert(highGasOrderPush);

                } else {
                    HighCouponCode code = highCouponCodeService.getCouponCodeByOrderId(highChildOrder.getId());
                    code.setStatus(2);  // 状态：1.待销售 2.未使用 3.已使用  99.预支付
                    code.setReceiveTime(new Date());
                    highCouponCodeService.updateCouponCode(code);

                    // 卡卷关联用户
                    HighUserCoupon highUserCoupon = new HighUserCoupon();
                    highUserCoupon.setMerchantId(code.getMerchantId());
                    highUserCoupon.setCouponId(code.getCouponId());
                    highUserCoupon.setUserId(order.getMemId());
                    highUserCoupon.setCouponCodeId(code.getId());
                    highUserCoupon.setCreateTime(new Date());
                    highUserCoupon.setQrCodeImg(code.getExt1());

                    // 计算使用有效期
                    Calendar userEndTime = Calendar.getInstance();
                    userEndTime.setTime(new Date());
                    userEndTime.set(Calendar.HOUR_OF_DAY, 23);
                    userEndTime.set(Calendar.MINUTE, 59);
                    userEndTime.set(Calendar.SECOND, 59);
                    userEndTime.add(Calendar.DATE, coupon.getRecycleDay());
                    if (userEndTime.getTime().compareTo(code.getUseEndTime()) == 1) {
                        highUserCoupon.setUseEndTime(code.getUseEndTime());
                    } else {
                        highUserCoupon.setUseEndTime(userEndTime.getTime());
                    }
                    highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                    highUserCouponMapper.insert(highUserCoupon);
                }

                // 查询卡券是否有活动
                Map<String, Object> activity = highActivityInfoService.getNewActivityByCouponId(coupon.getId());
                if (activity != null && MapUtils.getLong(activity, "id") != null) {
                    highActivityUserLotteryNumService.addLotteryNum(MapUtils.getLong(activity, "id"), order.getMemId(), 1);
                }
            }

            if (highChildOrder.getGoodsType() == 2) {
                highChildOrder.setChildOrdeStatus(3);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
                // 金币 1：100
                Integer goldNum = new BigDecimal(highChildOrder.getTotalPrice().toString()).multiply(new BigDecimal("100")).intValue();
                String remark = "订单" + order.getOrderNo() + "积分充值积分：" +  goldNum;
                highUserService.goldHandle(highChildOrder.getGoodsId(), goldNum, 1, 1, highChildOrder.getId() , remark);
            }

            if (highChildOrder.getGoodsType() == 3) {
                highChildOrder.setChildOrdeStatus(3);
                order.setOrderStatus(3);
                HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(highChildOrder.getGoodsId());

                // 来源类型  1：平台自建   2：团油
                if (store.getSourceType().equals(1)) {

                    // 预存类型  0：非预存  1：预存门店
                    if (store.getPrestoreType() != null && store.getPrestoreType().equals(1)) {
                        Map<String, Object> pushParam = new HashMap<>();
                        pushParam.put("businessType", MerStoreAmountTypeEnum.type2.getType());
                        pushParam.put("storeId", highChildOrder.getGoodsId());
                        pushParam.put("price", order.getTotalPrice());
                        pushParam.put("sourceType", MerStoreAmountSourceTypeEnum.type2.getType());
                        pushParam.put("sourceId", order.getId());
                        pushParam.put("sourceContent", "订单号：" + order.getOrderNo() + ",加油金额：￥" + order.getTotalPrice());
                        pushParam.put("opUserId", order.getMemId());
                        pushParam.put("opUserName", order.getMemName());
                        // 扣预存款
                        this.redisTemplate.boundListOps(MsgTopic.MerStoreAccount.getName()).leftPush(pushParam);
                    }
                } else if (store.getSourceType().equals(2)) {
                    // 推送团油订单
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("gasId", store.getStoreKey());
                    paramMap.put("oilNo", highChildOrder.getGasOilNo());
                    paramMap.put("gunNo", highChildOrder.getGasGunNo());
                    BigDecimal priceGun = highChildOrder.getGasPriceGun();
                    BigDecimal priceVip = highChildOrder.getGasPriceVip();
                    paramMap.put("priceGun", priceGun);  // 枪单价
                    paramMap.put("priceVip", priceVip);  // 优惠价
                    paramMap.put("driverPhone", order.getMemPhone());
                    paramMap.put("thirdSerialNo", order.getOrderNo());
                    paramMap.put("refuelingAmount", highChildOrder.getTotalPrice());

                    // 油品类型 1:汽油:2:柴油;3:天然气
                    if (highChildOrder.getGasOilType() == 1) {
                        paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouGasolineAccount());
                    } else if (highChildOrder.getGasOilType() == 2) {
                        paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouDieselAccount());
                    }
                    JSONObject orderPushObject = TuanYouConfig.refuelingOrderPush(paramMap);
                    // 推送团油订单记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type1.getType());
                    highGasOrderPush.setOrderNo(order.getOrderNo());
                    highGasOrderPush.setCreateTime(new Date());
                    highGasOrderPush.setCode(orderPushObject.getString("code"));
                    highGasOrderPush.setRequestContent(JSONObject.toJSONString(paramMap));
                    highGasOrderPush.setReturnContent(orderPushObject.toJSONString());
                    highGasOrderPushMapper.insert(highGasOrderPush);

                    if (orderPushObject != null && orderPushObject.getString("code").equals("200")) {
                        highChildOrder.setGasOrderNo(orderPushObject.getJSONObject("result").getString("orderNo"));
                    }
                } else if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {

                    // 推送加好油
                    shellGroupService.gasSyncPayment(order.getOrderNo(),
                            store.getStoreKey(),
                            order.getPayTime(),
                            highChildOrder.getTotalPrice(),
                            highChildOrder.getGasOilNo(),
                            highChildOrder.getGasGunNo(),
                            order.getPayablePrice(),
                            order.getDeductionPrice()
                    );
                } else if (store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                    // 推送金猪加油
                    jinZhuJiaYouService.payOrder(order.getOrderNo(), highChildOrder.getGasPriceChannelPay());
                }
            }

            if (highChildOrder.getGoodsType() == 7) {
                HighDiscountPackageActual actual = discountPackageActualService.getDetailByChildOrderId(highChildOrder.getId());
                if (actual != null) {
                    List<HighDiscountPackageDiscountActual> discountList = discountPackageDiscountActualService.getHighDiscountPackageDiscountActualList(actual.getId());
                    for (HighDiscountPackageDiscountActual discount : discountList) {
                        highDiscountUserRelService.receiveDiscount(order.getMemId(), discount.getAgentDiscountCodeId());
                    }
                    HighDiscountPackage discountPackage = discountPackageService.findDiscountPackageById(actual.getDiscountPackageId());
                    HighDiscountPackageRecord record = new HighDiscountPackageRecord();
                    record.setDiscountPackageId(discountPackage.getId());
                    record.setDiscountPackageTitle(discountPackage.getTitle());
                    record.setUsingAttribution(discountPackage.getUsingAttribution());
                    record.setCompanyId(discountPackage.getCompanyId());
                    record.setOrderId(order.getId().intValue());
                    record.setChildOrderId(highChildOrder.getId().intValue());
                    record.setRecordNo(System.currentTimeMillis() + "");
                    record.setSalesType(1);
                    record.setPrice(order.getPayPrice());
                    record.setUserId(order.getMemId().intValue());
                    discountPackageRecordService.insertRecord(record);
                    actual.setAllocationTime(new Date());
                    actual.setStatus(3);  // 状态： 1: 待分配 2:预分配（售卖）3:已分配
                    discountPackageActualService.updateHighDiscountPackageActual(actual);
                }
            }
        }

        updateOrder(order);

        new Thread(() -> {
            if (order.getHighChildOrderList().get(0).getGoodsType().equals(3)) {
                printGasOrder(order.getHighChildOrderList().get(0).getGoodsId(), order, false);

                Map<String, Object> pushMsg = new HashMap<>();
                pushMsg.put("userId", order.getHighChildOrderList().get(0).getGoodsId());

                Map<String, Object> msgContent = new HashMap<>();
                msgContent.put("order", highOrderService.getGasOrderDetail(order.getOrderNo()));
                msgContent.put("voice", baiduVoiceService.text2audio(order.getHighChildOrderList().get(0).getGoodsName() + "，收款：" + order.getTotalPrice() + "元"));
                pushMsg.put("message", JSONObject.toJSONString(msgContent));
                HttpsUtils.doPost("http://127.0.0.1:9901/msg/websocket/websocket", pushMsg, new HashMap<>());
            }
        }).start();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateOrder(HighOrder highOrder) {
        highOrderMapper.updateByPrimaryKey(highOrder);

        for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
            highChildOrderMapper.updateByPrimaryKey(childOrder);
        }
    }

    @Override
    public void updateOrderDetail(HighOrder highOrder) {
        highOrderMapper.updateByPrimaryKey(highOrder);
    }

    @Override
    public void orderBusinessTransaction(HighOrder order) throws Exception {
        for (HighChildOrder highChildOrder : order.getHighChildOrderList()) {
            // 商品类型   商品类型   1:卡卷   2:金币充值
            if (highChildOrder.getGoodsType() == 1) {
                highChildOrder.setChildOrdeStatus(2);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

                HighCoupon coupon = highCouponService.getCouponById(highChildOrder.getGoodsId());

                // 是否预约
                if (coupon.getReserveStatus() == true) {
                    HighOrderPre orderPre = new HighOrderPre();
                    orderPre.setCompanyId(coupon.getCompanyId());
                    orderPre.setMerchantId(coupon.getMerchantId());
                    orderPre.setMerchantStoreId(highChildOrder.getStoreId());
                    orderPre.setPreOrderNo(System.currentTimeMillis() + "");
                    orderPre.setOrderId(order.getId());
                    orderPre.setOrderNo(order.getOrderNo());
                    orderPre.setChildOrderId(highChildOrder.getId());
                    orderPre.setPayRealPrice(order.getPayRealPrice());
                    orderPre.setGoodsType(1);
                    orderPre.setGoodsName(coupon.getCouponName());
                    orderPre.setGoodsId(coupon.getId());
                    orderPre.setPreUserId(order.getMemId());
                    orderPre.setPreUserName(order.getMemName());
                    orderPre.setPreUserPhone(order.getMemPhone());
                    orderPre.setPreUserRemark(order.getRemarks());
                    orderPre.setStatus(1);
                    highOrderPreService.insertOrderPre(orderPre);
                }

                // 贵州中石化
                if (coupon.getCouponSource() == 4) {
                    Map<String, Object> push = new HashMap<>();
                    push.put("couTypeCode", coupon.getCouponKey());
                    push.put("distCouCount", highChildOrder.getSaleCount());
                    push.put("userPhone", order.getMemPhone());
                    push.put("thirdUserId", order.getMerchId());

                    // 推送给高速
                    JSONObject returnParam = HuiLianTongConfig.costRechargeOrder(highChildOrder.getExt2());
                    if (returnParam != null && returnParam.getString("respCode").equals("0000")) {
                        // 解密
                        JSONObject jsonObject = HuiLianTongUnionCardConfig.resolveResponse(returnParam.getString("data"));
                        JSONArray dataArray = JSONObject.parseObject(jsonObject.getString("data"), JSONArray.class);
                        for (Object data : dataArray) {
                            JSONObject dataObject = (JSONObject) data;
                            HighCouponCodeOther couponCodeOther = new HighCouponCodeOther();
                            couponCodeOther.setType(1);
                            couponCodeOther.setOrderId(order.getId());
                            couponCodeOther.setChildOrderId(highChildOrder.getId());
                            couponCodeOther.setCouTypeCode(dataObject.getString("couTypeCode"));
                            couponCodeOther.setCouNo(dataObject.getString("couNo"));
                            couponCodeOther.setActiveTime(dataObject.getDate("activeTime"));
                            couponCodeOther.setValidStartDate(dataObject.getDate("validStartDate"));
                            couponCodeOther.setValidEndDate(dataObject.getDate("validEndDate"));
                            couponCodeOther.setStatus(20);
                            couponCodeOther.setCreateTime(new Date());
                            highCouponCodeOtherMapper.insert(couponCodeOther);

                            // 卡卷关联用户
                            HighUserCoupon highUserCoupon = new HighUserCoupon();
                            highUserCoupon.setMerchantId(coupon.getMerchantId());
                            highUserCoupon.setCouponId(coupon.getId());
                            highUserCoupon.setUserId(order.getMemId());
                            highUserCoupon.setCreateTime(new Date());
                            highUserCoupon.setQrCodeImg(dataObject.getString("couNo"));
                            highUserCoupon.setUseEndTime(dataObject.getDate("validEndDate"));
                            highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                            highUserCouponMapper.insert(highUserCoupon);
                        }
                    }

                    // 推送记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type6.getType());
                    highGasOrderPush.setOrderNo(order.getOrderNo());
                    highGasOrderPush.setCreateTime(new Date());
                    highGasOrderPush.setCode(returnParam.getString("result"));
                    highGasOrderPush.setRequestContent(JSONObject.toJSONString(push));
                    highGasOrderPush.setReturnContent(returnParam.toJSONString());
                    highGasOrderPushMapper.insert(highGasOrderPush);

                } else {
                    HighCouponCode code = highCouponCodeService.getCouponCodeByOrderId(highChildOrder.getId());
                    code.setStatus(2);  // 状态：1.待销售 2.未使用 3.已使用  99.预支付
                    code.setReceiveTime(new Date());
                    highCouponCodeService.updateCouponCode(code);

                    // 卡卷关联用户
                    HighUserCoupon highUserCoupon = new HighUserCoupon();
                    highUserCoupon.setMerchantId(code.getMerchantId());
                    highUserCoupon.setCouponId(code.getCouponId());
                    highUserCoupon.setUserId(order.getMemId());
                    highUserCoupon.setCouponCodeId(code.getId());
                    highUserCoupon.setCreateTime(new Date());
                    highUserCoupon.setQrCodeImg(code.getExt1());

                    // 计算使用有效期
                    Calendar userEndTime = Calendar.getInstance();
                    userEndTime.setTime(new Date());
                    userEndTime.set(Calendar.HOUR_OF_DAY, 23);
                    userEndTime.set(Calendar.MINUTE, 59);
                    userEndTime.set(Calendar.SECOND, 59);
                    userEndTime.add(Calendar.DATE, coupon.getRecycleDay());
                    if (userEndTime.getTime().compareTo(code.getUseEndTime()) == 1) {
                        highUserCoupon.setUseEndTime(code.getUseEndTime());
                    } else {
                        highUserCoupon.setUseEndTime(userEndTime.getTime());
                    }
                    highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                    highUserCouponMapper.insert(highUserCoupon);
                }

                // 查询卡券是否有活动
                Map<String, Object> activity = highActivityInfoService.getNewActivityByCouponId(coupon.getId());
                if (activity != null && MapUtils.getLong(activity, "id") != null) {
                    highActivityUserLotteryNumService.addLotteryNum(MapUtils.getLong(activity, "id"), order.getMemId(), 1);
                }
            }

            if (highChildOrder.getGoodsType() == 2) {
                highChildOrder.setChildOrdeStatus(3);  // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消

                // 金币 1：100
                Integer goldNum = new BigDecimal(highChildOrder.getTotalPrice().toString()).multiply(new BigDecimal("100")).intValue();
                String remark = "订单" + order.getOrderNo() + "积分充值积分：" +  goldNum;
                highUserService.goldHandle(highChildOrder.getGoodsId(), goldNum, 1, 1, highChildOrder.getId(), remark);
            }

            if (highChildOrder.getGoodsType() == 3) {
                highChildOrder.setChildOrdeStatus(3);
                order.setOrderStatus(3);
                HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(highChildOrder.getGoodsId());

                // 来源类型  1：平台自建   2：团油
                if (store.getSourceType().equals(1)) {

                    // 预存类型  0：非预存  1：预存门店
                    if (store.getPrestoreType() != null && store.getPrestoreType().equals(1)) {
                        Map<String, Object> pushParam = new HashMap<>();
                        pushParam.put("businessType", MerStoreAmountTypeEnum.type2.getType());
                        pushParam.put("storeId", highChildOrder.getGoodsId());
                        pushParam.put("price", order.getTotalPrice());
                        pushParam.put("sourceType", MerStoreAmountSourceTypeEnum.type2.getType());
                        pushParam.put("sourceId", order.getId());
                        pushParam.put("sourceContent", "订单号：" + order.getOrderNo() + ",加油金额：￥" + order.getTotalPrice());
                        pushParam.put("opUserId", order.getMemId());
                        pushParam.put("opUserName", order.getMemName());
                        // 扣预存款
                        this.redisTemplate.boundListOps(MsgTopic.MerStoreAccount.getName()).leftPush(pushParam);
                    }

                    // 打印小票
                    printGasOrder(highChildOrder.getGoodsId(), order, false);

                } else if (store.getSourceType().equals(2)) {
                    // 推送团油订单
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("gasId", store.getStoreKey());
                    paramMap.put("oilNo", highChildOrder.getGasOilNo());
                    paramMap.put("gunNo", highChildOrder.getGasGunNo());
                    BigDecimal priceGun = highChildOrder.getGasPriceGun();
                    BigDecimal priceVip = highChildOrder.getGasPriceVip();
                    paramMap.put("priceGun", priceGun);  // 枪单价
                    paramMap.put("priceVip", priceVip);  // 优惠价
                    paramMap.put("driverPhone", order.getMemPhone());
                    paramMap.put("thirdSerialNo", order.getOrderNo());
                    paramMap.put("refuelingAmount", highChildOrder.getTotalPrice());

                    // 油品类型 1:汽油:2:柴油;3:天然气
                    if (highChildOrder.getGasOilType() == 1) {
                        paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouGasolineAccount());
                    } else if (highChildOrder.getGasOilType() == 2) {
                        paramMap.put("accountNo", CommonSysConst.getSysConfig().getTuanYouDieselAccount());
                    }
                    JSONObject orderPushObject = TuanYouConfig.refuelingOrderPush(paramMap);
                    // 推送团油订单记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type1.getType());
                    highGasOrderPush.setOrderNo(order.getOrderNo());
                    highGasOrderPush.setCreateTime(new Date());
                    highGasOrderPush.setCode(orderPushObject.getString("code"));
                    highGasOrderPush.setRequestContent(JSONObject.toJSONString(paramMap));
                    highGasOrderPush.setReturnContent(orderPushObject.toJSONString());
                    highGasOrderPushMapper.insert(highGasOrderPush);

                    if (orderPushObject != null && orderPushObject.getString("code").equals("200")) {
                        highChildOrder.setGasOrderNo(orderPushObject.getJSONObject("result").getString("orderNo"));
                    }
                } else if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {

                    // 推送加好油
                    shellGroupService.gasSyncPayment(order.getOrderNo(),
                            store.getStoreKey(),
                            order.getPayTime(),
                            highChildOrder.getTotalPrice(),
                            highChildOrder.getGasOilNo(),
                            highChildOrder.getGasGunNo(),
                            order.getPayablePrice(),
                            order.getDeductionPrice()
                    );
                } else if (store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                    // 推送金猪加油
                    JSONObject jzOrderObject = jinZhuJiaYouService.payOrder(order.getOrderNo(), highChildOrder.getGasPriceChannelPay());
                    if (jzOrderObject == null
                            || !jzOrderObject.getString("type").equals("OK")
                            || !jzOrderObject.getInteger("status").equals(200)) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jzOrderObject.getString("title"));
                    }
                }
            }

            if (highChildOrder.getGoodsType() == 7) {
                HighDiscountPackageActual actual = discountPackageActualService.getDetailByChildOrderId(highChildOrder.getId());
                if (actual != null) {
                    List<HighDiscountPackageDiscountActual> discountList = discountPackageDiscountActualService.getHighDiscountPackageDiscountActualList(actual.getId());
                    for (HighDiscountPackageDiscountActual discount : discountList) {
                        highDiscountUserRelService.receiveDiscount(order.getMemId(), discount.getAgentDiscountCodeId());
                    }
                    HighDiscountPackage discountPackage = discountPackageService.findDiscountPackageById(actual.getDiscountPackageId());
                    HighDiscountPackageRecord record = new HighDiscountPackageRecord();
                    record.setDiscountPackageId(discountPackage.getId());
                    record.setDiscountPackageTitle(discountPackage.getTitle());
                    record.setUsingAttribution(discountPackage.getUsingAttribution());
                    record.setCompanyId(discountPackage.getCompanyId());
                    record.setOrderId(order.getId().intValue());
                    record.setChildOrderId(highChildOrder.getId().intValue());
                    record.setRecordNo(System.currentTimeMillis() + "");
                    record.setSalesType(1);
                    record.setPrice(order.getPayPrice());
                    record.setUserId(order.getMemId().intValue());
                    discountPackageRecordService.insertRecord(record);
                    actual.setAllocationTime(new Date());
                    actual.setStatus(3);  // 状态： 1: 待分配 2:预分配（售卖）3:已分配
                    discountPackageActualService.updateHighDiscountPackageActual(actual);
                }
            }
        }
    }

    @Override
    public Integer getUndoneChildOrder(Long orderId) {
        HighOrder order = getOrderById(orderId);
        Integer count = 0;
        for (HighChildOrder childOrder : order.getHighChildOrderList()) {
            if (childOrder.getChildOrdeStatus() != 3) {
                count++;
            }
        }
        return count;
    }

    @Override
    public HighChildOrder getChildOrderById(Long childOrderId) {
        return highChildOrderMapper.selectByPrimaryKey(childOrderId);
    }

    @Override
    public HighChildOrder getChildOrderByUserGoods(Long userId, Integer goodsType, Long goodsId) {
        HighChildOrderExample example = new HighChildOrderExample();
        example.createCriteria().andMemIdEqualTo(userId).andGoodsTypeEqualTo(goodsType).andGoodsIdEqualTo(goodsId);
        List<HighChildOrder> list = highChildOrderMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<HighChildOrder> getChildOrderByOrder(Long orderId) {
        HighChildOrderExample example = new HighChildOrderExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        return highChildOrderMapper.selectByExample(example);
    }

    @Override
    public List<HighChildOrder> getChildOrderList(Map<String, Object> map) {
        HighChildOrderExample example = new HighChildOrderExample();
        HighChildOrderExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "memId") != null) {
            criteria.andOrderIdEqualTo(MapUtils.getLong(map, "memId"));
        }

        if (MapUtils.getLong(map, "childOrdeStatus") != null) {
            criteria.andChildOrdeStatusEqualTo(MapUtils.getInteger(map, "childOrdeStatus"));
        }

        if (MapUtils.getString(map, "childOrdeStatusList") != null) {
            String[] childOrdeStatusLists = MapUtils.getString(map, "childOrdeStatusList").split(",");
            List<Integer> integerList = new ArrayList<>();
            for (String status : childOrdeStatusLists) {
                integerList.add(Integer.parseInt(status));
            }
            criteria.andChildOrdeStatusIn(integerList);
        }

        if (MapUtils.getLong(map, "goodsType") != null) {
            criteria.andGoodsTypeEqualTo(MapUtils.getInteger(map, "goodsType"));
        }

        if (MapUtils.getLong(map, "goodsId") != null) {
            criteria.andGoodsIdEqualTo(MapUtils.getLong(map, "goodsId"));
        }

        if (MapUtils.getLong(map, "giveawayType") != null) {
            criteria.andGiveawayTypeEqualTo(MapUtils.getBoolean(map, "giveawayType"));
        }
        return highChildOrderMapper.selectByExample(example);
    }

    @Override
    public HighOrder getOrderById(Long id) {
        HighOrder order = highOrderMapper.selectByPrimaryKey(id);
        if (order == null) {
            return null;
        }
        order.setHighChildOrderList(getChildOrderByOrder(order.getId()));
        if (order.getMemDiscountId() != null) {
            order.setHighDiscount(highDiscountUserRelService.getRelById(order.getMemDiscountId()).getHighDiscount());
        }
        return order;
    }

    @Override
    public HighOrder getOrderByOrderNo(String orderNo) {
        HighOrderExample example = new HighOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);

        List<HighOrder> list = highOrderMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return getOrderById(list.get(0).getId());
        }
        return null;
    }

    @Override
    public List<HighOrderData> getOrderBList(Map<String, Object> map) {
        return highOrderMapperExt.selectOrderDataList(map);
    }

    @Override
    public List<HighOrder> getOrderList(Map<String, Object> map) {
        HighOrderExample example = new HighOrderExample();
        HighOrderExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "memId") != null) {
            criteria.andMemIdEqualTo(MapUtils.getLong(map, "memId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "status"))) {
            String[] statuses = MapUtils.getString(map, "status").split(",");
            List<Integer> list = new ArrayList<>();
            for (String status : statuses) {
                list.add(Integer.parseInt(status));
            }
            criteria.andOrderStatusIn(list);
        }

        if (MapUtils.getString(map, "orderNo") != null) {
            criteria.andOrderNoEqualTo(MapUtils.getString(map, "orderNo"));
        }

        if (MapUtils.getString(map, "phone") != null) {
            criteria.andMemPhoneEqualTo(MapUtils.getString(map, "phone"));
        }
        if (MapUtils.getString(map, "merchId") != null) {
            criteria.andMerchIdEqualTo(MapUtils.getString(map, "merchId"));
        }

        if (MapUtils.getLong(map, "identificationCode") != null) {
            criteria.andIdentificationCodeEqualTo(MapUtils.getLong(map, "identificationCode"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "createTimeS")) && StringUtils.isNotBlank(MapUtils.getString(map, "createTimeE"))) {
            criteria.andCreateTimeBetween(
                    DateUtil.format(MapUtils.getString(map, "createTimeS"), "yyyy-MM-dd HH:mm:ss"),
                    DateUtil.format(MapUtils.getString(map, "createTimeE"), "yyyy-MM-dd HH:mm:ss"));
        }

        example.setOrderByClause("create_time desc");
        List<HighOrder> list = highOrderMapper.selectByExample(example);
        if (list.size() > 0) {
            for (HighOrder order : list) {
                order.setHighChildOrderList(getChildOrderByOrder(order.getId()));
            }
        }

        return list;
    }

    @Override
    public List<HighOrderModel> getGoodsOrderModelList(Map<String, Object> map) throws Exception {

        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeS") != null) {
            map.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeE") != null) {
            map.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        return highOrderMapper.selectGoodsOrderList(map);
    }

    @Override
    public List<HighOrderModel> getGasOrderModelList(Map<String, Object> map) throws Exception {

        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeS") != null) {
            map.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeE") != null) {
            map.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        return highOrderMapper.selectGasOrderList(map);
    }

    @Override
    public List<HighOrderModel> getKfcOrderModelList(Map<String, Object> map) throws Exception {
        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeS") != null) {
            map.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeE") != null) {
            map.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        return highOrderMapper.selectKfcOrderList(map);
    }

    @Override
    public List<HighOrderModel> getCinemaOrderList(Map<String, Object> map) throws Exception {
        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeS") != null) {
            map.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeE") != null) {
            map.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        return highOrderMapper.selectCinemaOrderList(map);
    }

    @Override
    public List<HighOrderModel> getMobileOrderList(Map<String, Object> map) throws Exception {
        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeS") != null) {
            map.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeE") != null) {
            map.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        return highOrderMapper.getMobileOrderList(map);
    }

    @Override
    public List<HighOrderModel> getOrderListByIdCode(String identificationCode, Map<String, Object> map) throws Exception {
        map.put("identificationCode", identificationCode);

        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeS") != null) {
            map.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeE") != null) {
            map.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        return highOrderMapper.getOrderListByIdCode(map);
    }

    @Override
    public List<HighOrder> getCloseOrder() {
        return highOrderMapperExt.getCloseOrder();
    }

    @Override
    public HighOrder getConsumeOrderByDiscountCode(Long discountCodeId) {

        // 查询优惠券有没有被使用
        HighDiscountUserRelExample example = new HighDiscountUserRelExample();
        example.createCriteria().andDiscountAgentCodeIdEqualTo(discountCodeId).andStatusEqualTo(2);
        List<HighDiscountUserRel> userRels = highDiscountUserRelMapper.selectByExample(example);

        if (userRels.size() > 0) {
            HighOrderExample orderExample = new HighOrderExample();
            orderExample.createCriteria().andMemDiscountIdEqualTo(userRels.get(0).getId());
            List<HighOrder> orderList = highOrderMapper.selectByExample(orderExample);
            if (orderList.size() > 0) {
                HighOrder highOrder = orderList.get(0);
                highOrder.setHighChildOrderList(getChildOrderByOrder(highOrder.getId()));
                return highOrder;
            }
        }
        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void childOrderComplete(Long childOrderId) {
        HighChildOrder childOrder = highChildOrderMapper.selectByPrimaryKey(childOrderId);
        if (childOrder == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        childOrder.setChildOrdeStatus(3);
        highChildOrderMapper.updateByPrimaryKey(childOrder);

        // 查询未完成的子订单数量
        Integer count = getUndoneChildOrder(childOrder.getOrderId());
        if (count == 0) {
            HighOrder order = getOrderById(childOrder.getOrderId());
            order.setOrderStatus(3);
            order.setFinishTime(new Date());
            highOrderMapper.updateByPrimaryKey(order);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void cancelOrder(Long orderId) {
        HighOrder order = getOrderById(orderId);
        if (order != null) {
            if (order.getOrderStatus() != 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }
            order.setOrderStatus(5); // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
            order.setCancelTime(new Date());

            for (HighChildOrder highChildOrder : order.getHighChildOrderList()) {
                // 商品类型   1:卡卷   2:金币充值
                if (highChildOrder.getGoodsType() == 1) {
                    // 查询卡卷详情
                    HighCouponCode couponCode = highCouponCodeService.getCouponCodeByOrderId(highChildOrder.getId());
                    if (couponCode != null) {
                        couponCode.setChildOrderId(null);
                        couponCode.setStatus(1);   // 状态：1.待销售 2.未使用 3.已使用  99.预支付
                        highCouponCodeService.updateCouponCode(couponCode);
                    }
                }

                if (highChildOrder.getGoodsType() == 7) {
                    HighDiscountPackageActual actual = discountPackageActualService.getDetailByChildOrderId(highChildOrder.getId());
                    if (actual != null) {
                        actual.setChildOrderId(null);
                        actual.setUserId(null);
                        actual.setStatus(1);
                        discountPackageActualService.updateHighDiscountPackageActual(actual);
                    }
                }

                highChildOrder.setChildOrdeStatus(5); // 子订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
            }

            if (order.getMemDiscountId() != null) {
                HighDiscountUserRel rel = highDiscountUserRelService.getRelById(order.getMemDiscountId());
                if (rel != null) {
                    rel.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                    rel.setUseTime(null);
                    highDiscountUserRelService.updateDiscountUserRel(rel);

                    HighDiscountAgentCode code = highDiscountAgentCodeService.getCodeById(rel.getDiscountAgentCodeId());
                    code.setStatus(2);
                    highDiscountAgentCodeService.updateCode(code);
                }
            }

            if (order.getPayGold() != null) {
                // 积分返回
                String remark = "订单" + order.getOrderNo() + "取消，退还积分：" +  order.getPayGold();
                highUserService.goldHandle(order.getMemId(), order.getPayGold(), 1, 3, order.getId() , remark);
            }

            updateOrder(order);
        }
    }

    @Override
    public Integer countOrderByUserId(Long memId, Integer status) {

        HighOrderExample example = new HighOrderExample();
        HighOrderExample.Criteria criteria = example.createCriteria();

        criteria.andMemIdEqualTo(memId);
        criteria.andOrderStatusEqualTo(status);
        return highOrderMapper.selectByExample(example).size();
    }

    @Override
    public Integer countUnusedDiscountByUserId(Long userId, Integer status) {

        HighDiscountUserRelExample example = new HighDiscountUserRelExample();
        HighDiscountUserRelExample.Criteria criteria = example.createCriteria();

        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }

        if (status != null) {
            criteria.andStatusEqualTo(status);
        }

        example.setOrderByClause("create_time desc");
        return highDiscountUserRelMapper.selectByExample(example).size();
    }

    @Override
    public List<HighOrder> getAlreadyPaidMobileOrder() {
        return highOrderMapperExt.selectAlreadyPaidMobileOrder();
    }

    @Override
    public List<HighOrder> getAlreadyPaidKfcOrder() {
        return highOrderMapperExt.selectAlreadyPaidKfcOrder();
    }

    @Override
    public List<HighOrder> getAlreadyPaidCinemaOrder() {
        return highOrderMapperExt.selectAlreadyPaidCinemaOrder();
    }

    @Override
    public List<HighOrder> getTest() {
        return highOrderMapperExt.selectTest();
    }


    @Override
    public List<Map<String, Object>> getFinishGasOrder() {
        return highOrderMapper.selectFinishGasOrder();
    }

    @Override
    public HighChildOrder getChildOrderByPresentation(Long orderId) {
        HighChildOrderExample example = new HighChildOrderExample();
        example.createCriteria().andOrderIdEqualTo(orderId).andGiveawayTypeEqualTo(false);
        return highChildOrderMapper.selectByExample(example).get(0);
    }


    @Override
    public List<HighOrderModel> selectDiscountPackageOrderList(Map<String, Object> map) throws Exception {

        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeS") != null) {
            map.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "payTimeE") != null) {
            map.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        return highOrderMapper.selectDiscountPackageOrderList(map);
    }

    @Override
    public OrderCountModel orderByIndex(Integer code) {
        return highOrderMapper.orderByIndex(code);
    }

    @Override
    public OrderCountModel HLTOrderByIndex(Integer code) {
        return highOrderMapper.HLTOrderByIndex(code);
    }

    @Override
    public List<HighOrderModel> HLTOrderByList(Integer code) throws Exception {

        Map<String, Object> map = new HashMap<>();

        map.put("identificationCode", code);
        map.put("orderStatus", "2,3");
        map.put("payType", "1,2,3,5");

        return highOrderMapper.selectOrderList(map);
    }

    @Override
    public BigDecimal orderPriceTotal(Map<String, Object> map) {
        if (highOrderMapper.orderPriceTotal(map) == null) {
            return new BigDecimal(0);
        }
        return highOrderMapper.orderPriceTotal(map);
    }

    @Override
    public BigDecimal rechargePriceTotal(Map<String, Object> map) {
        if (highOrderMapper.rechargePriceTotal(map) == null) {
            return new BigDecimal(0);
        }
        return highOrderMapper.rechargePriceTotal(map);
    }

    @Override
    public Long orderPriceCount(Map<String, Object> map) {
        return highOrderMapper.orderPriceCount(map);
    }

    @Override
    public Long rechargePriceCount(Map<String, Object> map) {
        return highOrderMapper.rechargePriceCount(map);
    }

    @Override
    public List<OrderSumModel> getOrderSumOrderByDate() {
        return highOrderMapper.getOrderSumOrderByDate();
    }

    @Override
    public List<OrderSumModel> getOrderSumRechargeByDate() {
        return highOrderMapper.getOrderSumRechargeByDate();
    }

    @Override
    public List<DateCountModel> getDateCountByUser() {
        return highOrderMapper.getDateCountByUser();
    }

    @Override
    public List<DateCountModel> getDateCountByOrder() {
        return highOrderMapper.getDateCountByOrder();
    }

    @Override
    public List<DateCountModel> getDateCountByRecharge() {
        return highOrderMapper.getDateCountByRecharge();
    }

    @Override
    public int getGasTheDayOrderNum(Long userId) {
        return 0;
    }

    @Override
    public TyOrderCountModel TyOrderStatistics(Map<String, Object> map) throws Exception {

        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }

        TyOrderCountModel tyOrderCountModel = new TyOrderCountModel();

        if (highOrderMapper.TyOrderCount(map) != null) {
            tyOrderCountModel = highOrderMapper.TyOrderCount(map);
            tyOrderCountModel.setOrderNum(highOrderMapper.TyOrderNum(map));
        }
        Integer[] priceArr = {100, 200, 300, 400, 20000};

        List<TyOrderGorpModel> priceList = new ArrayList<>();

        for (Integer s : priceArr) {
            TyOrderGorpModel tyOrderGorpModel = new TyOrderGorpModel();
            map.put("totalPrice", s);
            tyOrderGorpModel.setName(priceName(s));
            tyOrderGorpModel.setValue(highOrderMapper.TyOrderNumByPrice(map));
            priceList.add(tyOrderGorpModel);
        }

        priceList.get(1).setValue(priceList.get(1).getValue() - priceList.get(0).getValue());
        priceList.get(2).setValue(priceList.get(2).getValue() - priceList.get(1).getValue() - priceList.get(0).getValue());
        priceList.get(3).setValue(priceList.get(3).getValue() - priceList.get(2).getValue() - priceList.get(1).getValue() - priceList.get(0).getValue());
        priceList.get(4).setValue(priceList.get(4).getValue() - priceList.get(3).getValue() - priceList.get(2).getValue() - priceList.get(1).getValue() - priceList.get(0).getValue());


        tyOrderCountModel.setPriceGorp(priceList);
        tyOrderCountModel.setPayTypeGorp(highOrderMapper.TyOrderNumGroupByPayType(map));
        tyOrderCountModel.setGasOilNoGorp(highOrderMapper.TyOrderNumGroupByGasOilNo(map));

        return tyOrderCountModel;
    }

    @Override
    public Map<String, Object> getGasTheDayOrderCount(Long storeId, String status) {
        return highOrderMapperExt.selectGasTheDayOrderCount(storeId, status);
    }

    @Override
    public Map<String, Object> getGasStaffTheDayOrderCount(Long gasStaffId, String status) {
        return highOrderMapperExt.selectGasStaffTheDayOrderCount(gasStaffId,status);
    }

    @Override
    public Map<String, Object> getGasHistoryOrderCount(Long storeId, String status) {
        return highOrderMapperExt.selectGasHistoryOrderCount(storeId, status);
    }

    @Override
    public Map<String, Object> getGasStaffHistoryOrderCount(Long gasStaffId, String status) {
        return highOrderMapperExt.selectGasStaffHistoryOrderCount(gasStaffId,status);
    }

    @Override
    public List<GasOrderModel> getGasOrderList(Map<String, Object> param) throws Exception {
        if (MapUtils.getLong(param, "createTimeS") != null) {
            param.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(param, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }
        if (MapUtils.getLong(param, "createTimeE") != null) {
            param.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(param, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }
        if (MapUtils.getLong(param, "payTimeS") != null) {
            param.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(param, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }
        if (MapUtils.getLong(param, "payTimeE") != null) {
            param.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(param, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }
        return highOrderMapperExt.selectGasStoreOrderList(param);
    }

    @Override
    public Map<String, Object> countGasOrder(Map<String, Object> param) throws Exception {
        if (MapUtils.getLong(param, "createTimeS") != null) {
            param.put("createTimeS", DateUtil.date2String(new Date(MapUtils.getLong(param, "createTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }
        if (MapUtils.getLong(param, "createTimeE") != null) {
            param.put("createTimeE", DateUtil.date2String(new Date(MapUtils.getLong(param, "createTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }
        if (MapUtils.getLong(param, "payTimeS") != null) {
            param.put("payTimeS", DateUtil.date2String(new Date(MapUtils.getLong(param, "payTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }
        if (MapUtils.getLong(param, "payTimeE") != null) {
            param.put("payTimeE", DateUtil.date2String(new Date(MapUtils.getLong(param, "payTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }
        return highOrderMapperExt.countGasStoreOrder(param);
    }

    @Override
    public GasOrderModel getGasOrderDetail(String orderNo) {
        Map<String, Object> param = new HashMap<>();
        param.put("orderNo", orderNo);
        List<GasOrderModel> list = highOrderMapperExt.selectGasStoreOrderList(param);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void printGasOrder(Long gasId, HighOrder order, boolean makeUp) {
        if (order == null) {
            return;
        }

        for (HighChildOrder childOrder : order.getHighChildOrderList()) {
            if (childOrder.getGoodsType().equals(3)) {

                // 查询油站云打印设备
                List<HighDevice> deviceList = deviceService.getDeviceListByStoreId(gasId);
                for (HighDevice device : deviceList) {
                    Map<String, Object> receiptMap = new HashMap<>();
                    receiptMap.put("receiptTop", device.getReceiptTop());
                    receiptMap.put("receiptSource", device.getReceiptSource());
                    receiptMap.put("receiptBottom", device.getReceiptBottom());

                    if (device.getType().equals(DeviceTypeEnum.type1.getType())) {
                        new Thread(() -> {
                            try {
                                SpPrinterConfig sp = new SpPrinterConfig();

                                String printStr =  SpPrinterTemplate.oilCashierStubTemp(
                                        childOrder.getGoodsName(),
                                        order.getOrderNo(),
                                        DateUtil.date2String(order.getPayTime(), "yyyy-MM-dd HH:mm:ss"),
                                        order.getMemPhone(),
                                        childOrder.getGasGunNo(),
                                        childOrder.getGasOilNo(),
                                        childOrder.getGasOilLiters().toString(),
                                        order.getTotalPrice().toString(),
                                        receiptMap,
                                        makeUp
                                );
                                sp.print(device.getDeviceSn(), printStr, 1);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }).start();
                    }

                    if (device.getType().equals(DeviceTypeEnum.type2.getType())) {
                        new Thread(() -> {
                            try {
                                mqttProviderConfig.publish(2, false, device.getDeviceImei(),
                                      ZkcPrinterTemplate.oilCashierStubTemp(
                                        childOrder.getGoodsName(),
                                        order.getOrderNo(),
                                        DateUtil.date2String(order.getPayTime(), "yyyy-MM-dd HH:mm:ss"),
                                        order.getMemPhone(),
                                        "嗨森逛",
                                        childOrder.getGasGunNo(),
                                        childOrder.getGasOilNo(),
                                        childOrder.getGasOilLiters().toString(),
                                        order.getTotalPrice().toString(),
                                        receiptMap,
                                        makeUp
                                ));
                            } catch (Exception e) {
                                e.getMessage();
                            }
                        }).start();
                    }
                }
            }
        }
    }

    public String priceName(Integer num) {

        switch (num) {
            case 100:
                return "100元以下";
            case 200:
                return "100-200元";
            case 300:
                return "200-300元";
            case 400:
                return "300-400元";
            default:
                return "400元以上";
        }
    }

    @Override
    @Transactional(
            isolation = Isolation.SERIALIZABLE,
            propagation = Propagation.REQUIRES_NEW)
    public HighOrder insertThirdProduct(JSONObject object) throws Exception {

        HighOrder highOrder = new HighOrder();
        highOrder.setMerchId(object.getString("mchId"));
        highOrder.setWhetherRebate(false);
        HighUser user = highUserService.findByUserId(object.getLong("userId"));

        JSONObject jsonObject = null;
        JSONObject requestContent = null;

        // 积分抵扣金额
        BigDecimal integralPrice = new BigDecimal(0);
        // 优惠券抵扣金额
        BigDecimal discountPrice = new BigDecimal(0);
        // 实际支付金额
        BigDecimal orderPayPrice = new BigDecimal(0);
        // 市场金额
        BigDecimal marketPrice = new BigDecimal(0);

        // 查询详单订单的实际
        JSONObject productDetail = thirdProductConfig.getThirdPartyByDetail(object.getInteger("platformId"), object.getInteger("productType"), object.getLong("companyId"));


        highOrder.setProductType(object.getInteger("productType"));

        JSONObject userToken = QianZhuConfig.getTokenV2(user.getId().toString(), user.getName(), user.getPhone());

        if (!userToken.getBoolean("success")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
        }

        // 1 星巴克 2 肯德基 3 会员充值
        if (object.getInteger("productType") == 1) {



            List<String> List = new ArrayList<>();

            JSONArray array = object.getJSONArray("orderItems");

            for (Object o : array) {
                JSONObject object1 = (JSONObject) o;
                Map<String, Object> contentMap = new LinkedHashMap<>();
                if (!object1.getString("productId").equals("")) {
                    contentMap.put("productId", object1.getString("productId"));
                }
                if (!object1.getString("cupSize").equals("")) {
                    contentMap.put("cupSize", object1.getString("cupSize"));
                }
                if (!object1.getString("temperature").equals("")) {
                    contentMap.put("temperature", object1.getString("temperature"));
                }
                if (!object1.getString("cream").equals("")) {
                    contentMap.put("cream", object1.getString("cream"));
                }
                if (!object1.getString("espresso").equals("")) {
                    contentMap.put("espresso", object1.getString("espresso"));
                }
                if (!object1.getString("milk").equals("")) {
                    contentMap.put("milk", object1.getString("milk"));
                }
                if (!object1.getString("milkBubble").equals("")) {
                    contentMap.put("milkBubble", object1.getString("milkBubble"));
                }
                if (!object1.getString("num").equals("")) {
                    contentMap.put("num", object1.getString("num"));
                }
                List.add(JSON.toJSONString(contentMap));
            }

            // 下单
            jsonObject = QianZhuConfig.starbucksOrders(user.getId().toString(), object.getString("storeCode"), List.toString().replace(" ", ""), object.getString("customerMobile"));

            // 判断下单是否成功
            if (!Objects.equals(jsonObject.getString("code"), "200")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
            }

            if (!jsonObject.getBoolean("success")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
            }

            // 根据订单号查询订单详情
            JSONObject orderObject = QianZhuConfig.starbucksOrderByOrderNo(jsonObject.getJSONObject("data").getString("orderNo"));

            // 判断是否成功
            if (!orderObject.getBoolean("success")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
            }

            // 插入订单内容
            highOrder.setOrderNo(jsonObject.getJSONObject("data").getString("orderNo"));
            highOrder.setRegionId(object.getString("regionId"));
            highOrder.setCompanyId(object.getLong("companyId"));
            highOrder.setCreateTime(new Date());
            highOrder.setMemId(user.getId());
            highOrder.setMemName(user.getName());
            highOrder.setMemPhone(user.getPhone());
            highOrder.setOrderStatus(1);
            highOrderMapper.insert(highOrder);

            // 获取星巴克订单内容
            JSONArray starbucksOrder = orderObject.getJSONObject("data").getJSONArray("orderItems");

            for (Object starbucksObject : starbucksOrder) {
                JSONObject childObject = (JSONObject) starbucksObject;
                HighChildOrder childOrder = new HighChildOrder();
                childOrder.setOrderId(highOrder.getId());
                childOrder.setChildOrdeStatus(1);
                childOrder.setGoodsType(9);
                childOrder.setStoreId(object.getLong("storeCode"));
                childOrder.setGoodsId(object.getLong("productId"));
                childOrder.setStoreAddress(childObject.getString("storeAddress"));
                childOrder.setStoreName(childObject.getString("storeName"));
                childOrder.setGoodsName(childObject.getString("productName"));
                childOrder.setGoodsImg(childObject.getString("imgUrl"));
                childOrder.setSaleCount(childObject.getInteger("quantity"));
                childOrder.setGoodsPrice(childObject.getBigDecimal("marketPrice"));

                // 计算利润
                BigDecimal profitPrice = childObject.getBigDecimal("marketPrice").multiply(productDetail.getBigDecimal("priceDiscount").divide(new BigDecimal(100)));
                // 计算子订单支付金额
                BigDecimal childPrice = childObject.getBigDecimal("unitPrice").add(profitPrice).setScale(2 , RoundingMode.HALF_UP);
                if (childPrice.compareTo(childObject.getBigDecimal("marketPrice")) > 0) {
                    childPrice = childObject.getBigDecimal("marketPrice");
                }
                if (object.getLong("memDiscountId") != null) {
                    childOrder.setGoodsActualPrice(childObject.getBigDecimal("marketPrice"));
                } else {
                    childOrder.setGoodsActualPrice(childPrice);
                }
                childPrice = childPrice.multiply(childObject.getBigDecimal("quantity"));
                // 计算总订单实际支付金额
                orderPayPrice = orderPayPrice.add(childPrice);
                // 计算市场价金额
                marketPrice = marketPrice.add(childObject.getBigDecimal("marketPrice").multiply(childObject.getBigDecimal("quantity")));
                childOrder.setTotalPrice(childPrice);
                highChildOrderMapper.insert(childOrder);
            }


        } else if (object.getInteger("productType") == 2) {
            if (object.getInteger("eatType") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请选择就餐方式！");
            }
            // 下单
            jsonObject = QianZhuConfig.createKfcOrder(object.getInteger("eatType"), object.getString("storeCode"), object.getString("customerMobile"), object.getString("orderItems"), object.getString("userId"));

            // 判断下单是否成功
            if (!Objects.equals(jsonObject.getString("code"), "10000")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
            }

            // 根据订单号查询订单详情
            JSONObject orderObject = QianZhuConfig.getKfcOrderByOrderNo(jsonObject.getJSONObject("data").getString("orderNo"));
            // 判断下单是否成功
            if (!orderObject.getBoolean("success")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
            }

            // 插入订单内容
            highOrder.setOrderNo(jsonObject.getJSONObject("data").getString("orderNo"));
            highOrder.setRegionId(object.getString("regionId"));
            highOrder.setCompanyId(object.getLong("companyId"));
            highOrder.setCreateTime(new Date());
            highOrder.setMemId(user.getId());
            highOrder.setMemName(user.getName());
            highOrder.setMemPhone(user.getPhone());
            highOrder.setOrderStatus(1);

            highOrderMapper.insert(highOrder);

            // 获取肯德基订单内容
            JSONArray kfcOrder = orderObject.getJSONObject("data").getJSONObject("kfcPlaceOrder").getJSONArray("items");
            for (Object kfcObject : kfcOrder) {
                JSONObject childObject = (JSONObject) kfcObject;
                HighChildOrder childOrder = new HighChildOrder();
                childOrder.setOrderId(highOrder.getId());
                childOrder.setChildOrdeStatus(1);
                childOrder.setGoodsType(4);
                childOrder.setGoodsId(object.getLong("productId"));
                childOrder.setStoreAddress(orderObject.getJSONObject("data").getJSONObject("kfcPlaceOrder").getString("storeAddress"));
                childOrder.setStoreName(orderObject.getJSONObject("data").getJSONObject("kfcPlaceOrder").getString("storeName"));
                childOrder.setGoodsName(childObject.getString("productName"));
                childOrder.setGoodsImg(childObject.getString("imageUrl"));
                childOrder.setSaleCount(childObject.getInteger("quantity"));
                childOrder.setGoodsPrice(childObject.getBigDecimal("originPrice"));

                // 计算利润
                BigDecimal profitPrice = childObject.getBigDecimal("originPrice").multiply(productDetail.getBigDecimal("priceDiscount").divide(new BigDecimal(100)));
                // 计算子订单支付金额
                BigDecimal childPrice = childObject.getBigDecimal("price").add(profitPrice).setScale(2 , RoundingMode.HALF_UP);
                if (childPrice.compareTo(childObject.getBigDecimal("originPrice")) > 0) {
                    childPrice = childObject.getBigDecimal("originPrice");
                }

                if (object.getLong("memDiscountId") != null) {
                    childOrder.setGoodsActualPrice(childObject.getBigDecimal("originPrice"));
                } else {
                    childOrder.setGoodsActualPrice(childPrice);
                }
                childPrice = childPrice.multiply(childObject.getBigDecimal("quantity"));
                // 计算总订单实际支付金额
                orderPayPrice = orderPayPrice.add(childPrice);
                // 计算市场价金额
                marketPrice = marketPrice.add(childObject.getBigDecimal("originPrice").multiply(childObject.getBigDecimal("quantity")));
                childOrder.setTotalPrice(childPrice);
                highChildOrderMapper.insert(childOrder);

            }
        } else if (object.getInteger("productType") == 3) {
            ApiMemberProduct memberProduct = apiMemberProductService.findById(object.getLong("goodsId"));

            if (memberProduct == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前产品不可购买");
            }
            object.put("productId", memberProduct.getProductId());
            // 插入订单内容
            highOrder.setOrderNo("HF" + DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + IDGenerator.nextId(5));
            highOrder.setRegionId(object.getString("regionId"));
            highOrder.setCompanyId(object.getLong("companyId"));
            highOrder.setCreateTime(new Date());
            highOrder.setMemId(user.getId());
            highOrder.setMemName(user.getName());
            highOrder.setMemPhone(user.getPhone());
            highOrder.setOrderStatus(1);

            // 计算实际支付金额
            orderPayPrice = memberProduct.getCostPrice().add(memberProduct.getPrice().multiply(productDetail.getBigDecimal("priceDiscount").divide(new BigDecimal(100)))).setScale(2, RoundingMode.HALF_UP);
            if (orderPayPrice.compareTo(memberProduct.getPrice()) > 0) {
                orderPayPrice = memberProduct.getPrice();
            }
            // 计算市场价金额
            marketPrice = memberProduct.getPrice();

            highOrderMapper.insert(highOrder);

            HighChildOrder childOrder = new HighChildOrder();
            childOrder.setOrderId(highOrder.getId());
            childOrder.setChildOrdeStatus(1);
            childOrder.setGoodsType(10);
            childOrder.setStoreId(object.getLong("storeCode"));
            childOrder.setGoodsId(memberProduct.getId());
            childOrder.setGoodsName(memberProduct.getName());
            childOrder.setSaleCount(1);
            childOrder.setGoodsPrice(marketPrice);
            if (object.getLong("memDiscountId") != null) {
                childOrder.setGoodsActualPrice(marketPrice);
                childOrder.setTotalPrice(marketPrice);
            } else {
                childOrder.setGoodsActualPrice(orderPayPrice);
                childOrder.setTotalPrice(orderPayPrice);
            }

            highChildOrderMapper.insert(childOrder);

        }

        // 定义优惠券
        HighDiscountUserRel highDiscountUserRel = null;
        // 判断是否有优惠券
        if (object.getLong("memDiscountId") != null) {
            orderPayPrice = marketPrice;
            // 优惠券信息
            highDiscountUserRel = highDiscountUserRelService.getRelById(object.getLong("memDiscountId"));
            highOrder.setMemDiscountId(object.getLong("memDiscountId"));
            if (highDiscountUserRel == null || highDiscountUserRel.getStatus() != 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "优惠券状态错误");
            }
            if (!highDiscountUserRel.getHighDiscount().getUseScope().equals(DiscountUseScope.type4.getType())
                    && !highDiscountUserRel.getHighDiscount().getUseScope().equals(DiscountUseScope.type5.getType())
                    && !highDiscountUserRel.getHighDiscount().getUseScope().equals(DiscountUseScope.type6.getType())
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法使用此优惠券");
            }
        }

        // 优惠券抵扣
        if (highDiscountUserRel != null) {
            highOrder.setMemDiscountName(highDiscountUserRel.getHighDiscount().getDiscountName());
            // 卡卷类型  1：满减  2：抵扣   3：折扣
            if (highDiscountUserRel.getHighDiscount().getDiscountType() == 1) {
                // 如果商品支付总额 小于 满减价格
                if (orderPayPrice.compareTo(highDiscountUserRel.getHighDiscount().getDiscountCondition()) < 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_MEMBER_ERROR, "订单未达到" + highDiscountUserRel.getHighDiscount().getDiscountCondition() + "元,无法使用此优惠券");
                }
                // 满减额度
                discountPrice = highDiscountUserRel.getHighDiscount().getDiscountPrice();
            }

            // 卡卷类型  1：满减  2：抵扣   3：折扣
            if (highDiscountUserRel.getHighDiscount().getDiscountType() == 2) {
                // 满减额度
                discountPrice = highDiscountUserRel.getHighDiscount().getDiscountPrice();

            }

            // 卡卷类型  1：满减  2：抵扣   3：折扣
            if (highDiscountUserRel.getHighDiscount().getDiscountType() == 3) {
                // 满减额度
                discountPrice = orderPayPrice.subtract(orderPayPrice.multiply(highDiscountUserRel.getHighDiscount().getDiscountPrice())).setScale(2, RoundingMode.HALF_UP);
            }
        }

        // 使用优惠券
        if (highOrder.getMemDiscountId() != null) {
            HighDiscountUserRel discountUserRel = highDiscountUserRelService.getRelById(highOrder.getMemDiscountId());
            discountUserRel.setUseTime(new Date()); // 使用时间
            discountUserRel.setStatus(2);  //状态  0:已过期  1：未使用  2：已使用
            highDiscountUserRelService.updateDiscountUserRel(discountUserRel);

            HighDiscountAgentCode code = highDiscountAgentCodeService.getCodeById(discountUserRel.getDiscountAgentCodeId());
            code.setStatus(3);
            highDiscountAgentCodeService.updateCode(code);
        }

        // 使用积分
        // 判断积分数量是否大于0
        if (object.getLong("integralNum") != null) {
            if (object.getLong("integralNum") > 0 && productDetail.getBigDecimal("integralDiscount").compareTo(new BigDecimal("0")) > 0) {

                // 判断用户积分是否够
                if (object.getLong("integralNum") > user.getGold()) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "用户积分不足");
                }

                // 积分抵扣金额
                integralPrice = object.getBigDecimal("integralNum").divide(new BigDecimal(100).setScale(2, RoundingMode.HALF_UP));
                // 最高可抵扣金额
                BigDecimal maxIntegralDeductionPrice = orderPayPrice.multiply(productDetail.getBigDecimal("integralDiscount")).divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                // 判读积分是否大于限制额度
                if (maxIntegralDeductionPrice.compareTo(integralPrice) < 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "订单最大抵扣积分金额：" + maxIntegralDeductionPrice);
                }

                // 判断积分抵扣比例是否为100% 并且积分数量是否可以抵扣最后的支付金额
                if (productDetail.getBigDecimal("integralDiscount").compareTo(new BigDecimal(100)) == 0 && integralPrice.compareTo(orderPayPrice) == 0) {
                    // 查询用户支付密码
                    HighUserPayPassword userPayPassword = highUserPayPasswordService.getDetailByUser(object.getLong("userId"));
                    if (userPayPassword == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_SET_USER_PAY_PWD, "");
                    }
                    if (StringUtils.isBlank(object.getString("password"))) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_ENTER_USER_PAY_PWD, "");
                    }
                    // 校验支付密码
                    if (!AESEncodeUtil.aesEncrypt(object.getString("password")).equals(userPayPassword.getPassword())) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PAY_PWD_ERROR, "");
                    }
                }
            }
        }

        highOrder.setDeductionPrice(discountPrice);
        highOrder.setPayGold(object.getInteger("integralNum"));

        highOrder.setTotalPrice(orderPayPrice);
        highOrder.setPayPrice(orderPayPrice.subtract(discountPrice));

        if (integralPrice.compareTo(new BigDecimal(0)) > 0) {
            highOrder.setPayPrice(highOrder.getPayPrice().subtract(integralPrice));

            String remark = "订单" + highOrder.getOrderNo() + "下单，使用积分：" +  object.getInteger("integralNum");
            highUserService.goldHandle(highOrder.getMemId(), object.getInteger("integralNum"), 2, 2, highOrder.getId() , remark);
        }

        // 判断积分支付是否扣完金额
        if (highOrder.getPayPrice().compareTo(new BigDecimal(0)) == 0) {
            highOrder.setOrderStatus(2);
            highOrder.setPayModel(1);
            highOrder.setPayType(3);
            highOrder.setPayTime(new Date());
            highOrder.setPaySerialNo("HF" + DateUtil.date2String(new Date(), "yyyyMMddHHmmss") + IDGenerator.nextId(5));
        } else {
            highOrder.setOrderStatus(1);
        }

        highOrder.setPayRealPrice(highOrder.getPayPrice());
        highOrder.setRemarks(object.getString("customerMobile"));

        highOrderMapper.updateByPrimaryKey(highOrder);

        if (highOrder.getOrderStatus() == 2) {
            HighOrder highOrderList = highOrderService.getOrderById(highOrder.getId());
            for (HighChildOrder childOrder : highOrderList.getHighChildOrderList()) {
                childOrder.setChildOrdeStatus(2);
            }

            // 推送订单记录
            HighGasOrderPush highGasOrderPush = new HighGasOrderPush();

            // 1 星巴克 2 肯德基 3:第三方会员充值
            if (object.getInteger("productType") == 1) {
                highGasOrderPush.setType(OrderPushType.type8.getType());
                requestContent = QianZhuConfig.starbucksOrdersPay(highOrder.getOrderNo());
            } else if (object.getInteger("productType") == 2){
                highGasOrderPush.setType(OrderPushType.type4.getType());
                requestContent = QianZhuConfig.payKfcOrder(highOrder.getOrderNo());
            } else if (object.getInteger("productType") == 3){
                highGasOrderPush.setType(OrderPushType.type9.getType());
                requestContent = QianZhuConfig.insertV2(object.getString("productId") , highOrder.getOrderNo() , object.getString("customerMobile"));
            }

            highGasOrderPush.setOrderNo(highOrder.getOrderNo());
            highGasOrderPush.setCreateTime(new Date());
            highGasOrderPush.setRequestContent(highOrder.getOrderNo());
            highGasOrderPush.setReturnContent(requestContent.toJSONString());
            highGasOrderPushMapper.insert(highGasOrderPush);

        }
        return highOrder;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void hltUnionCardPayByThirdProduct(HighUserCard userCard, Long orderId) throws Exception {
        String goodsDesc = "";
        String tranDesc = "";
        String instCode = "11101527";
        String businessType = "hisen_consume";

        // 查询订单信息
        HighOrder order = getOrderById(orderId);
        if (order == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
        }

        if (order.getHighChildOrderList().get(0).getGoodsType() == 4) {
            goodsDesc = "购买肯德基产品";
            tranDesc = goodsDesc + order.getPayRealPrice() + "元";
        } else if (order.getHighChildOrderList().get(0).getGoodsType() == 9) {
            goodsDesc = "购买星巴克产品";
            tranDesc = goodsDesc + order.getPayRealPrice() + "元";
        } else if (order.getHighChildOrderList().get(0).getGoodsType() == 10) {
            goodsDesc = "购买会员充值产品";
            tranDesc = goodsDesc + order.getPayRealPrice() + "元";
        } else {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法支付，请使用其他支付方式");
        }

        // 工会卡支付
        JSONObject consumption = HuiLianTongUnionCardConfig.consumption(order.getOrderNo(), userCard.getCardNo(), order.getPayRealPrice(), businessType, instCode, goodsDesc, tranDesc);
        System.out.println("工会卡支付响应参数" + consumption.toJSONString());

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orderNo", order.getOrderNo());
        dataMap.put("cardType", "ghk");
        dataMap.put("cardNo", userCard.getCardNo());
        dataMap.put("checkPassword", "N");
        dataMap.put("tranAmount", order.getPayRealPrice());
        dataMap.put("tranChannel", "HiSen");
        dataMap.put("businessType", businessType);
        dataMap.put("instCode", instCode);
        dataMap.put("goodsDesc", goodsDesc);
        dataMap.put("tranDesc", tranDesc);
        HighGasOrderPush payPush = new HighGasOrderPush();
        payPush.setType(OrderPushType.type5.getType());
        payPush.setOrderNo(order.getOrderNo());
        payPush.setCreateTime(new Date());
        payPush.setCode(consumption.getString("respCode"));
        payPush.setRequestContent(JSON.toJSONString(dataMap));
        payPush.setReturnContent(consumption.toJSONString());
        highGasOrderPushMapper.insert(payPush);

        if (!consumption.getString("respCode").equals("0000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumption.getString("respMessage"));
        }
        JSONObject consumptionResult = HuiLianTongUnionCardConfig.resolveResponse(consumption.getString("data"));
        if (!consumptionResult.getBoolean("success")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumptionResult.getString("message"));
        }
        order.setPaySerialNo(consumptionResult.getString("orderId")); // 支付流水号
        order.setOrderStatus(2);
        order.setMemCardNo(userCard.getCardNo());
        order.setPayType(4);

        order.setPayTime(new Date()); // 支付时间
        updateOrder(order);

        HighGasOrderPush orderPush = new HighGasOrderPush();
        JSONObject returnObject;

        for (HighChildOrder childOrder : order.getHighChildOrderList()) {
            childOrder.setChildOrdeStatus(2);
        }
        if (order.getHighChildOrderList().get(0).getGoodsType() == 4) {
            orderPush.setType(OrderPushType.type4.getType());
            returnObject = QianZhuConfig.payKfcOrder(order.getOrderNo());
        } else if (order.getHighChildOrderList().get(0).getGoodsType() == 9) {
            orderPush.setType(OrderPushType.type8.getType());
            returnObject = QianZhuConfig.starbucksOrdersPay(order.getOrderNo());
        } else if (order.getHighChildOrderList().get(0).getGoodsType() == 10){
            orderPush.setType(OrderPushType.type9.getType());
            ApiMemberProduct memberProduct = apiMemberProductService.findById(order.getHighChildOrderList().get(0).getGoodsId());
            returnObject = QianZhuConfig.insertV2(memberProduct.getProductId() , order.getOrderNo() , order.getRemarks());
        } else {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法支付，请使用其他支付方式");
        }

        orderPush.setOrderNo(order.getOrderNo());
        orderPush.setCreateTime(new Date());
        orderPush.setRequestContent(JSON.toJSONString(dataMap));
        orderPush.setReturnContent(returnObject.toJSONString());
        highGasOrderPushMapper.insert(orderPush);

    }

    @Override
    public List<HighOrder> getThirdOrder() {
        return highOrderMapper.getThirdOrder();
    }


    @Override
    public void thirdOrderToRefund(Long orderId) throws Exception {

        HighOrder order = highOrderService.getOrderById(orderId);


        // 101.待支付 102.已支付 100.已完成 104.已取消 105.已退款
        if (order.getOrderStatus() != 2) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法退款，订单不处于已支付状态");
        }



        // 微信退款
        if (order.getPayType() == 2) {
            Map<String, String> param = new HashMap<>();
            param.put("appid", "wx637bd6f7314daa46");
            param.put("mch_id", "1289663601");
            param.put("sub_mch_id", "1614670195");
            param.put("nonce_str", WxUtils.makeNonStr());
            param.put("transaction_id", order.getPaySerialNo());
            param.put("out_refund_no", "HFR" + new Date().getTime());
            param.put("total_fee", String.valueOf(order.getPayRealPrice().multiply(new BigDecimal("100")).intValue()));
            param.put("refund_fee", String.valueOf(order.getPayRealPrice().multiply(new BigDecimal("100")).intValue()));
            param.put("sign_type", "HMAC-SHA256");

            String signStr = WxUtils.generateSignature(param, "Skufk5oi85wDFGl888i6wsRSTkdd5df5", WXPayConstants.SignType.HMACSHA256);
            param.put("sign", signStr);

            String resultXmL = doRefundRequest(param.get("mch_id"), WxUtils.mapToXml(param));
            OrderRefundModel orderRefundModel = XmlUtil.getObjectFromXML(resultXmL, OrderRefundModel.class);
            if (orderRefundModel.getResult_code().equals("SUCCESS")) {
                order.setRefundTime(new Date());
                order.setRefundNo(orderRefundModel.getOut_refund_no());
                order.setRefundPrice(new BigDecimal(orderRefundModel.getRefund_fee()).divide(new BigDecimal("100")));
                order.setOrderStatus(4);
                order.setRefundTime(new Date());
                for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                    childOrder.setChildOrdeStatus(4);
                }
                updateOrder(order);
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败！错误代码：" + orderRefundModel.getErr_code() + ",错误描述" + orderRefundModel.getErr_code_des());
            }
        }

        // 工会卡退款
        if (order.getPayType() == 4) {
            JSONObject jsonObject = HuiLianTongUnionCardConfig.refund("HFR" + new Date().getTime(), order.getOrderNo());

            if (jsonObject == null) {
                jsonObject = HuiLianTongUnionCardConfig.refund("HFR" + new Date().getTime(), order.getOrderNo());
            }

            JSONObject dataObject = HuiLianTongUnionCardConfig.resolveResponse(jsonObject.getString("data"));

            if (dataObject.getBoolean("success") || Objects.equals(dataObject.getString("message"), "原交易已撤销,不可再次操作")) {
                order.setRefundTime(new Date());
                order.setRefundNo("HFR" + new Date().getTime());
                order.setRefundPrice(order.getPayRealPrice());
                order.setOrderStatus(4);
                order.setRefundTime(new Date());
                for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                    childOrder.setChildOrdeStatus(4);
                }
                updateOrder(order);

            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, dataObject.getString("message"));
            }

            // 商户预充值 帐户退款
            if (order.getPayType() == 7) {

                Map<String , Object> map = new HashMap<>();
                map.put("orderNo" , order.getOrderNo());
                map.put("amountType" , 1);
                map.put("sourceType" , 2);

                if ( apiAmountRecordService.getApiAmountRecordByList(map).size() == 1) {

                    ApiMerchants apiMerchants = apiMerchantsService.findByMchId(order.getMerchId());
                    // 插入金额记录
                    // 变更前金额
                    BigDecimal beforeAmount = apiMerchants.getAmounts();
                    // 计算金额
                    apiMerchants.setAmounts(apiMerchants.getAmounts().add(order.getPayPrice()));
                    // 变更后金额
                    BigDecimal afterAmount = apiMerchants.getAmounts();

                    apiMerchantsService.updateApiMerchants(apiMerchants);

                    ApiAmountRecord apiAmountRecord = new ApiAmountRecord();

                    apiAmountRecord.setCreateTime(new Date());
                    apiAmountRecord.setUpdateTime(new Date());
                    apiAmountRecord.setMchId(order.getMerchId());

                    apiAmountRecord.setStatus(100);
                    apiAmountRecord.setAmount(order.getPayPrice());
                    apiAmountRecord.setAfterAmount(afterAmount);
                    apiAmountRecord.setBeforeAmount(beforeAmount);
                    apiAmountRecord.setAmountType(1);
                    apiAmountRecord.setSourceType(2);
                    apiAmountRecord.setSourceOrderNo(order.getOrderNo());
                    apiAmountRecord.setSourceId(order.getId());
                    apiAmountRecord.setSourceContent(apiMerchants.getMerchantName() + "|订单退款"  + order.getPayPrice());

                    apiAmountRecordService.insertAmountRecord(apiAmountRecord);

                    Map<String, Object> orderMap = new HashMap<>();
                    orderMap.put("orderId" , order.getId());

                    // 查询是否用重复订单
                    ApiOrderRecord apiOrderRecord = apiOrderRecordService.queryOrderResult(orderMap);

                    apiOrderRecord.setStatus(100);
                    apiOrderRecord.setRequestTime(new Date());
                    apiOrderRecordService.updateOrderRecord(apiOrderRecord);
                }

            }
        }

        // 银联退款
        if (order.getPayType() == 5) {
            // 订单退款
            JSONObject refund = UnionPayConfig.zwrefund(UnionPayConfig.MER_ID2, UnionPayConfig.TERM_ID2, order.getOrderNo(), order.getPaySerialNo(), order.getPayRealPrice().multiply(new BigDecimal("100")).longValue());
            if (!refund.getString("resultcode").equals("W6")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, refund.getString("returnmsg"));
            }
            order.setRefundTime(new Date());
            order.setRefundNo(refund.getString("oriwtorderid"));
            order.setRefundPrice(order.getPayRealPrice());
            order.setOrderStatus(4);
            order.setRefundTime(new Date());
            for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                childOrder.setChildOrdeStatus(4);
            }
            updateOrder(order);
        }
        // 退还积分
        if (order.getPayGold() != null) {
            String remark = "订单" + order.getOrderNo() + "退款，退还积分：" +  order.getPayGold();
            highUserService.goldHandle(order.getMemId(), order.getPayGold(), 1, 3, order.getId() , remark);
            if (order.getPayRealPrice().compareTo(new BigDecimal(0)) == 0) {
                order.setOrderStatus(4);
                order.setRefundTime(new Date());
                for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                    childOrder.setChildOrdeStatus(4);
                }
                updateOrder(order);
            }
        }

        if (order.getMemDiscountId() != null) {
            HighDiscountUserRel rel = highDiscountUserRelService.getRelById(order.getMemDiscountId());
            if (rel != null) {
                rel.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                rel.setUseTime(null);
                highDiscountUserRelService.updateDiscountUserRel(rel);

                HighDiscountAgentCode code = highDiscountAgentCodeService.getCodeById(rel.getDiscountAgentCodeId());
                code.setStatus(2);
                highDiscountAgentCodeService.updateCode(code);
            }
        }

    }

    public String doRefundRequest(String mchId, String data) throws Exception {

        //小程序退款需要调用双向证书的认证
        CloseableHttpClient httpClient = goodsOrderService.readCertificate(mchId);
        try {
            HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund"); // 设置响应头信息
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "text/xml");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpClient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            httpClient.close();
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void thirdCancelOrder(Long orderId) {
        HighOrder order = getOrderById(orderId);
        if (order != null && order.getOrderStatus() == 1) {
            order.setOrderStatus(5);
            order.setCancelTime(new Date());

            for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                childOrder.setChildOrdeStatus(5);
            }

            if (order.getMemDiscountId() != null) {
                HighDiscountUserRel rel = highDiscountUserRelService.getRelById(order.getMemDiscountId());
                if (rel != null) {
                    rel.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                    rel.setUseTime(null);
                    highDiscountUserRelService.updateDiscountUserRel(rel);

                    HighDiscountAgentCode code = highDiscountAgentCodeService.getCodeById(rel.getDiscountAgentCodeId());
                    code.setStatus(2);
                    highDiscountAgentCodeService.updateCode(code);
                }
            }

            if (order.getPayGold() != null) {
                // 积分返回
                String remark = "订单" + order.getOrderNo() + "取消，退还积分：" +  order.getPayGold();
                highUserService.goldHandle(order.getMemId(), order.getPayGold(), 1, 3, order.getId() , remark);
            }

            updateOrder(order);
        }
    }

    @Override
    public Long whetherCheck(Long memId, Integer status) {

        HighOrderExample example = new HighOrderExample();
        HighOrderExample.Criteria criteria = example.createCriteria();

        criteria.andMemIdEqualTo(memId).andOrderStatusEqualTo(status).andWhetherCheckEqualTo(false);

        return highOrderMapper.countByExample(example);
    }

    @Override
    public void orderCheck(Long orderId) {
        HighOrder highOrder = highOrderMapper.selectByPrimaryKey(orderId);

        highOrder.setWhetherCheck(true);

        if  (highOrder.getOrderStatus() == 3) {
            highOrderMapper.updateByPrimaryKey(highOrder);
        }

    }

    @Override
    public List<SelfOilStationModel> getSelfOilStationOrderList(String goodsId) {
        return highOrderMapper.getSelfOilStationOrderList(goodsId);
    }

    @Override
    public List<HighOrder> integralRebateOrder() {
        return highOrderMapper.integralRebateOrder();
    }

    @Override
    public JSONObject orderSource(Integer goodsType, Long goodsId , String orderNo , Long companyId) {

        JSONObject object = new JSONObject();

        if (goodsType == 1) {
            HighCoupon coupon = highCouponService.getCouponById(goodsId);

            object.put("type" , 1);
            object.put("productId", 1);
            object.put("companyId", coupon.getCompanyId());
            object.put("remark" , "卡券订单:"+ coupon.getCouponName() + "-" + orderNo + "积分返利：");
            object.put("name" , "购买卡券产品:"+ coupon.getCouponName());

        }
        if (goodsType == 3) {
            HighMerchantStore merchantStore = highMerchantStoreService.getMerchantStoreById(goodsId);
            object.put("type" , 2);
            object.put("productId", 1);
            object.put("companyId", merchantStore.getCompanyId());
            object.put("remark" , "在线加油订单" + orderNo + "积分返利：");
            object.put("name" , "购买在线加油产品");
        }

        if (goodsType == 4) {
            object.put("type" , 4);
            object.put("productId", 2);
            object.put("companyId", companyId);
            object.put("remark" , "肯德基订单" + orderNo + "积分返利：");
            object.put("name" , "购买肯德基产品");
        }
        if (goodsType == 9) {
            object.put("type" , 4);
            object.put("productId", 1);
            object.put("companyId", companyId);
            object.put("remark" , "星巴克订单" + orderNo + "积分返利：");
            object.put("name" , "购买星巴克产品");
        }
        if (goodsType == 10) {
            object.put("type" , 4);
            object.put("productId", 3);
            object.put("companyId", companyId);
            object.put("remark" , "会员充值订单" + orderNo + "积分返利：");
            object.put("name" , "购买会员充值产品");
        }

        object.put("logoImg" , OrderLogoEnum.getNameByImgUrl(goodsType));
        return object;
    }

    @Override
    public List<HighOrder> promoteOrderList(Long identificationCode) throws Exception {

        HighOrderExample example = new HighOrderExample();
        HighOrderExample.Criteria criteria = example.createCriteria();

        criteria.andIdentificationCodeEqualTo(identificationCode).andOrderStatusEqualTo(3);

        List<HighOrder> list = highOrderMapper.selectByExample(example);

        for (HighOrder order : list) {
             order.setTime(DateUtil.date2String(order.getCreateTime() , "MM月dd日 HH:mm"));
             List<HighChildOrder> childOrder = getChildOrderByOrder(order.getId());
             order.setGoodsTypeName("购买：" + GoodsType.getNameByType(childOrder.get(0).getGoodsType()));
        }

        return list;
    }

    @Override
    public List<HighOrder> orderListByAgentId(Map<String, Object> map) throws Exception {

        HighOrderExample example = new HighOrderExample();
        HighOrderExample.Criteria criteria = example.createCriteria();

        criteria.andOrderStatusEqualTo(3);

        if (MapUtils.getLong(map , "agentId") != null) {
            criteria.andIdentificationCodeEqualTo(MapUtils.getLong(map , "agentId"));
        } else {
            criteria.andIdentificationCodeIsNotNull();
        }

        List<HighOrder> list = highOrderMapper.selectByExample(example);

        if (list.size() > 0) {
            for (HighOrder order : list) {
                HighUser user = highUserService.findByUserId(order.getIdentificationCode());
                order.setTime(DateUtil.date2String(order.getCreateTime() , "MM月dd日 HH:mm"));
                List<HighChildOrder> childOrder = getChildOrderByOrder(order.getId());
                order.setGoodsTypeName("购买：" + GoodsType.getNameByType(childOrder.get(0).getGoodsType()));
                if (user != null) {
                    order.setAgentName(user.getName());
                } else {
                    if (order.getIdentificationCode() == 60) {
                        order.setAgentName("贵州汇联通");
                    } else {
                        order.setAgentName("暂无推广人");
                    }
                }
            }
        }

        return list;
    }
}
