package com.platform.yijia.controller;
import com.google.gson.Gson;
import com.platform.yijia.config.YiJiaRequest;
import com.platform.yijia.dao.PayOrderMapper;
import com.platform.yijia.param.request.PayOrderRequest;
import com.platform.yijia.pojo.*;
import com.platform.yijia.service.*;
import com.platform.yijia.utils.CodeMsg;
import com.platform.yijia.utils.ResultData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

@Controller
@YiJiaRequest()
public class PayOrderController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(PayOrderController.class);
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private StationService stationService;
    @Resource
    private CustomerGradeServices customerGradeServices;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private  CustomerManagerService customerManagerService;
    @Resource
    private SysDictDataService sysDictDataService;

    //小程序支付生成订单
    @RequestMapping(value = "/AddPayOrderInfoNew", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String  AddPayOrderInfoNew(@RequestBody PayOrderRequest payOrderRequest){
        logger.info("获取订单前端传来参数openId："+ payOrderRequest.getOpenId());
        Gson gson =new Gson();
        ResultData resultData =null;
        AppUserInfo appUserInfo =new AppUserInfo();     //查询客户信息传递参数
        PayOrder payOrder = new PayOrder();             //生成订单参数
        if(StringUtils.isNotBlank(payOrderRequest.getUserType()) && StringUtils.isNotBlank(payOrderRequest.getOpenId()) && StringUtils.isNotBlank(payOrderRequest.getOilName()) &&
                StringUtils.isNotBlank(payOrderRequest.getOilGun()) && payOrderRequest.getReceivableAmt() !=null && StringUtils.isNotBlank(payOrderRequest.getOrderType())){
            appUserInfo.setUserType(payOrderRequest.getUserType());
            switch (payOrderRequest.getUserType()){
                case "1":       //公众号
                    appUserInfo.setBlogOpenid(payOrderRequest.getOpenId());
                    break;
                case "2":       //小程序
                    appUserInfo.setMinaOpenid(payOrderRequest.getOpenId());
                    break;
                case "3":       //支付宝公众号
                    appUserInfo.setALiId(payOrderRequest.getOpenId());
                    break;
                case "4":       //支付宝小程序
                    appUserInfo.setALiId(payOrderRequest.getOpenId());
                    break;
            }
            AppUserInfo appUserInfos = appUserInfoService.getAppUserInfo(appUserInfo);
            Map<String ,Object> resultMap = new HashMap<>();            //返回结果集
            if(appUserInfos !=null){
                payOrderRequest.setCustomerPhone(appUserInfos.getMobilePhone());    //客户手机号; 注：此处存放手机号用于获取客户信息参数查询
                payOrderRequest.setUnionId(appUserInfos.getUnionId());              //客户UnionId；注：此处存放unionId用于获取客户电子卡参数查询
                payOrder.setConsumer(appUserInfos.getBlogNickName());             //昵称
                payOrder.setConsumerId(appUserInfos.getUserId());                 //用户id
                Random random = new Random();
                String result="";
                for(int i=0;i<6;i++){
                    result+=random.nextInt(10);
                }
                String ordNo=System.nanoTime()+result;
                payOrder.setOrderNo(ordNo);                                             //订单号
                logger.info("生成的订单号：" + ordNo);
                payOrder.setDiscountCouponAmt(payOrderRequest.getDiscountCouponAmt());  //优惠劵金额
                payOrder.setDiscountCoupon(payOrderRequest.getDiscountCoupon());        //优惠券
                payOrder.setCarNo(payOrderRequest.getCarNo());                          //车牌号、
                payOrder.setCustomerGrade(payOrderRequest.getCustomerGrade());          //客户电话
                payOrder.setMemberNo(payOrderRequest.getMemberNo());                    //会员卡号
                payOrder.setMemberAmt(payOrderRequest.getMemberAmt());                  //会员支付金额
                payOrder.setScore(payOrderRequest.getScore());                          //积分
                payOrder.setStationId(payOrderRequest.getStationId());                  //油站id
                payOrder.setStatus("0");                                                //创建订单 未支付状态 0
                payOrder.setCreatedDate(new Timestamp(new Date().getTime()));                    //创建时间
                payOrder.setOrderType(payOrderRequest.getOrderType());  //订单类型
                payOrder.setOilGun(payOrderRequest.getOilGun());        //油枪号
                payOrder.setReceivableAmt(payOrderRequest.getReceivableAmt());                //订单应收金额
                String oilName =payOrderRequest.getOilName();
                //获取该油品所属哪一类
                Oil oil = new Oil();
                oil.setOilName(oilName);
                Oil oilInfo = sysDictDataService.selectOilType(oil);
                payOrder.setOilType(oilInfo.getOilsType());     //油品类型
                payOrderRequest.setCardOilsType(oilInfo.getOilsType());                 //电子卡类型；注：用于获取客户电子卡参数查询
                payOrder.setOilName(oilName);                   //油品名称
                StationInfo stationInfo = new StationInfo();
                stationInfo.setStationId(payOrderRequest.getStationId());
                StationInfo stationInfos = stationService.selectStationInfo(stationInfo);
                if(stationInfos !=null){
                    payOrder.setStationName(stationInfos.getStationName());
                    //获取油站图片和名称
                    resultMap.put("stationPic", stationInfos.getStationPic());
                    resultMap.put("stationName", stationInfos.getStationName());
                }

                //根据油站和油枪获取加油员
                HashMap<String, Object> params = new HashMap<>();
                params.put("oliGunNo", payOrderRequest.getOilGun());
                params.put("stationId", payOrderRequest.getStationId());
                List<Map> mapResultList = payOrderMapper.selectPersonelName(params);    //使用list原因：一个枪号对应多个加油员场景
                logger.info("加油员信息："+ mapResultList.toString());
                if(mapResultList != null && mapResultList.size() > 0){
                    String oilPersonnel = "";
                    for (Map per : mapResultList){
                        if(per.containsKey("personelName") && per.get("personelName").toString() !=null && per.get("personelName").toString() !=""){
                            oilPersonnel += per.get("personelName").toString() +",";
                        }
                    }
                    if(oilPersonnel !=""){
                        payOrder.setOilPersonnel(oilPersonnel.substring(0, oilPersonnel.length()-1));   //加油员
                    }
                }else {
                    payOrder.setOilPersonnel("");
                }
                String orderType = payOrderRequest.getOrderType();                          //获取订单类型
                logger.info("订单类型：" + orderType);
                if(orderType.equals("1")){                                                  //订单类型是油品时计算
                    PayOrderResultInfo payOrderResultInfo = this.calculateAmt(payOrderRequest); //计算订单金额 价格 加油升数 等等
                    payOrder.setOilPirce(payOrderResultInfo.getOilPrice());
                    payOrder.setOrderLiters(payOrderResultInfo.getOilLiters());
                    payOrder.setDiscountAmt(Double.valueOf(payOrderResultInfo.getDiscountAmt()));
                    payOrder.setAmt(Double.valueOf(payOrderResultInfo.getAmt()));
                    resultMap.put("discountAmt", payOrderResultInfo.getDiscountAmt());                                          //优惠价格
                    resultMap.put("amt", payOrderResultInfo.getAmt());                   //实收价格
                    resultMap.put("receivableAmt", payOrderResultInfo.getReceivableAmt());         //应收价格
                    resultMap.put("oilLiters", payOrderResultInfo.getOilLiters());
                    resultMap.put("discountPrice", payOrderResultInfo.getDiscountPrice());
                    resultMap.put("amt_dzk", payOrderResultInfo.getDzkAmt());
                    resultMap.put("balance", payOrderResultInfo.getBalance());               //电子卡余额
                    resultMap.put("cardOilsType", payOrderResultInfo.getCardOilsType());     //电子卡类型1.汽油； 2.柴油
                    resultMap.put("ordNo", ordNo);
                    logger.info("返回前端的结果：" +resultMap.toString());
                    payOrderMapper.insertSelective(payOrder);
                }else {
                    payOrder.setAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));        //非油品金额
                    payOrder.setDiscountAmt(Double.valueOf(0));                                 //优惠金额
                    payOrder.setOilPirce(payOrderRequest.getReceivableAmt().toString());        //非油品价格
                    payOrder.setOrderLiters("0");
                    resultMap.put("discountAmt", "0");                                          //优惠价格
                    resultMap.put("amt", payOrderRequest.getReceivableAmt());                   //实收价格
                    resultMap.put("receivableAmt", payOrderRequest.getReceivableAmt());         //应收价格
                    resultMap.put("oilLiters", "0");
                    resultMap.put("discountPrice", "0");
                    resultMap.put("ordNo", ordNo);
                    payOrderMapper.insertSelective(payOrder);
                }
                resultData = ResultData.success(resultMap);
            }else {
                //登录人验证失败
                resultData=ResultData.error(CodeMsg.USER_NOT_EXSIST);
            }
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }


    //根据营销方案计算订单金额
    public PayOrderResultInfo calculateAmt(PayOrderRequest payOrderRequest){
        PayOrderResultInfo payOrderResultInfo = new PayOrderResultInfo();
        Integer stationId = payOrderRequest.getStationId();         //油站ID
        BigDecimal receivableAmt = new BigDecimal(payOrderRequest.getReceivableAmt());  //应收金额 用户输入的金额
        String oilName = payOrderRequest.getOilName();          //油品名称
        String openId = payOrderRequest.getOpenId();        //用户的openId
        Map<String, Object> map = new HashMap<>();
        map.put("oilName", oilName);
        map.put("stationId", stationId);
        Map<String, Object> result = stationService.selectStationOilPriceAndDiscountSetting(map);
        String oilPrice = result.get("oilPrice").toString();
        String discountSetting = result.get("discountSetting").toString();
        String cardEnabledFlag = result.get("cardEnabledFlag").toString();

        Map<String ,Object> params = new HashMap<String, Object>();
        params.put("stationId", stationId);
        params.put("oilName", oilName);
        params.put("receivableAmt", receivableAmt);
        params.put("oilPrice", oilPrice);
        params.put("mobilePhone", payOrderRequest.getCustomerPhone());
        params.put("minaOpenid", openId);
        params.put("cardEnabledFlag", cardEnabledFlag);
        params.put("unionId", payOrderRequest.getUnionId());
        params.put("cardOilsType", payOrderRequest.getCardOilsType());
        switch (discountSetting){
            case "0":   //不执营销方案时 计算等级优惠
                payOrderResultInfo = this.calculateGradeDiscount(params);
                break;
            case "1":    //满减方案
                payOrderResultInfo = this.calculateManJianDiscount(params);
                break;
            case "2":    //立减方案
                payOrderResultInfo = this.calculateLiJianDiscount(params);
                break;
            case "3":    //独立直降
                payOrderResultInfo = this.calculateZhiJiangDiscount(params);
                break;
        }
        return  payOrderResultInfo;
    }

    //计算直降
    public PayOrderResultInfo calculateZhiJiangDiscount(Map<String ,Object> params){
        BigDecimal oilPrice = new BigDecimal(params.get("oilPrice").toString());    //油品价格
        BigDecimal receivableAmt = new BigDecimal(params.get("receivableAmt").toString());   //应收金额
        BigDecimal oilLiters = new BigDecimal("0.00");  //加油升数
        BigDecimal discountAmt = new BigDecimal(0);  //优惠金额
        BigDecimal amt = new BigDecimal(0);
        BigDecimal discountPrice = oilPrice;
        BigDecimal gradeDiscountAmt = new BigDecimal(0);    //等级优惠金额
        //加油升数
        oilLiters = receivableAmt.divide(oilPrice,2, BigDecimal.ROUND_HALF_UP);
        if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
            oilLiters = receivableAmt.divide(oilPrice,2, BigDecimal.ROUND_UP);
        }
        PayOrderResultInfo payOrderResultInfo = new PayOrderResultInfo();
        params.put("discountPlanType", "3");
        List<Map> customerMarkertPlanList = customerGradeServices.getCustomerMarkertPlanList(params);
        if(customerMarkertPlanList !=null && customerMarkertPlanList.size() >0){
            BigDecimal discountAmt_b = new BigDecimal(customerMarkertPlanList.get(0).get("discountAmt").toString());   //条件金额
            BigDecimal gasoilDiscountAmt_b = new BigDecimal(customerMarkertPlanList.get(0).get("gasoilDiscountAmt").toString());
            String discountTerm = customerMarkertPlanList.get(0).get("discountTerm").toString();
            switch (discountTerm){
                case "1":   //按加油升数
                    if(oilLiters.compareTo(discountAmt_b) ==1 || oilLiters.compareTo(discountAmt_b) ==0){
                        discountAmt = oilLiters.multiply(gasoilDiscountAmt_b);
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    break;
                case "2":   //按加油金额
                    if(receivableAmt.compareTo(discountAmt_b) ==1 || receivableAmt.compareTo(discountAmt_b) ==0){
                        discountAmt = oilLiters.multiply(gasoilDiscountAmt_b);
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    break;
            }
            String vipDiscountyPlus = customerMarkertPlanList.get(0).get("vipDiscountyPlus").toString();
            if(vipDiscountyPlus.equals("1")){
                PayOrderResultInfo payOrderResultInfoGrade = this.calculateGradeDiscount(params);
                discountAmt = discountAmt.add(new BigDecimal(payOrderResultInfoGrade.getDiscountAmt()));
            }
        }
        amt = receivableAmt.subtract(discountAmt);  //应收金额
        discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? discountPrice : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);  //优惠价格
        payOrderResultInfo.setAmt(amt.toString());
        payOrderResultInfo.setDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(params.get("cardEnabledFlag").toString().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
            if(cardRechargeSettingList !=null && cardRechargeSettingList.size() >0){
                String isGradeSetting = cardRechargeSettingList.get(0).getIsGradeSetting(); //是否叠加等级方案
                String isMarket = cardRechargeSettingList.get(0).getIsMarket(); //等候否叠加营销方案
                if(isMarket.equals("1")){
                    if(isGradeSetting.equals("1")){
                        payOrderResultInfo.setDzkAmt(amt.toString());
                    }else {
                        //如果电子卡设置执行营销方案不执行等级优惠 则 电子卡支付金额 =实收金额+等级优惠金额
                        BigDecimal subtract = amt.add(gradeDiscountAmt);
                        payOrderResultInfo.setDzkAmt(subtract.toString());
                    }
                }else {
                    if(isGradeSetting.equals("1")){
                        //如果电子卡设置不执行营销方案执行等级优惠 则 电子卡支付金额 =应收金额-等级优惠金额
                        BigDecimal subtract = receivableAmt.subtract(gradeDiscountAmt);
                        payOrderResultInfo.setDzkAmt(subtract.toString());
                    }else {
                        payOrderResultInfo.setDzkAmt(receivableAmt.toString());
                    }
                }
            }
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(Integer.valueOf(params.get("stationId").toString()), params.get("cardOilsType").toString(), params.get("unionId").toString());
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setCardOilsType(map.get("cardOilsType"));
        }
        return  payOrderResultInfo;
    }

    //计算立减
    public PayOrderResultInfo calculateLiJianDiscount(Map<String ,Object> params){
        BigDecimal oilPrice = new BigDecimal(params.get("oilPrice").toString());    //油品价格
        BigDecimal receivableAmt = new BigDecimal(params.get("receivableAmt").toString());   //应收金额
        BigDecimal oilLiters = new BigDecimal("0.00");  //加油升数
        BigDecimal discountAmt = new BigDecimal(0);  //优惠金额
        BigDecimal amt = new BigDecimal(0);
        BigDecimal discountPrice = oilPrice;
        BigDecimal gradeDiscountAmt = new BigDecimal(0);    //等级优惠金额
        //加油升数
        oilLiters = receivableAmt.divide(oilPrice,2, BigDecimal.ROUND_HALF_UP);
        if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
            oilLiters = receivableAmt.divide(oilPrice,2, BigDecimal.ROUND_UP);
        }
        PayOrderResultInfo payOrderResultInfo = new PayOrderResultInfo();
        params.put("discountPlanType", "2");
        List<Map> customerMarkertPlanList = customerGradeServices.getCustomerMarkertPlanList(params);
        if(customerMarkertPlanList !=null && customerMarkertPlanList.size() >0){
            BigDecimal discountAmt_b = new BigDecimal(customerMarkertPlanList.get(0).get("discountAmt").toString());                //条件金额
            BigDecimal gasoilDiscountAmt_b = new BigDecimal(customerMarkertPlanList.get(0).get("gasoilDiscountAmt").toString());    //享受的优惠
            if(receivableAmt.compareTo(discountAmt_b) == 1 || receivableAmt.compareTo(discountAmt_b) == 0){
                discountAmt = gasoilDiscountAmt_b;
            }
            String vipDiscountyPlus = customerMarkertPlanList.get(0).get("vipDiscountyPlus").toString();
            if(vipDiscountyPlus.equals("1")){
                PayOrderResultInfo payOrderResultInfoGrade = this.calculateGradeDiscount(params);
                gradeDiscountAmt = new BigDecimal(payOrderResultInfoGrade.getDiscountAmt());
                discountAmt = discountAmt.add(gradeDiscountAmt);
            }

        }
        amt = receivableAmt.subtract(discountAmt);  //应收金额
        discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? discountPrice : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);  //优惠价格
        payOrderResultInfo.setAmt(amt.toString());
        payOrderResultInfo.setDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(params.get("cardEnabledFlag").toString().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
            if(cardRechargeSettingList !=null && cardRechargeSettingList.size() >0){
                String isGradeSetting = cardRechargeSettingList.get(0).getIsGradeSetting(); //是否叠加等级方案
                String isMarket = cardRechargeSettingList.get(0).getIsMarket(); //等候否叠加营销方案
                if(isMarket.equals("1")){
                    if(isGradeSetting.equals("1")){
                        payOrderResultInfo.setDzkAmt(amt.toString());
                    }else {
                        //如果电子卡设置执行营销方案不执行等级优惠 则 电子卡支付金额 =实收金额+等级优惠金额
                        BigDecimal subtract = amt.add(gradeDiscountAmt);
                        payOrderResultInfo.setDzkAmt(subtract.toString());
                    }
                }else {
                    if(isGradeSetting.equals("1")){
                        //如果电子卡设置不执行营销方案执行等级优惠 则 电子卡支付金额 =应收金额-等级优惠金额
                        BigDecimal subtract = receivableAmt.subtract(gradeDiscountAmt);
                        payOrderResultInfo.setDzkAmt(subtract.toString());
                    }else {
                        payOrderResultInfo.setDzkAmt(receivableAmt.toString());
                    }
                }
            }
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(Integer.valueOf(params.get("stationId").toString()), params.get("cardOilsType").toString(), params.get("unionId").toString());
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setCardOilsType(map.get("cardOilsType"));
        }
        return  payOrderResultInfo;
    }

    //计算满减
    public PayOrderResultInfo calculateManJianDiscount(Map<String ,Object> params){

        BigDecimal oilPrice = new BigDecimal(params.get("oilPrice").toString());    //油品价格
        BigDecimal receivableAmt = new BigDecimal(params.get("receivableAmt").toString());   //应收金额
        BigDecimal oilLiters = new BigDecimal("0.00");  //加油升数
        BigDecimal discountAmt = new BigDecimal(0);  //优惠金额
        BigDecimal amt = new BigDecimal(0);
        BigDecimal discountPrice = oilPrice;
        BigDecimal gradeDiscountAmt = new BigDecimal(0);    //等级优惠金额
        //加油升数
        oilLiters = receivableAmt.divide(oilPrice,2, BigDecimal.ROUND_HALF_UP);
        if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
            oilLiters = receivableAmt.divide(oilPrice,2, BigDecimal.ROUND_UP);
        }
        PayOrderResultInfo payOrderResultInfo = new PayOrderResultInfo();
        params.put("discountPlanType", "1");
        List<Map> customerMarkertPlanList = customerGradeServices.getCustomerMarkertPlanList(params);
        if(customerMarkertPlanList !=null && customerMarkertPlanList.size() >0){
            BigDecimal discountAmt_b = new BigDecimal(customerMarkertPlanList.get(0).get("discountAmt").toString());                //条件金额
            BigDecimal gasoilDiscountAmt_b = new BigDecimal(customerMarkertPlanList.get(0).get("gasoilDiscountAmt").toString());    //享受的优惠
            if(receivableAmt.compareTo(discountAmt_b) == 1 || receivableAmt.compareTo(discountAmt_b) == 0){
                discountAmt = receivableAmt.divide(discountAmt_b, 2, BigDecimal.ROUND_HALF_UP).multiply(gasoilDiscountAmt_b);  //优惠金额
                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            //是否共享会员等级优惠叠加: 1 代表是； 2 代表否；
            String vipDiscountyPlus = customerMarkertPlanList.get(0).get("vipDiscountyPlus").toString();
            if(vipDiscountyPlus.equals("1")){
                PayOrderResultInfo payOrderResultInfoGrade = this.calculateGradeDiscount(params);
                discountAmt = discountAmt.add(new BigDecimal(payOrderResultInfoGrade.getDiscountAmt()));
            }
        }
        amt = receivableAmt.subtract(discountAmt);  //应收金额
        discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? discountPrice : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);  //优惠价格
        payOrderResultInfo.setAmt(amt.toString());
        payOrderResultInfo.setDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(params.get("cardEnabledFlag").toString().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
            if(cardRechargeSettingList !=null && cardRechargeSettingList.size() >0){
                String isGradeSetting = cardRechargeSettingList.get(0).getIsGradeSetting(); //是否叠加等级方案
                String isMarket = cardRechargeSettingList.get(0).getIsMarket(); //等候否叠加营销方案
                if(isMarket.equals("1")){
                    if(isGradeSetting.equals("1")){
                        payOrderResultInfo.setDzkAmt(amt.toString());
                    }else {
                        //如果电子卡设置执行营销方案不执行等级优惠 则 电子卡支付金额 =实收金额+等级优惠金额
                        BigDecimal subtract = amt.add(gradeDiscountAmt);
                        payOrderResultInfo.setDzkAmt(subtract.toString());
                    }
                }else {
                    if(isGradeSetting.equals("1")){
                        //如果电子卡设置不执行营销方案执行等级优惠 则 电子卡支付金额 =应收金额-等级优惠金额
                        BigDecimal subtract = receivableAmt.subtract(gradeDiscountAmt);
                        payOrderResultInfo.setDzkAmt(subtract.toString());
                    }else {
                        payOrderResultInfo.setDzkAmt(receivableAmt.toString());
                    }
                }
            }
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(Integer.valueOf(params.get("stationId").toString()), params.get("cardOilsType").toString(), params.get("unionId").toString());
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setCardOilsType(map.get("cardOilsType"));
        }
        return payOrderResultInfo;
    }

    //计算等级优惠
    public PayOrderResultInfo calculateGradeDiscount(Map<String ,Object> params){
        String oilName = params.get("oilName").toString();
        String stationId = params.get("stationId").toString();
        BigDecimal oilPrice = new BigDecimal(params.get("oilPrice").toString());    //油品价格
        BigDecimal receivableAmt = new BigDecimal(params.get("receivableAmt").toString());   //应收金额
        BigDecimal oilLiters = new BigDecimal("0.00");  //加油升数
        BigDecimal discountAmt = new BigDecimal(0);  //优惠金额
        BigDecimal amt = new BigDecimal(0);
        BigDecimal discountPrice = oilPrice;
        PayOrderResultInfo payOrderResultInfo = new PayOrderResultInfo();

        oilLiters = receivableAmt.divide(oilPrice,2, BigDecimal.ROUND_HALF_UP);
        if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
            oilLiters = receivableAmt.divide(oilPrice,2, BigDecimal.ROUND_UP);
        }
        //当前客户是否已存在当前油站客户信息中
        CustomerManage customerManage = new CustomerManage();
        customerManage.setPhoneNumber(params.get("mobilePhone").toString());
        customerManage.setOilName(oilName);
        customerManage.setStationId(Integer.valueOf(stationId));
        CustomerManage customerManageInfo = customerManagerService.getCustomerManageInfo(customerManage);
        if(customerManageInfo !=null){
            //当前客户所加油的订单已存在等级时
            double amtSum = customerManageInfo.getAmt().doubleValue();   //当前客户已累计的金额
            List<Map> cList = customerGradeServices.getCustomerGradeListOrderByDesc(params);    //获取油站的等级优惠方案 倒叙查询规则
            if(cList !=null && cList.size() >0){    //当前油站设置等级方案时
                for(Map m : cList){
                    if(amtSum >= Double.valueOf(m.get("memberConditStart").toString())){
                        discountAmt = oilLiters.multiply(new BigDecimal(m.get("discountAmt").toString()));
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                        break;
                    }
                }
            }
        }else {
            //当前客户所加油的订单不存在等级时
            List<Map> customerGradeList = customerGradeServices.getCustomerGradeList(params);   //升序查询 取第一条
            if(customerGradeList !=null && customerGradeList.size() >0){
                discountAmt = oilLiters.multiply(new BigDecimal(customerGradeList.get(0).get("discountAmt").toString()));
                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        }
        amt = receivableAmt.subtract(discountAmt);  //应收金额
        discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? discountPrice : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);  //优惠价格
        payOrderResultInfo.setAmt(amt.toString());
        payOrderResultInfo.setDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(params.get("cardEnabledFlag").toString().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
            if(cardRechargeSettingList !=null && cardRechargeSettingList.size() >0){
                String isGradeSetting = cardRechargeSettingList.get(0).getIsGradeSetting();
                if(isGradeSetting.equals("1")){
                    payOrderResultInfo.setDzkAmt(amt.toString());
                }
            }
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(Integer.valueOf(params.get("stationId").toString()), params.get("cardOilsType").toString(), params.get("unionId").toString());
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setCardOilsType(map.get("cardOilsType"));
        }
        return  payOrderResultInfo;
    }

    //查询用户电子会员卡余额
    public Map<String, String>  selectCardBalance(Integer stationId, String cardOilsType, String unionId) {
        CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
        customerElectronicCard.setCardOilsType(cardOilsType);
        customerElectronicCard.setStationId(stationId);
        customerElectronicCard.setUnionId(unionId);
        CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getElectronicCardInfoByUnionId(customerElectronicCard);
        BigDecimal balance = null;
        String cardOilsType1 ="";
        Map<String, String> result = new HashMap<>();
        if(electronicCardInfo !=null){
            balance = electronicCardInfo.getAmt();
            cardOilsType1 = electronicCardInfo.getCardOilsType();
            result.put("balance",balance.toString());
            result.put("cardOilsType",cardOilsType1);
        }
        return result;
    }


    /*
     * ===========================计算订单金额======================================
     * 第一次修订时间：2021年4月20日15:31:30
     * 修订标题：修订优惠计算
     * 修订内容 ：
     *    修改为目前只有三种优惠：根据立减、满减、独立直降；
     *    注释：优惠为 1 是：表示不走满减、立减、独立直降优惠，只走等级直降的优惠；
     *    条件规则：
     *      一，优先满减（只有一档，不存在多档！）、立减（只有一档，不存在多档！）、独立直降（只有一档）
     *      二，若用户消费门槛 >= 优惠门槛，且启用优惠叠加时，则计算优惠规则和等级优惠规则；
     *         若用户消费门槛 >= 优惠门槛，且不启用优惠叠加时，则只计算优惠规则；
     *         若用户消费门槛 <  优惠门槛，且启用优惠叠加时，则只计算等级规则；
     *         若用户消费门槛 <  优惠门槛，且不启用优惠叠加时，则只计算等级规则；
     *
     * ===========================================================================
     */
    public Map<String ,Object> calculateAmtNew(PayOrderRequest payOrderRequest){
        Map<String ,Object> resultMap = new HashMap<>();
        if(payOrderRequest.getReceivableAmt() !=null){  //应收金额
            Double receivableAmt = payOrderRequest.getReceivableAmt();  //应收金额 用户输入的金额
            Integer stationId = payOrderRequest.getStationId();         //油站ID

            //String oilGun = payOrderRequest.getOilGun();                //油枪号
            String oilName = payOrderRequest.getOilName();          //油品名称
            String openId = payOrderRequest.getOpenId();        //用户的openId
            String mobilePhone = payOrderRequest.getCustomerPhone();        //客户手机号
            //获取油品价格
            StationOilPrice stationOilPrice = new StationOilPrice();
            stationOilPrice.setStationId(stationId);
            stationOilPrice.setOilName(oilName);
            StationOilPrice oilPriceInfo = stationService.getStationOilPrice(stationOilPrice);
            String oilPrice = oilPriceInfo.getOilPrice();
            //String stationNanme = oilPriceInfo.getStationNanme();
            BigDecimal oilLiters = new BigDecimal(0);
            BigDecimal discountAmt =new BigDecimal(0);
            BigDecimal discountPrice = null;
            BigDecimal amt = null;

            //resultMap.put("stationName", stationNanme);
            resultMap.put("oilPrice", oilPrice);        //油品价格
            resultMap.put("receivableAmt", receivableAmt);        //应收价格
            //该油站的优惠方式
            String stationDiscountWay = stationService.getStationDiscountWay(stationId.toString());
            Map<String ,Object> params = new HashMap<String, Object>();
            params.put("stationId", stationId);
            params.put("oilName", oilName);
            params.put("receivableAmt", receivableAmt);
            params.put("oilPrice", oilPrice);
            params.put("mobilePhone", mobilePhone);
            params.put("minaOpenid", openId);
            BigDecimal receivableAmt_b = new BigDecimal(receivableAmt); //传入的应收金额
            switch (stationDiscountWay){
                case "1":       //1.等级直降
                    //查询等级直降的优惠方式
                    //查询客户等级信息
                    List<Map<String, Object>> customerGradeInfo = customerGradeServices.getCustomerGradeInfo(params);
                    if(customerGradeInfo != null && customerGradeInfo.size() >0){   //已存在客户等级信息
                        //使用客户已存在的等级计算优惠
                        oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                        if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                            oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                        }
                        if(customerGradeInfo.get(0).containsKey("gasoilDiscountLitre")){    //表示可以查到客户在当前油站的等级信息,油站等级体系没有删除
                            if(customerGradeInfo.get(0).get("gasoilDiscountLitre") !=null){
                                discountAmt = oilLiters.multiply(new BigDecimal(customerGradeInfo.get(0).get("gasoilDiscountLitre").toString()));
                                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                            }else {
                                discountAmt =new BigDecimal("0.00");
                            }
                        }else {
                            //如果存在客户等级，但油站修改等级体系，客户等级已超出等级体系时
                            List<Map> cList = customerGradeServices.getCustomerGradeListOrderByDesc(params);
                            if(cList !=null && cList.size() >0){
                                CustomerManage customerManage = new CustomerManage();
                                customerManage.setStationId(Integer.valueOf(params.get("stationId").toString()));    //油站ID
                                customerManage.setOilName(params.get("oilName").toString());                        //油品名称
                                customerManage.setPhoneNumber(params.get("mobilePhone").toString());
                                customerManage.setMinaOpenid(params.get("minaOpenid").toString());
                                CustomerManage existCustomer = customerManagerService.getCustomerManageInfo(customerManage);         //已存在用户信息 existCustomer
                                for(Map m : cList){
                                    if(Double.valueOf(existCustomer.getAmt().toString()) >= Double.valueOf(m.get("memberConditStart").toString())){
                                        discountAmt = oilLiters.multiply(new BigDecimal(cList.get(0).get("gasoilDiscountLitre").toString()));
                                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                                        break;
                                    }
                                }
                            }
                        }
                        amt = receivableAmt_b.subtract(discountAmt);
                        discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                        resultMap.put("discountAmt", discountAmt.doubleValue());
                        resultMap.put("amt", amt.doubleValue());
                        resultMap.put("oilLiters", oilLiters.doubleValue());
                        resultMap.put("discountPrice", discountPrice.doubleValue());
                    }else {
                        //不存在客户等级信息时，查询油站的客户等级直降优惠（查询结果根据会员成长值条件做升序查询）
                        List<Map> customerGradeList = customerGradeServices.getCustomerGradeList(params);
                        //如果存在
                        if(customerGradeList !=null && customerGradeList.size() >0){
                            //用户第一次购买 取等级最低初始会员的优惠条件计算
                            oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                            if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                                oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                            }

                            if(customerGradeList.get(0).get("gasoilDiscountLitre") !=null){
                                discountAmt = oilLiters.multiply(new BigDecimal(customerGradeList.get(0).get("gasoilDiscountLitre").toString()));
                                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                            }else {
                                discountAmt =new BigDecimal("0.00");
                            }
                            amt = receivableAmt_b.subtract(discountAmt);
                            discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                            resultMap.put("discountAmt", discountAmt.doubleValue());
                            resultMap.put("amt", amt.doubleValue());
                            resultMap.put("oilLiters", oilLiters.doubleValue());
                            resultMap.put("discountPrice", discountPrice.doubleValue());
                        }else {
                            //不存在
                            resultMap.put("discountAmt", 0);
                            resultMap.put("amt", receivableAmt.doubleValue());
                            oilLiters = new BigDecimal(receivableAmt).divide(new BigDecimal(oilPrice), 2, BigDecimal.ROUND_UP);
                            resultMap.put("oilLiters", oilLiters.doubleValue());
                            resultMap.put("discountPrice", oilPrice);
                        }
                    }
                    break;
                case "2":       //2.满减
                    params.put("discountPlanType", "1");
                    //营销方案
                    List<Map> customerMarkertPlanList_1 = customerGradeServices.getCustomerMarkertPlanList(params);
                    //有优惠规则
                    if(customerMarkertPlanList_1 !=null && customerMarkertPlanList_1.size() >0){
                        //是否共享会员优惠叠加: 1 代表是； 2 代表否；
                        String vipDiscountyPlus = customerMarkertPlanList_1.get(0).get("vipDiscountyPlus").toString();
                        //如果当前应收金额大于条件金额
                        BigDecimal discountAmt_b = new BigDecimal(customerMarkertPlanList_1.get(0).get("discountAmt").toString());   //条件金额
                        if(receivableAmt_b.compareTo(discountAmt_b) ==1 || receivableAmt_b.compareTo(discountAmt_b) ==0){
                            BigDecimal gasoilDiscountAmt_b = new BigDecimal(customerMarkertPlanList_1.get(0).get("gasoilDiscountAmt").toString());   //每满多少优惠多少的金额
                            discountAmt = receivableAmt_b.divide(discountAmt_b, 2, BigDecimal.ROUND_HALF_UP).multiply(gasoilDiscountAmt_b);  //优惠金额
                            discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                            amt = receivableAmt_b.subtract(discountAmt);   //实收金额
                            oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                            if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                                oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                            }
                            discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                            switch (vipDiscountyPlus){
                                case "1":
                                    Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                                    discountAmt = discountAmt.add(new BigDecimal(map.get("discountAmt").toString()));
                                    amt = receivableAmt_b.subtract(discountAmt);
                                    discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                    resultMap.put("discountAmt", discountAmt.doubleValue());
                                    resultMap.put("amt", amt.doubleValue());
                                    resultMap.put("oilLiters", oilLiters.doubleValue());
                                    resultMap.put("discountPrice", discountPrice.doubleValue());
                                    break;
                                case "2":
                                    resultMap.put("discountAmt", discountAmt.doubleValue());
                                    resultMap.put("amt", amt.doubleValue());
                                    resultMap.put("oilLiters", oilLiters.doubleValue());
                                    resultMap.put("discountPrice", discountPrice.doubleValue());
                                    break;
                            }
                        }else{
                            switch (vipDiscountyPlus){
                                case "1":
                                    Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                                    discountAmt = discountAmt.add(new BigDecimal(map.get("discountAmt").toString()));
                                    oilLiters = new BigDecimal(map.get("oilLiters").toString());
                                    amt = receivableAmt_b.subtract(discountAmt);
                                    discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                    resultMap.put("discountAmt", discountAmt.doubleValue());
                                    resultMap.put("amt", amt.doubleValue());
                                    resultMap.put("oilLiters", oilLiters.doubleValue());
                                    resultMap.put("discountPrice", discountPrice.doubleValue());
                                    break;
                                case "2":
                                    resultMap.put("discountAmt", 0);
                                    resultMap.put("amt", receivableAmt.doubleValue());
                                    oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                                    if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                                        oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                                    }
                                    resultMap.put("oilLiters", oilLiters.doubleValue());
                                    resultMap.put("discountPrice", oilPrice);
                                    break;
                            }
                        }
                    }else {
                        //用户没有设置优惠规则时
                        Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                        resultMap.put("discountAmt", map.get("discountAmt").toString());
                        resultMap.put("amt", map.get("amt").toString());
                        resultMap.put("oilLiters", map.get("oilLiters").toString());
                        resultMap.put("discountPrice", map.get("discountPrice").toString());
                    }
                    break;
                case "3":       //3.立减
                    params.put("discountPlanType", "2");
                    //营销方案
                    List<Map> customerMarkertPlanList_2 = customerGradeServices.getCustomerMarkertPlanList(params);
                    if(customerMarkertPlanList_2 !=null && customerMarkertPlanList_2.size() >0){
                        //是否共享会员优惠叠加: 1 代表是； 2 代表否；
                        String vipDiscountyPlus = customerMarkertPlanList_2.get(0).get("vipDiscountyPlus").toString();
                        //如果当前应收金额大于条件金额
                        BigDecimal discountAmt_b = new BigDecimal(customerMarkertPlanList_2.get(0).get("discountAmt").toString());   //条件金额
                        if(receivableAmt_b.compareTo(discountAmt_b) ==1 || receivableAmt_b.compareTo(discountAmt_b) ==0){
                            BigDecimal gasoilDiscountAmt_b = new BigDecimal(customerMarkertPlanList_2.get(0).get("gasoilDiscountAmt").toString());   //满多少优惠多少的金额
                            discountAmt = gasoilDiscountAmt_b;  //优惠金额
                            amt = receivableAmt_b.subtract(gasoilDiscountAmt_b);   //实收金额
                            oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                            if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                                oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                            }
                            discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_UP);
                            switch (vipDiscountyPlus){
                                case "1":
                                    Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                                    discountAmt = discountAmt.add(new BigDecimal(map.get("discountAmt").toString()));
                                    amt = receivableAmt_b.subtract(discountAmt);
                                    discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                    //discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_UP);
                                    resultMap.put("discountAmt", discountAmt.doubleValue());
                                    resultMap.put("amt", amt.doubleValue());
                                    resultMap.put("oilLiters", oilLiters.doubleValue());
                                    resultMap.put("discountPrice", discountPrice.doubleValue());
                                    break;
                                case "2":
                                    resultMap.put("discountAmt", discountAmt.doubleValue());
                                    resultMap.put("amt", amt.doubleValue());
                                    resultMap.put("oilLiters", oilLiters.doubleValue());
                                    resultMap.put("discountPrice", discountPrice.doubleValue());
                                    break;
                            }
                        }else {
                            //不满足优惠条件
                            switch (vipDiscountyPlus) {
                                case "1":
                                    Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                                    discountAmt = discountAmt.add(new BigDecimal(map.get("discountAmt").toString()));
                                    oilLiters = new BigDecimal(map.get("oilLiters").toString());
                                    amt = receivableAmt_b.subtract(discountAmt);
                                    discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                    //discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_UP);
                                    resultMap.put("discountAmt", discountAmt.doubleValue());
                                    resultMap.put("amt", amt.doubleValue());
                                    resultMap.put("oilLiters", oilLiters.doubleValue());
                                    resultMap.put("discountPrice", discountPrice.doubleValue());
                                    break;
                                case "2":
                                    resultMap.put("discountAmt", 0);
                                    resultMap.put("amt", receivableAmt.doubleValue());
                                    oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                                    if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                                        oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                                    }
                                    resultMap.put("oilLiters", oilLiters.doubleValue());
                                    resultMap.put("discountPrice", oilPrice);
                                    break;
                            }
                        }
                    }else {
                        //用户没有设置优惠规则时
                        Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                        resultMap.put("discountAmt", map.get("discountAmt").toString());
                        resultMap.put("amt", map.get("amt").toString());
                        resultMap.put("oilLiters", map.get("oilLiters").toString());
                        resultMap.put("discountPrice", map.get("discountPrice").toString());
                    }
                    break;
                case "4":       //4.独立直降
                    params.put("discountPlanType", "3");
                    //营销方案
                    List<Map> customerMarkertPlanList_3 = customerGradeServices.getCustomerMarkertPlanList(params);
                    if(customerMarkertPlanList_3 !=null && customerMarkertPlanList_3.size() >0){
                        //是否共享会员优惠叠加: 1 代表是； 2 代表否；
                        String vipDiscountyPlus_4 = customerMarkertPlanList_3.get(0).get("vipDiscountyPlus").toString();
                        BigDecimal discountAmt_b = new BigDecimal(customerMarkertPlanList_3.get(0).get("discountAmt").toString());   //条件金额
                        BigDecimal gasoilDiscountAmt_b = new BigDecimal(customerMarkertPlanList_3.get(0).get("gasoilDiscountAmt").toString());
                        oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                        if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                            oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                        }
                        if(customerMarkertPlanList_3.get(0).get("discountTerm").toString().equals("1")){   //按升数优惠
                            if(oilLiters.compareTo(discountAmt_b) ==1 || oilLiters.compareTo(discountAmt_b) ==0){
                                //计算
                                discountAmt = oilLiters.multiply(gasoilDiscountAmt_b);
                                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                                amt = receivableAmt_b.subtract(discountAmt);
                                discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                //discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_UP);        //优惠价格

                                if(vipDiscountyPlus_4.equals("1")){
                                    Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                                    discountAmt = discountAmt.add(new BigDecimal(map.get("discountAmt").toString()));
                                    amt = receivableAmt_b.subtract(discountAmt);
                                    discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                    //discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_UP);
                                }
                                resultMap.put("discountAmt", discountAmt.doubleValue());
                                resultMap.put("amt", amt.doubleValue());
                                resultMap.put("oilLiters", oilLiters.doubleValue());
                                resultMap.put("discountPrice", discountPrice.doubleValue());
                                break;
                            }else {
                                //不满足优惠条件
                                switch (vipDiscountyPlus_4) {
                                    case "1":
                                        Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                                        discountAmt = discountAmt.add(new BigDecimal(map.get("discountAmt").toString()));
                                        oilLiters = new BigDecimal(map.get("oilLiters").toString());
                                        amt = receivableAmt_b.subtract(discountAmt);
                                        discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                        resultMap.put("discountAmt", discountAmt.doubleValue());
                                        resultMap.put("amt", amt.doubleValue());
                                        resultMap.put("oilLiters", oilLiters.doubleValue());
                                        resultMap.put("discountPrice", discountPrice.doubleValue());
                                        break;
                                    case "2":
                                        resultMap.put("discountAmt", 0);
                                        resultMap.put("amt", receivableAmt.doubleValue());
                                        oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                                        if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                                            oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                                        }
                                        resultMap.put("oilLiters", oilLiters.doubleValue());
                                        resultMap.put("discountPrice", oilPrice);
                                        break;
                                }
                            }
                        }else if(customerMarkertPlanList_3.get(0).get("discountTerm").toString().equals("2")){     //按金额优惠
                            if(receivableAmt_b.compareTo(discountAmt_b) ==1 || receivableAmt_b.compareTo(discountAmt_b) ==0){
                                discountAmt = oilLiters.multiply(gasoilDiscountAmt_b);
                                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                                amt = receivableAmt_b.subtract(discountAmt);
                                discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                //是否共享会员优惠叠加
                                if(vipDiscountyPlus_4.equals("1")){
                                    Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                                    discountAmt = discountAmt.add(new BigDecimal(map.get("discountAmt").toString()));
                                    amt = receivableAmt_b.subtract(discountAmt);
                                    discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                    //discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_UP);
                                }
                                resultMap.put("discountAmt", discountAmt.doubleValue());
                                resultMap.put("amt", amt.doubleValue());
                                resultMap.put("oilLiters", oilLiters.doubleValue());
                                resultMap.put("discountPrice", discountPrice.doubleValue());
                                break;
                            }else {
                                //不满足优惠条件
                                switch (vipDiscountyPlus_4) {
                                    case "1":
                                        Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                                        discountAmt = discountAmt.add(new BigDecimal(map.get("discountAmt").toString()));
                                        oilLiters = new BigDecimal(map.get("oilLiters").toString());
                                        amt = receivableAmt_b.subtract(discountAmt);
                                        discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                                        resultMap.put("discountAmt", discountAmt.doubleValue());
                                        resultMap.put("amt", amt.doubleValue());
                                        resultMap.put("oilLiters", oilLiters.doubleValue());
                                        resultMap.put("discountPrice", discountPrice.doubleValue());
                                        break;
                                    case "2":
                                        resultMap.put("discountAmt", 0);
                                        resultMap.put("amt", receivableAmt.doubleValue());
                                        oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                                        if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                                            oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                                        }
                                        resultMap.put("oilLiters", oilLiters.doubleValue());
                                        resultMap.put("discountPrice", oilPrice);
                                        break;
                                }
                            }
                        }
                    }else {
                        //没有设置优惠条件时
                        Map<String, Object> map = this.calcuteDengJiZhiJiang(params);
                        resultMap.put("discountAmt", map.get("discountAmt").toString());
                        resultMap.put("amt", map.get("amt").toString());
                        resultMap.put("oilLiters", map.get("oilLiters").toString());
                        resultMap.put("discountPrice", map.get("discountPrice").toString());
                    }
                    break;
            }
        }
        return resultMap;
    }

    //计算


    //计算等级直降
    public  Map<String, Object> calcuteDengJiZhiJiang(Map params){
        Double receivableAmt = Double.valueOf(params.get("receivableAmt").toString());
        Map<String, Object> resultMap = new HashMap();
        BigDecimal oilLiters = null;
        BigDecimal discountAmt =new BigDecimal(0);
        BigDecimal discountPrice = null;
        BigDecimal amt = null;
        BigDecimal receivableAmt_b = new BigDecimal(receivableAmt); //传入的应收金额
        String oilPrice = params.get("oilPrice").toString();
        List<Map<String, Object>> customerGradeInfo = customerGradeServices.getCustomerGradeInfo(params);
        if(customerGradeInfo != null && customerGradeInfo.size() >0){   //已存在客户等级信息
            //使用客户已存在的等级计算优惠
            oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
            if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
            }

            if(customerGradeInfo.get(0).containsKey("gasoilDiscountLitre")){
                if(customerGradeInfo.get(0).get("gasoilDiscountLitre") !=null){
                    discountAmt = oilLiters.multiply(new BigDecimal(customerGradeInfo.get(0).get("gasoilDiscountLitre").toString()));
                    discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                }else {
                    discountAmt =new BigDecimal("0.00");
                }
            }else {
                //如果存在客户等级，但油站修改等级体系，客户等级已超出等级体系时
                List<Map> cList = customerGradeServices.getCustomerGradeListOrderByDesc(params);
                if(cList !=null && cList.size() >0){
                    CustomerManage customerManage = new CustomerManage();
                    customerManage.setStationId(Integer.valueOf(params.get("stationId").toString()));    //油站ID
                    customerManage.setOilName(params.get("oilName").toString());    //油品名称
                    customerManage.setPhoneNumber(params.get("mobilePhone").toString());
                    customerManage.setMinaOpenid(params.get("minaOpenid").toString());
                    CustomerManage existCustomer = customerManagerService.getCustomerManageInfo(customerManage);         //已存在用户信息 existCustomer
                    for(Map m : cList){
                        if(Double.valueOf(existCustomer.getAmt().toString()) >= Double.valueOf(m.get("memberConditStart").toString())){
                            discountAmt = oilLiters.multiply(new BigDecimal(cList.get(0).get("gasoilDiscountLitre").toString()));
                            discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                            break;
                        }
                    }
                }
            }
            amt = receivableAmt_b.subtract(discountAmt);
            discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
            //discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_UP);
            resultMap.put("discountAmt", discountAmt.doubleValue());
            resultMap.put("amt", amt.doubleValue());
            resultMap.put("oilLiters", oilLiters.doubleValue());
            resultMap.put("discountPrice", discountPrice.doubleValue());
        }else {
            //不存在客户等级信息时，查询油站的客户等级直降优惠（查询结果根据会员成长值条件做升序查询）
            List<Map> customerGradeList = customerGradeServices.getCustomerGradeList(params);
            //如果存在
            if(customerGradeList !=null && customerGradeList.size() >0){
                //用户第一次购买 取等级最低初始会员的优惠条件计算
                oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                    oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                }
                if(customerGradeList.get(0).get("gasoilDiscountLitre") !=null){
                    discountAmt = oilLiters.multiply(new BigDecimal(customerGradeList.get(0).get("gasoilDiscountLitre").toString()));
                    discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                }else {
                    discountAmt =new BigDecimal("0.00");
                }
                amt = receivableAmt_b.subtract(discountAmt);
                discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? new BigDecimal(oilPrice) : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                //discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_UP);
                resultMap.put("discountAmt", discountAmt.doubleValue());
                resultMap.put("amt", amt.doubleValue());
                resultMap.put("oilLiters", oilLiters.doubleValue());
                resultMap.put("discountPrice", discountPrice.doubleValue());
            }else {
                //不存在
                resultMap.put("discountAmt", 0);
                resultMap.put("amt", receivableAmt.doubleValue());
                oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_HALF_UP);   //加油升数
                if(!oilLiters.toString().substring(oilLiters.toString().indexOf(".") + 1).equals("00")){
                    oilLiters = receivableAmt_b.divide(new BigDecimal(oilPrice),2, BigDecimal.ROUND_UP);
                }
                resultMap.put("oilLiters", oilLiters.doubleValue());
                resultMap.put("discountPrice", oilPrice);
            }
        }
        return resultMap;
    }

    /**
     * 根据订单号获取订单信息
     * produces="application/json;charset=UTF-8",consumes = "application/json",
     * @RequestBody String orderno
     * @param
     * @return
     */
    @RequestMapping(value = "/getPayOrderList", method = RequestMethod.GET)
    @ResponseBody
    public String getPayOrderList(@RequestParam String orderNo,String openId,String userType){
        Gson gson =new Gson();
        ResultData resultData =null;
        //根据token 和 usertype来判断用户是否存在
        boolean flag = appUserInfoService.selectAppUserInfo(openId,userType);
        if(flag){
            if(StringUtils.isNotBlank(orderNo)){
                PayOrderRequest payOrderRequest =new PayOrderRequest();
                payOrderRequest.setOrderNo(orderNo);
                List<PayOrder> payOrderList = payOrderService.getPayOrderList(payOrderRequest.getOrderNo());
                resultData=ResultData.success(payOrderList);
            }else {
                resultData=ResultData.error(CodeMsg.SEARCH_FAIL);
            }
        }else{
            resultData=ResultData.error(CodeMsg.USER_NOT_EXSIST);
        }
        return gson.toJson(resultData);
    }

    /*
     * 根据用户openId和用户类型userType查询用户订单
     * @param openId
     * @param userType
     * @return
     */
    @RequestMapping(value = "/getOrderListByOpenIdAndUserType", method = RequestMethod.GET)
    @ResponseBody
    public String getOrderListByOpenIdAndUserType(@RequestParam("openId") String openId, @RequestParam("userType") String userType){
        Gson gson =new Gson();
        ResultData resultData =null;
            if(StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(userType)){
                AppUserInfo appUserInfo = new AppUserInfo();
                switch (userType){
                    case "1":
                        appUserInfo.setBlogOpenid(openId);
                        break;
                    case "2":
                        appUserInfo.setMinaOpenid(openId);
                        break;
                }
                List<PayOrder> payOrderList = payOrderService.getOrderListByOpenIdAndUserType(appUserInfo);
                resultData=ResultData.success(payOrderList);
            }else {
                resultData=ResultData.error(CodeMsg.SEARCH_FAIL);
            }

        return gson.toJson(resultData);
    }
}

