package com.cweb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.AESEncodeUtil;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.IDGenerator;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonSysConfig;
import com.hai.config.CommonSysConst;
import com.hai.config.TuanYouConfig;
import com.hai.entity.*;
import com.hai.enum_type.DiscountUseScope;
import com.hai.enum_type.GasClassGroupTaskStatus;
import com.hai.enum_type.MerAccountMarketingType;
import com.hai.enum_type.OrderChildGoodsTypeEnum;
import com.hai.model.GasPayPriceModel;
import com.hai.model.HighMerchantStoreModel;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/26 23:08
 */
@Controller
@RequestMapping(value = "/highOrder")
@Api(value = "订单接口")
public class HighOrderController {
    private static Logger log = LoggerFactory.getLogger(HighMerchantStoreController.class);

    @Autowired
    private UserCenter userCenter;

    @Resource
    private CommonService commonService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private HighMerchantAccountMarketingService merchantAccountMarketingService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighDiscountUserRelService highDiscountUserRelService;

    @Resource
    private HighDiscountCouponRelService highDiscountCouponRelService;

    @Resource
    private HighDiscountPackageService discountPackageService;

    @Resource
    private HighDiscountPackageActualService discountPackageActualService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighTyAgentOilStationService tyAgentOilStationService;

    @Resource
    private HighTyAgentPriceService tyAgentPriceService;

    @Resource
    private HighGasDiscountOilPriceService gasDiscountOilPriceService;

    @Resource
    private HighGasStaffService gasStaffService;

    @Resource
    private HighGasClassGroupTaskService gasClassGroupTaskService;

    @Resource
    private BsCompanyService bsCompanyService;

    @RequestMapping(value="/addOrder",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加订单")
    public ResponseData addOrder(@RequestBody HighOrder highOrder, HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            if (highOrder.getHighChildOrderList() == null
                || highOrder.getHighChildOrderList().size() == 0
            ) {
                log.error("HighOrderController --> addOrder() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (StringUtils.isBlank(userInfoModel.getHighUser().getPhone())) {
                log.error("HighOrderController --> addOrder() error!", "未绑定手机号");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NO_BIND_PHONE, "");
            }

            HighDiscountUserRel highDiscountUserRel = null;
            if (highOrder.getMemDiscountId() != null) {
                // 卡优惠券信息
                highDiscountUserRel = highDiscountUserRelService.getRelById(highOrder.getMemDiscountId());
                if (highDiscountUserRel == null || highDiscountUserRel.getStatus() != 1) {
                    log.error("HighOrderController --> addOrder() error!", "优惠券状态错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "优惠券状态错误");
                }
            }

            // 定义当前卡券是否可以直冲积分
            boolean buyPoints = false;


            BigDecimal totalPrice = new BigDecimal("0");
            BigDecimal totalActualPrice = new BigDecimal("0");
            for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                if (childOrder.getGoodsType() == null || childOrder.getGoodsId() == null || childOrder.getSaleCount() == null) {
                    log.error("HighOrderController --> addOrder() error!", "参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }

                // 商品类型   1:卡卷  2:金币充值  3:团油【加油站】
                if (childOrder.getGoodsType() == 1) {
                    if (childOrder.getSaleCount() != 1) {
                        log.error("HighOrderController --> addOrder() error!", "卡卷只能购买一张");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "卡卷只能购买一张");
                    }
                    // 查询卡卷信息
                    HighCoupon coupon = highCouponService.getCouponById(childOrder.getGoodsId());
                    if (coupon == null) {
                        log.error("HighOrderController --> addOrder() error!", "未找到卡卷信息");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
                    }
                    if (coupon.getReserveStatus() == true) {
                        if (childOrder.getStoreId() == null) {
                            log.error("HighOrderController --> addOrder() error!", "未选择门店");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未选择门店");
                        }
                        // 查询门店信息
                        HighMerchantStoreModel merchantStore = highMerchantStoreService.getMerchantStoreById(childOrder.getStoreId());
                        if (merchantStore == null) {
                            log.error("HighOrderController --> addOrder() error!", "未选择门店");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店信息");
                        }
                        if (!merchantStore.getMerchantId().equals(coupon.getMerchantId())) {
                            log.error("HighOrderController --> addOrder() error!", "卡券无法在此门店消费");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "卡券无法在此门店消费");
                        }
                    }
                    // 支付类型：1.微信支付 2.金币支付
                    if(coupon.getPayType() == 2) {
                        highOrder.setPayModel(1);  // 支付模式：1 金币，2 第三方平台，3 混合
                        highOrder.setPayType(3);   // 支付方式： 1：支付宝  2：微信  3：金币
                    }
                    // 是否达到限购数量
                    if (highCouponService.userBuyLimitNumber(userInfoModel.getHighUser().getId(), coupon.getId()) == true) {
                        log.error("HighOrderController --> addOrder() error!", "已达到限购数量");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + ",已达到限购数量");
                    }
                    //  校验优惠券是否可用  如果使用优惠券就只能使用卡券的原价
                    if (highDiscountUserRel != null) {
                        List<HighDiscountCouponRel> discountCouponRelList = highDiscountCouponRelService.getRelByCoupon(coupon.getId());
                        if (discountCouponRelList.size() > 0) {
                            HighDiscountUserRel finalHighDiscountUserRel = highDiscountUserRel;
                            List<HighDiscountCouponRel> collect = discountCouponRelList.stream().filter(o -> o.getDiscountId().equals(finalHighDiscountUserRel.getDiscountId())).collect(Collectors.toList());
                            if (collect == null || collect.size() == 0) {
                                log.error("HighOrderController --> addOrder() error!", "无法使用优惠券");
                                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法使用优惠券");
                            }
                        }
                        childOrder.setGoodsPrice(coupon.getSalesPrice());
                    } else {
                        childOrder.setGoodsPrice(coupon.getDiscountPrice());
                    }
                    // 贵州中石化
                    if (coupon.getCouponSource() != 4) {
                        if (highCouponCodeService.getStockCountByCoupon(coupon.getId()) <= 0) {
                            log.error("HighOrderController --> addOrder() error!", "卡卷库存数量不足");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "系统维护中");
                        }
                    }

                    if (coupon.getBuyPoints()) {
                        buyPoints = true;
                    }

                    childOrder.setGoodsActualPrice(childOrder.getGoodsPrice());
                    childOrder.setGoodsName(coupon.getCouponName());
                    childOrder.setGoodsImg(coupon.getCouponImg());
                    childOrder.setGoodsSpecName("默认");
                    childOrder.setExt1(coupon.getCouponSource().toString());
                }

                if (childOrder.getGoodsType() == 2) {
                    if (childOrder.getGoodsPrice() == null) {
                        log.error("HighOrderController --> addOrder() error!", "请设置充值金额");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请设置充值金额");
                    }
                    // 查询用户信息
                    HighUser user = highUserService.findByUserId(childOrder.getGoodsId());
                    if (user == null) {
                        log.error("HighOrderController --> addOrder() error!", "未找到用户");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_MEMBER_ERROR, "");
                    }
                    childOrder.setGoodsActualPrice(childOrder.getGoodsPrice());
                    childOrder.setGoodsName(user.getName());
                    childOrder.setGoodsImg(user.getHeaderImg());
                    childOrder.setGoodsSpecName("默认");
                }

                if (childOrder.getGoodsType() == 3) {
                    if (childOrder.getGasPriceGun() == null || childOrder.getGasPriceVip() == null || StringUtils.isBlank(childOrder.getGasGunNo()) || StringUtils.isBlank(childOrder.getGasOilNo()) || childOrder.getGasOilType() == null) {
                        log.error("HighOrderController --> addOrder() error!", "参数错误");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                    }

                    // 加油限制
                    if (childOrder.getGasOilType().equals(1)) {
                        SecDictionary refuelLimit = commonService.mappingSysName("REFUEL_LIMIT", "汽油");
                        if (refuelLimit != null && childOrder.getGoodsPrice().compareTo(new BigDecimal(refuelLimit.getCodeValue()))  == 1) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "汽油加油金额不能超过" + refuelLimit.getCodeValue()+"元");
                        }
                    } else if (childOrder.getGasOilType().equals(2)){
                        SecDictionary refuelLimit = commonService.mappingSysName("REFUEL_LIMIT", "柴油");
                        if (refuelLimit != null && childOrder.getGoodsPrice().compareTo(new BigDecimal(refuelLimit.getCodeValue()))  == 1) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "柴油加油金额不能超过" + refuelLimit.getCodeValue()+"元");
                        }
                    }

                    if (highOrderService.getGasTheDayOrderNum(userInfoModel.getHighUser().getId()) >= 1) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已达到每日加油次数上限");
                    }

                    if (StringUtils.isNotBlank(highOrder.getGasStaffCode())) {
                        String qrCodeSignKey = commonService.getDictionaryCodeName("QR_CODE_SIGN_KEY", "1");
                        if (StringUtils.isBlank(qrCodeSignKey)) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知秘钥");
                        }

                        String staffId;
                        try {
                            staffId = AESEncodeUtil.aesDecryptByBytes(AESEncodeUtil.base64Decode(URLDecoder.decode(highOrder.getGasStaffCode(),"UTF-8")), qrCodeSignKey);
                        } catch (Exception e) {
                            log.error("HighOrderController --> addOrder() error!", "收银员code解析失败");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "收银员code解析失败");
                        }

                        // 查询员工
                        HighGasStaff gasStaff = gasStaffService.getStaffDetailById(Long.parseLong(staffId));
                        if (gasStaff == null) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知收银员");
                        }
                        if (gasStaff.getMerchantStoreId().equals(childOrder.getGoodsId())) {
                            childOrder.setGasStaffId(gasStaff.getId());
                            childOrder.setGasStaffName(gasStaff.getName());
                        }
                    }

                    // 查询加油站是否开启班组
                    Map<String, Object> classGroup = new HashMap<>();
                    classGroup.put("merchantStoreId", childOrder.getGoodsId());
                    classGroup.put("status", GasClassGroupTaskStatus.status1.getStatus());
                    List<HighGasClassGroupTask> groupTaskList = gasClassGroupTaskService.getGroupTaskList(classGroup);
                    if (groupTaskList.size() > 0) {
                        HighGasClassGroupTask groupTask = groupTaskList.get(0);
                        childOrder.setGasClassGroupId(groupTask.getGasClassGroupId());
                        childOrder.setGasClassGroupName(groupTask.getGasClassGroupName());
                        childOrder.setGasClassGroupTaskId(groupTask.getId());
                    }

                    // 查询门店
                    HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(childOrder.getGoodsId());
                    if (store == null) {
                        log.error("HighOrderController --> addOrder() error!", "未找到门店信息");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店信息");
                    }
                    if (highOrder.getIsTyAgent() != null && highOrder.getIsTyAgent().equals(true)) {
                        // 查询加油站
                        HighTyAgentOilStation oilStation = tyAgentOilStationService.getDetailByOilStationId(childOrder.getGoodsId());
                        if (oilStation != null) {
                            childOrder.setGasSalesmanId(oilStation.getTySalesmanId());
                            childOrder.setGasSalesmanName(oilStation.getTySalesmanName());
                            childOrder.setGasAgentId(oilStation.getTyAgentId());
                            childOrder.setGasAgentName(oilStation.getTyAgentName());
                            childOrder.setGasOrgId(oilStation.getOrganizationId());
                            childOrder.setGasOrgName(oilStation.getOrganizationName());
                        }
                    }

                    // 营销减免的金额
                    BigDecimal marketingPrice = merchantAccountMarketingService.getPrice(store.getMerchantId(), MerAccountMarketingType.type3.getType(), Integer.valueOf(childOrder.getGasOilNo()));

                    // 计算价格
                    GasPayPriceModel priceModel = gasDiscountOilPriceService.oilPriceDiscountCompute(childOrder.getGoodsPrice(), childOrder.getGoodsId(), childOrder.getGasOilNo(), highOrder.getIsTyAgent());

                    // 使用了优惠价
                    if (highDiscountUserRel != null) {
                        // 支付价格
                        childOrder.setGoodsActualPrice(childOrder.getGoodsPrice());
                        // 油价信息
                        childOrder.setGasPriceGun(priceModel.getPriceGun());
                        childOrder.setGasPriceVip(priceModel.getPriceGun());
                        childOrder.setGasPriceOfficial(new BigDecimal("0"));
                        childOrder.setGasPricePlatform(priceModel.getPriceGun());
                        childOrder.setGasOilLiters(priceModel.getOilLiters());
                        childOrder.setGasDiscount(new BigDecimal("0"));
                        childOrder.setExt1(childOrder.getGasPricePlatform().toString());
                        childOrder.setGasOilSubsidy(new BigDecimal("0"));
                        childOrder.setGasLitersPreferences(new BigDecimal("0"));
                        childOrder.setGasPricePreferences(priceModel.getPriceGun());
                     } else {
                        // 支付价格
                        childOrder.setGoodsActualPrice(priceModel.getPayPrice());
                        // 油价信息
                        childOrder.setGasPriceGun(priceModel.getPriceGun());
                        childOrder.setGasPriceVip(priceModel.getPriceVip());
                        childOrder.setGasPriceOfficial(priceModel.getPriceOfficial());
                        childOrder.setGasPricePlatform(priceModel.getPricePlatform());
                        childOrder.setGasOilLiters(priceModel.getOilLiters());
                        childOrder.setGasDiscount(priceModel.getDiscount());
                        childOrder.setExt1(priceModel.getPricePlatform().toString());
                        childOrder.setGasOilSubsidy(priceModel.getPreferentialMargin());
                        childOrder.setGasLitersPreferences(priceModel.getLitersPreferences());
                        childOrder.setGasPricePreferences(priceModel.getPricePreferences());
                    }


                    // 来源类型  1：平台自建   2：团油
                    if (store.getSourceType().equals(1)) {
                        childOrder.setGoodsImg(CommonSysConst.getSysConfig().getHsgDomainName()+"/filesystem/"+store.getStoreLogo());
                    } else {
                        childOrder.setGoodsImg(store.getStoreLogo());
                    }

                    childOrder.setGoodsName(store.getStoreName());
                    childOrder.setGoodsSpecName("默认");
                    childOrder.setTotalPrice(childOrder.getGoodsPrice().multiply(new BigDecimal(childOrder.getSaleCount().toString())));

                    // 成本价 油站价 减 营销策略价
                    childOrder.setGasPriceCost(priceModel.getPriceGun().subtract(marketingPrice));
                    if (marketingPrice.compareTo(new BigDecimal("0")) <= 0) {
                        childOrder.setGasPriceCostTotal(childOrder.getTotalPrice());
                    } else {
                        childOrder.setGasPriceCostTotal(childOrder.getGasPriceCost().multiply(childOrder.getGasOilLiters()).setScale(2, BigDecimal.ROUND_HALF_DOWN));
                    }
                }

                if (childOrder.getGoodsType() == 7) {
                    // 查询优惠券包
                    HighDiscountPackage discountPackage = discountPackageService.findDiscountPackageById(childOrder.getGoodsId().intValue());

                    if (discountPackage == null) {
                        log.error("HighOrderController --> addOrder() error!", "");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到优惠券包");
                    }
                    if (discountPackage.getStatus() != 1) {
                        log.error("HighOrderController --> addOrder() error!", "");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "优惠券包不可用");
                    }
                    if (discountPackageActualService.getStockByPackageId(discountPackage.getId()) == 0) {
                        log.error("HighOrderController --> addOrder() error!", "");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "库存数量不足");
                    }

                    if (discountPackage.getPurchaseNum() < discountPackageActualService.userPurchaseByUserId(userInfoModel.getHighUser().getId().intValue(), discountPackage.getId())) {
                        log.error("HighOrderController --> addOrder() error!", "");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "超过购买限制");
                    }

                    childOrder.setGoodsActualPrice(childOrder.getGoodsPrice());
                    childOrder.setGoodsName(discountPackage.getTitle());
                    childOrder.setGoodsImg(discountPackage.getListImg());
                    childOrder.setGoodsPrice(discountPackage.getPrice());
                    childOrder.setGoodsActualPrice(discountPackage.getPrice());
                    childOrder.setGoodsSpecName("默认");
                }
                //  汇联通充值
                if (childOrder.getGoodsType() == 8) {
                    if (childOrder.getGoodsPrice() == null) {
                        log.error("HighOrderController --> addOrder() error!", "请设置充值金额");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请设置充值金额");
                    }
                    if (highOrder.getMemCardNo() == null) {
                        log.error("HighOrderController --> addOrder() error!", "请设置充值卡号");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请设置充值卡号");
                    }
                    // 查询用户信息
                    HighUser user = highUserService.findByUserId(childOrder.getGoodsId());
                    if (user == null) {
                        log.error("HighOrderController --> addOrder() error!", "未找到用户");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_MEMBER_ERROR, "");
                    }
                    highOrder.setPayType(2); // 第三方平台
                    childOrder.setGoodsActualPrice(childOrder.getGoodsPrice());
                    childOrder.setGoodsName(user.getName());
                    childOrder.setGoodsImg(user.getHeaderImg());
                    childOrder.setGoodsSpecName("默认");
                }

                childOrder.setMemId(userInfoModel.getHighUser().getId());
                childOrder.setTotalPrice(childOrder.getGoodsPrice().multiply(new BigDecimal(childOrder.getSaleCount().toString())));
                childOrder.setGiveawayType(false);  // 是否是赠品  0：否   1：是
                childOrder.setChildOrdeStatus(1);   // 1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
                childOrder.setPraiseStatus(0);

                // 累计订单价格
                totalPrice = totalPrice.add(childOrder.getTotalPrice());
                totalActualPrice = totalActualPrice.add(childOrder.getGoodsActualPrice());
            }

            // 积分抵扣金额
            BigDecimal integralDeductionPrice = new BigDecimal(0);
            if (buyPoints && highOrder.getPayGold() != null) {
                integralDeductionPrice = new BigDecimal(highOrder.getPayGold()).divide(new BigDecimal(100));
                String remark = "订单" + highOrder.getOrderNo() + "购买，使用积分：" +  highOrder.getPayGold();
                highUserService.goldHandle(userInfoModel.getHighUser().getId(), highOrder.getPayGold(), 2, 2, highOrder.getId() , remark);
                BigDecimal payGold = new BigDecimal(highOrder.getPayGold());

                if (payGold.compareTo(totalActualPrice.subtract(integralDeductionPrice)) < 0) {
                    highOrder.setPayModel(2);  // 支付模式：1 金币，2 第三方平台，3 混合
                    highOrder.setPayType(2);   // 支付方式： 1：支付宝  2：微信  3：金币
                }
            }

            if (request.getHeader("regionId") != null && request.getHeader("regionId").length() != 0) {
                SecRegion region = commonService.getParentByRegion(Long.valueOf(request.getHeader("regionId")));
                if (region != null) {
                    BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());
                    if (bsCompany != null) {
                        highOrder.setCompanyId(bsCompany.getId());
                    }
                }
            }

            highOrder.setMerchId(request.getHeader("mchId"));
            highOrder.setWhetherRebate(false);
            highOrder.setTotalPrice(totalPrice);
            highOrder.setPayablePrice(totalActualPrice);

            // 是否使用了优惠券
            if (highDiscountUserRel != null) {
                highOrder.setMemDiscountName(highDiscountUserRel.getHighDiscount().getDiscountName());

                // 优惠券使用范围
                if (highDiscountUserRel.getHighDiscount().getUseScope().equals(DiscountUseScope.type1.getType())) {
                    // 暂无限制
                } else if (highDiscountUserRel.getHighDiscount().getUseScope().equals(DiscountUseScope.type2.getType())) {
                    // 1:卡卷 2:金币充值  3:团油【加油站】 4: KFC  5：电影票 6：话费充值
                    if (!highOrder.getHighChildOrderList().get(0).getGoodsType().equals(1)) {
                        log.error("HighOrderController --> addOrder() error!", "此优惠券只能购买卡券商品使用");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "此优惠券只能购买卡券商品使用");
                    }
                } else if (highDiscountUserRel.getHighDiscount().getUseScope().equals(DiscountUseScope.type3.getType())) {
                    if (!highOrder.getHighChildOrderList().get(0).getGoodsType().equals(6)) {
                        log.error("HighOrderController --> addOrder() error!", "此优惠券只能充值话费中使用");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "此优惠券只能充值话费中使用");
                    }
                } else if (highDiscountUserRel.getHighDiscount().getUseScope().equals(DiscountUseScope.type7.getType())) {
                    if (!highOrder.getHighChildOrderList().get(0).getGoodsType().equals(3)) {
                        log.error("HighOrderController --> addOrder() error!", "此优惠券只能充值话费中使用");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "此优惠券只能充值话费中使用");
                    }
                } else {
                    log.error("HighOrderController --> addOrder() error!", "暂时无法使用此优惠券");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法使用此优惠券");
                }

                // 卡卷类型  1：满减  2：抵扣   3：折扣
                if (highDiscountUserRel.getHighDiscount().getDiscountType() == 1) {
                    // 如果订单总额 小于 满减价格
                    if (highOrder.getTotalPrice().compareTo(highDiscountUserRel.getHighDiscount().getDiscountCondition()) > 1) {
                        log.error("HighOrderController --> addOrder() error!", "订单未达到满减额度");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_MEMBER_ERROR, "订单未达到"+highDiscountUserRel.getHighDiscount().getDiscountCondition()+"元,无法使用此优惠券");
                    }
                    // 订单总额 - 满减额度
                    BigDecimal payablePrice = highOrder.getTotalPrice().subtract(highDiscountUserRel.getHighDiscount().getDiscountPrice());

                    highOrder.setDeductionPrice(highDiscountUserRel.getHighDiscount().getDiscountPrice());
                    // 如果总额小于0
                    if (payablePrice.compareTo(new BigDecimal("0")) < 0) {
                        highOrder.setPayablePrice(new BigDecimal("0"));
                    } else {
                        highOrder.setPayablePrice(payablePrice);
                    }
                }

                // 卡卷类型  1：满减  2：抵扣   3：折扣
                if (highDiscountUserRel.getHighDiscount().getDiscountType() == 2) {
                    // 订单总额 - 满减额度
                    BigDecimal payablePrice = highOrder.getTotalPrice().subtract(highDiscountUserRel.getHighDiscount().getDiscountPrice());
                    highOrder.setDeductionPrice(highDiscountUserRel.getHighDiscount().getDiscountPrice());

                    // 如果总额小于0
                    if (payablePrice.compareTo(new BigDecimal("0")) == -1) {
                        highOrder.setPayablePrice(new BigDecimal("0"));
                    } else {
                        highOrder.setPayablePrice(payablePrice);
                    }
                }

                // 卡卷类型  1：满减  2：抵扣   3：折扣
                if (highDiscountUserRel.getHighDiscount().getDiscountType() == 3) {
                    // 折扣除100
                    BigDecimal discountPrice = highDiscountUserRel.getHighDiscount().getDiscountPrice();
                    // 订单总额 * 折扣
                    BigDecimal payablePrice = highOrder.getTotalPrice().multiply(discountPrice).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                    highOrder.setDeductionPrice(highOrder.getTotalPrice().subtract(payablePrice));
                    highOrder.setPayablePrice(payablePrice);
                }
            }

            highOrder.setOrderNo("HF" + DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + IDGenerator.nextId(5));
            highOrder.setMemId(userInfoModel.getHighUser().getId());
            highOrder.setMemName(userInfoModel.getHighUser().getName());
            highOrder.setMemPhone(userInfoModel.getHighUser().getPhone());
            highOrder.setCreateTime(new Date());
            highOrder.setOrderStatus(1);
            highOrder.setPrintStatus(false);
            highOrder.setPrintNum(0);
            highOrder.setPayPrice(highOrder.getPayablePrice().subtract(integralDeductionPrice));
            highOrder.setDeductionPrice(highOrder.getTotalPrice().subtract(highOrder.getPayPrice()));

            highOrderService.insertOrder(highOrder);

            return ResponseMsgUtil.success(highOrderService.getOrderById(highOrder.getId()));

        } catch (DeadlockLoserDataAccessException deadlockLoserDataAccessException) {
            log.error("HighActivityController -> userLottery() error!", "服务器繁忙");
            return ResponseMsgUtil.builderResponse(ErrorCode.SERVER_BUSY_ERROR.getCode(),ErrorCode.SERVER_BUSY_ERROR.getMsg(),null);

        } catch (Exception e) {
            log.error("HighOrderController -> addOrder() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getOrderById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询订单详情")
    public ResponseData getOrderById(@RequestParam(name = "orderId", required = true) Long orderId) {
        try {
            return ResponseMsgUtil.success(highOrderService.getOrderById(orderId));
        } catch (Exception e) {
            log.error("HighOrderController --> getOrderById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/cancelOrder", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据订单id 取消订单")
    public ResponseData cancelOrder(@RequestParam(name = "orderId", required = true) Long orderId) {
        try {

            highOrderService.cancelOrder(orderId);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighOrderController --> cancelOrder() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/orderCheck", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据订单id查看订单")
    public ResponseData orderCheck(@RequestParam(name = "orderId", required = true) Long orderId) {
        try {

            highOrderService.orderCheck(orderId);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighOrderController --> cancelOrder() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/cancelOrderByOrderNo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据订单号 取消订单")
    public ResponseData cancelOrderByOrderNo(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {

            HighOrder order = highOrderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                log.error("HighOrderController --> addOrder() error!", "未找到订单");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
            }
            highOrderService.cancelOrder(order.getId());

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighOrderController --> cancelOrderByOrderNo() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getUserOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户订单")
    public ResponseData getUserOrderList(
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "orderNo", required = false) String orderNo,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                         HttpServletRequest request) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            Map<String,Object> map = new HashMap<>();
            map.put("memId", userInfoModel.getHighUser().getId());
            map.put("status", status);
            map.put("orderNo", orderNo);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highOrderService.getOrderList(map)));

        } catch (Exception e) {
            log.error("HighOrderController --> getUserOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
