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.utils.DateUtil;
import com.hai.config.*;
import com.hai.dao.*;
import com.hai.entity.*;
import com.hai.enum_type.OrderPushType;
import com.hai.model.*;
import com.hai.service.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
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.util.*;

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

    @Resource
    private HighOrderMapper highOrderMapper;

    @Resource
    private HighOrderMapperExt highOrderMapperExt;

    @Resource
    private HighUserCardService highUserCardService;

    @Resource
    private HighChildOrderMapper highChildOrderMapper;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @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 HighMerchantStoreService highMerchantStoreService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighActivityInfoService highActivityInfoService;

    @Resource
    private HighActivityUserLotteryNumService highActivityUserLotteryNumService;

    @Resource
    private HuiLianTongConfig huiLianTongConfig;

    @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(!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);
                            }
                        }
                    }
                }
            }
        }
    }

    @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.getTotalPrice().toString()).multiply(new BigDecimal("100")).intValue();
        highUserService.goldHandle(userId, goldNum, 2, 2, highOrder.getId());

        highOrder.setPayTime(new Date()); // 支付时间
        highOrder.setPayModel(1);         // 支付模式：1 金币，2 第三方平台，3 混合
        highOrder.setPayType(3);          // 支付方式： 1：支付宝  2：微信  3：金币
        highOrder.setPayGold(goldNum);
        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.getCouponSource() == 4) {
                    // 获取token
                    String token = huiLianTongConfig.getToken();

                    Map<String,Object> push = new HashMap<>();
                    push.put("token", token);
                    push.put("couTypeCode", coupon.getCouponKey());
                    push.put("distCouCount", highChildOrder.getSaleCount());
                    push.put("userPhone", highUser.getPhone());
                    push.put("thirdUserId", highUser.getUnionId());

                    // 推送给高速
                    JSONObject returnParam = HuiLianTongConfig.couJointDist(token, highOrder.getOrderNo(), coupon.getCouponKey(), highChildOrder.getSaleCount(), highUser.getPhone(), highUser.getUnionId());
                    if (returnParam != null && returnParam.getString("result").equals("success")) {
                        JSONArray dataArray = returnParam.getJSONArray("data");
                        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);
                        }
                    }
                    // 推送记录
                    HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                    highGasOrderPush.setType(OrderPushType.type6.getType());
                    highGasOrderPush.setOrderNo(highOrder.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(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);
                }
            }
        }

        updateOrder(highOrder);
    }

    @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 = "11101290";
        String businessType = "hisen_consume";

        if (order.getHighChildOrderList().get(0).getGoodsType() == 1) {
            instCode = "11101291";
            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 {
            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.getCouponSource() == 4) {
                    // 获取token
                    String token = huiLianTongConfig.getToken();

                    Map<String, Object> push = new HashMap<>();
                    push.put("token",token);
                    push.put("couTypeCode", coupon.getCouponKey());
                    push.put("distCouCount", highChildOrder.getSaleCount());
                    push.put("userPhone", highUser.getPhone());
                    push.put("thirdUserId", highUser.getUnionId());

                    // 推送给高速
                    JSONObject returnParam = HuiLianTongConfig.couJointDist(token, order.getOrderNo(),coupon.getCouponKey(), highChildOrder.getSaleCount(), highUser.getPhone(), highUser.getUnionId());
                    if (returnParam != null && returnParam.getString("result").equals("success")) {
                        JSONArray dataArray = returnParam.getJSONArray("data");
                        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.setStatus(20);
                            couponCodeOther.setCreateTime(new Date());
                            couponCodeOther.setActiveTime(dataObject.getDate("activeTime"));
                            couponCodeOther.setValidStartDate(dataObject.getDate("validStartDate"));
                            couponCodeOther.setValidEndDate(dataObject.getDate("validEndDate"));
                            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();
                highUserService.goldHandle(highChildOrder.getGoodsId(), goldNum, 1, 1, highChildOrder.getId());
            }

            if (highChildOrder.getGoodsType() == 3) {
                highChildOrder.setChildOrdeStatus(3);
                HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(highChildOrder.getGoodsId());
                // 推送团油订单
                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"));
                }
            }
        }

        updateOrder(order);
    }

    @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 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"));
        }

        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);
                    }
                }
                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(4);
                    highDiscountAgentCodeService.updateCode(code);
                }
            }
            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);
    }
}
