package com.platform.yijia.controller;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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.text.SimpleDateFormat;
import java.util.*;

@Controller
@YiJiaRequest()
@CrossOrigin
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;
    @Resource
    private LabelService labelService;
    @Resource
    private StationOilGunService stationOilGunService;

    //小程序支付生成订单
    @RequestMapping(value = "/AddPayOrderInfoNew", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String  AddPayOrderInfoNew(@RequestBody PayOrderRequest payOrderRequest){
        logger.info("生成订单前端传来参数油站ID："+payOrderRequest.getStationId()+"; 用户openId："+ payOrderRequest.getOpenId() +"; 加油员ID：" +payOrderRequest.getPersonnelId()+ ";");
        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 ){
            appUserInfo.setUserType(payOrderRequest.getUserType());
            switch (payOrderRequest.getUserType()){
                case "1":       //小程序
                    appUserInfo.setMinaOpenid(payOrderRequest.getOpenId());
                    break;
                case "2":       //支付宝公众号
                    appUserInfo.setALiId(payOrderRequest.getOpenId());
                    break;
            }
            StationInfo stationInfo = new StationInfo();
            stationInfo.setStationId(payOrderRequest.getStationId());
            StationInfo stationInfos = stationService.selectStationInfo(stationInfo);
            Map<String ,Object> resultMap = new HashMap<>();            //返回结果集
            if(stationInfos !=null){
                payOrder.setStationName(stationInfos.getStationName());
                //获取油站图片和名称
                resultMap.put("stationPic", stationInfos.getStationPic());
                resultMap.put("stationName", stationInfos.getStationName());
                appUserInfo.setStationId(stationInfos.getGroupId());
                AppUserInfo appUserInfos = appUserInfoService.getAppUserInfo(appUserInfo);
                if(appUserInfos !=null) {
                    //payOrderRequest存放参数原因：用于其他方法形参
                    payOrderRequest.setCardEnabledFlagGroup(stationInfos.getCardEnabledFlagGroup());        //集团是否开启电子卡
                    payOrderRequest.setCardRuleFlagGroup(stationInfos.getCardRuleFlagGroup());              //集团是否共享
                    payOrderRequest.setIntegralFlagGroup(stationInfos.getIntegralFlagGroup());              //集团是否启用积分功能
                    payOrderRequest.setIntegralRuleFlagGroup(stationInfos.getIntegralRuleFlagGroup());      //集团是否共享
                    payOrderRequest.setCustomerPhone(appUserInfos.getMobilePhone());                        //客户手机号; 注：此处存放手机号用于获取客户信息参数查询
                    payOrderRequest.setUnionId(appUserInfos.getUnionId());                                  //客户UnionId；注：此处存放unionId用于获取客户电子卡参数查询
                    payOrderRequest.setCustomerName(appUserInfos.getBlogNickName());                        //昵称
                    payOrderRequest.setGroupId(stationInfos.getGroupId());                                  //集团ID
                    payOrderRequest.setLabelFlag(stationInfos.getLabelFlag());                              //油站是否开启标签功能
                    payOrderRequest.setIsLngFlagGroup(stationInfos.getIsLngFlagGroup());                    //该集团是否为LNG第三方平台商：0，否；1，是；


                    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(Double.valueOf(payOrderRequest.getReceivableAmt()));                //订单应收金额
                    String oilName = payOrderRequest.getOilName();
                    //获取该油品所属哪一类
                    Oil oil = new Oil();
                    oil.setOilName(oilName);
                    oil.setDictType("oil_name");
                    Oil oilInfo = sysDictDataService.selectOilType(oil);
                    payOrder.setOilType(oilInfo.getOilsType());                                     //油品类型
                    String oilsType = oilInfo.getOilsType();                                        //获取订单类型
                    logger.info("订单油品类型：" + oilsType);
                    payOrderRequest.setCardOilsType(oilInfo.getOilsType());                         //电子卡类型；注：用于获取客户电子卡参数查询
                    payOrder.setOilName(oilName);                                                   //油品名称

                    if(oilsType.equals("3")){                                                       //订单类型是油品时计算
                        payOrder.setOrderType("2");
                        payOrder.setAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));        //非油品金额
                        payOrder.setDiscountAmt(Double.valueOf(0));                                 //优惠金额
                        payOrder.setOilPirce(payOrderRequest.getReceivableAmt());                   //非油品价格
                        payOrder.setOrderLiters("0");
                        resultMap.put("oilsCardFlag", "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);
                        logger.info("返回前端的结果：" +resultMap.toString());
                        //payOrderMapper.insertSelective(payOrder);
                    }else {
                        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()));
                        payOrder.setOrderType("1");
                        resultMap.put("discountPrice", payOrderResultInfo.getDiscountPrice());
                        if(payOrderResultInfo.getCardEnabledFlag() !=null && payOrderResultInfo.getCardEnabledFlag().equals("1")){
                            payOrder.setDzkAmt(Double.valueOf(payOrderResultInfo.getDzkAmt()));
                            //如果电子卡支付的金额与应收金额相同，则优惠价格有原有价格相同
//                            if(new BigDecimal(payOrderRequest.getReceivableAmt()).compareTo(new BigDecimal(payOrderResultInfo.getDzkAmt())) ==0){
//                                resultMap.put("discountPrice", payOrderResultInfo.getOilPrice());
//                            }
                            //payOrder.setDiscountAmt(Double.valueOf(payOrderResultInfo.getDzkDiscountAmt()));
                        }
                        resultMap.put("cardEnabledFlag", payOrderResultInfo.getCardEnabledFlag());
                        resultMap.put("oilsCardFlag", payOrderResultInfo.getOilsCardFlag());
                        resultMap.put("discountAmt", payOrderResultInfo.getDiscountAmt());    //优惠金额
                        resultMap.put("amt", payOrderResultInfo.getAmt());                   //实收价格
                        if(payOrderRequest.getIsLngFlagGroup() !=null && payOrderRequest.getIsLngFlagGroup().equals("1")){
                            payOrder.setSellAmt(Double.valueOf(payOrderResultInfo.getSellAmt()));
                            payOrder.setSellDiscountAmt(Double.valueOf(payOrderResultInfo.getSellDiscountAmt()));
                            payOrder.setSellOilPrice(Double.valueOf(payOrderResultInfo.getSellPrice()));
                            payOrder.setDriverDiscountAmt(Double.valueOf(payOrderResultInfo.getDriverDiscountAmt()));
                            resultMap.put("driverDiscountAmt", payOrderResultInfo.getDriverDiscountAmt());
                            resultMap.put("sellDiscountAmt", payOrderResultInfo.getSellDiscountAmt());
                        }
                        payOrder.setDriverOilPrice(Double.valueOf(payOrderResultInfo.getDiscountPrice()));
                        resultMap.put("receivableAmt", payOrderResultInfo.getReceivableAmt());           //应收价格
                        resultMap.put("oilLiters", payOrderResultInfo.getOilLiters());
                        resultMap.put("amt_dzk", payOrderResultInfo.getDzkAmt());
                        resultMap.put("discountAmt_dzk", payOrderResultInfo.getDzkDiscountAmt());        //电子卡优惠金额
                        resultMap.put("balance", payOrderResultInfo.getBalance());                       //电子卡余额
                        resultMap.put("cardOilsType", payOrderResultInfo.getCardOilsType());             //电子卡类型1.汽油； 2.柴油
                        resultMap.put("ordNo", ordNo);
                        logger.info("返回前端的结果：" +resultMap.toString());
                        //payOrderMapper.insertSelective(payOrder);
                    }

                    //根据油站和油枪获取加油员
                    if (payOrderRequest.getPersonnelId() != null && payOrderRequest.getPersonnelId() != "" && !payOrderRequest.getPersonnelId().equals("undefined")) {
                        //表示为一人一码：一个加油员一个码
                        Map<String, Object> params = new HashMap<>();
                        params.put("personnelId", payOrderRequest.getPersonnelId());
                        params.put("stationId", payOrderRequest.getStationId());
                        List<Map<String, Object>> list = stationOilGunService.selectOilGunByPersonalId(params);
                        if (list != null && list.size() > 0) {
                            if(list.get(0).containsKey("personnelName") && list.get(0).get("personnelName") !=null && list.get(0).get("personnelName").toString() !=""){
                                payOrder.setOilPersonnel(list.get(0).get("personnelName").toString());
                                payOrder.setOilPersonnelId(list.get(0).get("personnelId").toString());
                                payOrderMapper.insertSelective(payOrder);
                                resultData = ResultData.success(resultMap);
                            }else {
                                resultData = ResultData.error(CodeMsg.NO_PERSONNAL);
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.NO_PERSONNAL);
                        }
                    } else {
                        //resultData = ResultData.error(CodeMsg.NO_PERSONNAL);
                        //根据油站和油枪获取加油员
                        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 = "";
                            String oilPersonnelId ="";
                            for (Map per : mapResultList){
                                if(per.containsKey("personnelName") && per.get("personnelName").toString() !=null && per.get("personnelName").toString() !=""){
                                    oilPersonnel += per.get("personnelName").toString() +",";
                                    oilPersonnelId += per.get("personnelId").toString() +",";
                                }
                            }
                            if(oilPersonnel !=""){
                                payOrder.setOilPersonnel(oilPersonnel.substring(0, oilPersonnel.length()-1));   //加油员
                                payOrder.setOilPersonnelId(oilPersonnelId.substring(0, oilPersonnelId.length()-1));
                            }
//                            payOrder.setOilPersonnel(mapResultList.get(0).get("").toString());   //加油员
//                            payOrder.setOilPersonnelId(oilPersonnelId.substring(0, oilPersonnelId.length()-1));
                            payOrderMapper.insertSelective(payOrder);
                            resultData = ResultData.success(resultMap);
                        }else {
                            resultData = ResultData.error(CodeMsg.NO_PERSONNAL);
                        }
                    }
                }else {
                    //登录人验证失败
                    resultData=ResultData.error(CodeMsg.USER_NOT_EXSIST);
                }
            }else {
                resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
            }
        }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
        String userPhone = payOrderRequest.getCustomerPhone();        //用户手机号
        String customerName = payOrderRequest.getCustomerName();        //用户手机号
        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();  //是否开启电子卡
        String cardRuleFlag = result.get("cardRuleFlag").toString();        //是否共享电子卡储值规则
        String groupId = payOrderRequest.getGroupId().toString();           //集团ID

        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("cardRuleFlag", cardRuleFlag);
        params.put("groupId", groupId);
        params.put("unionId", payOrderRequest.getUnionId());
        params.put("cardOilsType", payOrderRequest.getCardOilsType());
        params.put("customerName", customerName);
        params.put("userPhone", userPhone);
        params.put("integralRuleFlagGroup", payOrderRequest.getIntegralRuleFlagGroup());    //      integralRuleFlagGroup;   //集团积分规则是否共享
        params.put("integralFlagGroup", payOrderRequest.getIntegralFlagGroup());            //      integralFlagGroup;       //集团是否开启积分功能
        params.put("cardRuleFlagGroup", payOrderRequest.getCardRuleFlagGroup());            //      cardRuleFlagGroup;       //集团是否共享电子卡充值规则
        params.put("cardEnabledFlagGroup", payOrderRequest.getCardEnabledFlagGroup());      //      cardEnabledFlagGroup;    //集团是否开启电子卡

        if(payOrderRequest.getIsLngFlagGroup() !=null && payOrderRequest.getIsLngFlagGroup().equals("1")){
            // isLngFlagGroup 表示该集团是否为LNG平台加气：0，否；1，是；
           // settlementType:结算价类型（1.直降，2.折扣）;  settlementPrice:结算价;  driverPrice:司机价;
            if(result.containsKey("settlementType") && result.get("settlementType") !=null && result.get("settlementType").toString() !=""){
                params.put("settlementType", result.get("settlementType").toString());
            }
            if(result.containsKey("settlementPrice") && result.get("settlementPrice") !=null && result.get("settlementPrice").toString() !=""){
                params.put("settlementPrice", result.get("settlementPrice").toString());
            }
            //driverPriceType 司机价类型（1.直降，2.折扣）;
            if(result.containsKey("driverPriceType") && result.get("driverPriceType") !=null && result.get("driverPriceType").toString() !=""){
                params.put("driverPriceType", result.get("driverPriceType").toString());
            }
            if(result.containsKey("driverPrice") && result.get("driverPrice") !=null && result.get("driverPrice").toString() !=""){
                params.put("driverPrice", result.get("driverPrice").toString());
            }

            payOrderResultInfo = this.calculateLngGroupStaDiscount(params);

        }else {
            CustomerLabel customerLabel = new CustomerLabel();
            customerLabel.setPhone(payOrderRequest.getCustomerPhone());
            customerLabel.setStationId(payOrderRequest.getStationId());
            //扫码进标签优惠：一码一签
            if(payOrderRequest.getLabelId() !=null){
                //如果前端传来labelId,则表示一码一签；
                params.put("labelId", payOrderRequest.getLabelId());
                payOrderResultInfo = this.calculateLabelDiscount(params);
                //是否强制将该扫码用户拉入此标签：0、否；1、是；
                if(payOrderResultInfo.getIsAddLabel() !=null && payOrderResultInfo.getIsAddLabel().equals("1")){
                    CustomerLabel customerLabel_info = labelService.getCustomerLabel(customerLabel);
                    if(customerLabel_info !=null){
                        customerLabel.setUpdateTime(new Date());
//                        customerLabel.setCreateBy(payOrderResultInfo.getLabelCreateBy());
//                        if(payOrderResultInfo.getLabelUpdateBy() !=null){
//                            customerLabel.setUpdateBy(payOrderResultInfo.getLabelUpdateBy());
//                        }
                        customerLabel.setLabelId(payOrderRequest.getLabelId());
                        labelService.updateCustomerLabel(customerLabel);
                    }else {
                        customerLabel.setCreateTime(new Date());
                        customerLabel.setDelFlag("0");
                        //customerLabel.setCreateBy(payOrderResultInfo.getLabelCreateBy());
                        customerLabel.setLabelId(payOrderRequest.getLabelId());
                        labelService.insertCustomerLabel(customerLabel);
                    }
                }
            }else {
                //按照正常优惠计算
                CustomerLabel customerLabelInfo = labelService.getCustomerLabel(customerLabel); //获取该用户是否在标签组内
                if(payOrderRequest.getLabelFlag() !=null && payOrderRequest.getLabelFlag().equals("1") && customerLabelInfo !=null){
                    //表示此用户为标签用户，计算标签用户优惠
                    params.put("labelId", customerLabelInfo.getLabelId());
                    payOrderResultInfo = this.calculateLabelDiscount(params);
                }else {
                    //不为标签用户时
                    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;
                        case "4":    //计算阶梯直降
                            payOrderResultInfo = this.calculateJieTiZhiJiangDiscount(params);
                            break;
                    }
                }
            }
        }
        return  payOrderResultInfo;
    }

    //计算集团下站点LNG平台加气
    public PayOrderResultInfo calculateLngGroupStaDiscount(Map<String ,Object> params){
        PayOrderResultInfo payOrderResultInfo = new PayOrderResultInfo();
        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 sellDiscountAmt = new BigDecimal(0);             //油站销售价后优惠金额
        BigDecimal dzkDiscountAmt = new BigDecimal(0);              //电子卡优惠金额
        BigDecimal amt = receivableAmt;                                 //司机价后支付金额
        BigDecimal sellAmt = new BigDecimal(0);                     //油站结算价支付金额
        BigDecimal discountPrice = oilPrice;                            //司机销售价
        BigDecimal sellPrice = discountPrice;                           //油站销售价
        BigDecimal driverDiscountAmt = 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);
//        }
        // settlementType:结算价类型（1.直降，2.折扣）;  settlementPrice:结算价;  driverPrice:司机价;
        if(params.containsKey("settlementType") && params.get("settlementType") !=null && params.get("settlementType").toString() !=""){
            String settlementType = params.get("settlementType").toString();
            switch (settlementType){
                case "1":   //直降
                    //优惠价（销售价）
                    if(params.containsKey("settlementPrice") && params.get("settlementPrice").toString() !=null && params.get("settlementPrice").toString() !=""){
                        sellPrice = oilPrice.subtract(new BigDecimal(params.get("settlementPrice").toString()));
                        sellAmt = sellPrice.multiply(oilLiters); //优惠价实付金额
                        sellDiscountAmt = receivableAmt.subtract(sellAmt);
                    }
                    break;
                case "2":   //折扣
                    //优惠价（销售价）
                    if(params.containsKey("settlementPrice") && params.get("settlementPrice").toString() !=null && params.get("settlementPrice").toString() !=""){
                        sellPrice = oilPrice.multiply(new BigDecimal(params.get("settlementPrice").toString())).divide(new BigDecimal("100"));
                        sellAmt =sellPrice.multiply(oilLiters);
                        sellDiscountAmt = receivableAmt.subtract(sellAmt);
                        //sellDiscountAmt = sellDiscountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    break;
            }
        }
        //driverPriceType: 司机价类型（1.直降，2.折扣）;
        if(params.containsKey("driverPriceType") && params.get("driverPriceType") !=null && params.get("driverPriceType").toString() !=""){
            String driverPriceType = params.get("driverPriceType").toString();
            switch (driverPriceType){
                case "1":
                    if(params.containsKey("driverPrice") && params.get("driverPrice").toString() !=null && params.get("driverPrice").toString() !=""){
                        //司机价
                        discountPrice = sellPrice.subtract(new BigDecimal(params.get("driverPrice").toString()));
                        amt = discountPrice.multiply(oilLiters);
                        //driverDiscountAmt = sellDiscountAmt.multiply(new BigDecimal("1").subtract(new BigDecimal(params.get("driverPrice").toString()).divide(new BigDecimal("100"))));
                        discountAmt = receivableAmt.subtract(amt);
                        driverDiscountAmt = discountAmt.subtract(sellDiscountAmt);
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                        discountPrice = discountPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    break;
                case "2":   //折扣
                    if(params.containsKey("driverPrice") && params.get("driverPrice").toString() !=null && params.get("driverPrice").toString() !=""){
                        //司机价
                        discountPrice = sellPrice.multiply(new BigDecimal(params.get("driverPrice").toString())).divide(new BigDecimal("100"));
                        amt = sellAmt.multiply(new BigDecimal(params.get("driverPrice").toString())).divide(new BigDecimal("100"));
                        //driverDiscountAmt = sellDiscountAmt.multiply(new BigDecimal("1").subtract(new BigDecimal(params.get("driverPrice").toString()).divide(new BigDecimal("100"))));
                        discountAmt = receivableAmt.subtract(amt);
                        driverDiscountAmt = discountAmt.subtract(sellDiscountAmt);
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                        discountPrice = discountPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    break;
            }
        }
        sellAmt =sellAmt.signum() == -1 ? new BigDecimal("0.01"): sellAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
        amt =amt.signum() == -1 ? new BigDecimal("0.01"): amt.setScale(2, BigDecimal.ROUND_HALF_UP);
        if(oilLiters.toString().equals("0.00")){
            amt = new BigDecimal("0.01");
            sellAmt = new BigDecimal("0.01");
            driverDiscountAmt = new BigDecimal("0.00");
            discountAmt = new BigDecimal("0.00");
            sellDiscountAmt = new BigDecimal("0.00");
        }

        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());  //应收金额
        //oilLiters = oilLiters.setScale(2,BigDecimal.ROUND_HALF_UP);
        payOrderResultInfo.setOilLiters(oilLiters.toString());          //加油升数

        payOrderResultInfo.setOilPrice(oilPrice.toString());            //油机价
        payOrderResultInfo.setAmt(amt.toString());                      //司机价后时候金额
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());  //司机价
        payOrderResultInfo.setDiscountAmt(discountAmt.toString());      //司机价后优惠总金额

        driverDiscountAmt = driverDiscountAmt.setScale(2,BigDecimal.ROUND_HALF_UP);
        payOrderResultInfo.setDriverDiscountAmt(driverDiscountAmt.toString());              //司机价后优惠金额

        payOrderResultInfo.setSellAmt(sellAmt.toString());                      //销售价后支付金额
        sellPrice = sellPrice.setScale(2, BigDecimal.ROUND_HALF_UP);   //销售价
        payOrderResultInfo.setSellPrice(sellPrice.toString());                  //销售价
        sellDiscountAmt = sellDiscountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
        payOrderResultInfo.setSellDiscountAmt(sellDiscountAmt.toString());      //销售价后优惠金额

        //LNG加气平台没有电子卡功能：此下参数无用用作填充参数值 0：代表否；4：代表LNG油品
        payOrderResultInfo.setDzkAmt(amt.toString());                           //电子卡支付金额
        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmt.toString());        //电子卡优惠金额
        payOrderResultInfo.setBalance("0");
        payOrderResultInfo.setCardOilsType("4");

        payOrderResultInfo.setOilsCardFlag("0");
        payOrderResultInfo.setCardEnabledFlag("0");

        return payOrderResultInfo;
    }

    //计算标签用户优惠
    public PayOrderResultInfo calculateLabelDiscount(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 dzkDiscountAmt = new BigDecimal(0);  //电子卡优惠金额
        BigDecimal amt = receivableAmt;
        BigDecimal discountPrice = oilPrice;

        //加油升数
        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();
        //获取该油站的标签规则
        LabelRule labelRule = new LabelRule();
        labelRule.setStationId(Integer.valueOf(params.get("stationId").toString()));        //油站ID
        //labelRule.setOilName(params.get("oilName").toString());                         //oilName
        labelRule.setDelFlag("0");
        labelRule.setLabelId(Integer.valueOf(params.get("labelId").toString()));//
        List<LabelRule> labelRuleList = labelService.getLabelRuleList(labelRule);
        if(labelRuleList !=null && labelRuleList.size()> 0){
            payOrderResultInfo.setIsAddLabel(labelRuleList.get(0).getIsAddLabel()); //'是否强制将该扫码用户拉入此标签：0、否；1、是
            payOrderResultInfo.setLabelCreateBy(labelRuleList.get(0).getCreateBy());        //标签创建人
            payOrderResultInfo.setLabelUpdateBy(labelRuleList.get(0).getUpdateBy());        //标签更新人
            payOrderResultInfo.setLabelCreateTime(labelRuleList.get(0).getCreateTime());    //标签创建时间
            //获取该油品的优惠明细
            labelRule.setOilName(params.get("oilName").toString());
            labelRule.setDelFlagDetail("0");
            List<LabelRule> labelRuleList_oilName = labelService.getLabelRuleList(labelRule);
            if(labelRuleList_oilName !=null && labelRuleList_oilName.size() >0){
                List<LabelRuleDetail> labelRuleDetailList = labelRuleList_oilName.get(0).getLabelRuleDetailList();
                if(labelRuleDetailList !=null && labelRuleDetailList.size() ==1){
                    BigDecimal discountAmt_B = new BigDecimal(labelRuleDetailList.get(0).getDiscountAmt()); //满足享受优惠条件（满多少升、满多少元）
                    String discountTerm = labelRuleDetailList.get(0).getDiscountTerm();
                    switch (discountTerm){
                        case "1":   //按加油升数
                            if(oilLiters.compareTo(discountAmt_B) ==1 || oilLiters.compareTo(discountAmt_B) ==0 ){
                                discountPrice = oilPrice.subtract(new BigDecimal(labelRuleDetailList.get(0).getDiscountLitersAmt()));
                                amt = discountPrice.multiply(oilLiters);
                                discountAmt = receivableAmt.subtract(amt);
                                //discountAmt = oilLiters.multiply(new BigDecimal(labelRuleDetailList.get(0).getDiscountLitersAmt()));
                                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                            }
                            break;
                        case "2":   //按加油金额
                            if(receivableAmt.compareTo(discountAmt_B) ==1 || receivableAmt.compareTo(discountAmt_B) ==0 ){
                                discountPrice = oilPrice.subtract(new BigDecimal(labelRuleDetailList.get(0).getDiscountLitersAmt()));
                                amt = discountPrice.multiply(oilLiters);
                                discountAmt = receivableAmt.subtract(amt);
                                //discountAmt = oilLiters.multiply(new BigDecimal(labelRuleDetailList.get(0).getDiscountLitersAmt()));
                                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                            }
                            break;
                    }
                    dzkDiscountAmt = discountAmt;       //赋值电子卡优惠金额
                }
            }
        }

        //amt = receivableAmt.subtract(discountAmt);  //应收金额
        amt = amt.setScale(2, BigDecimal.ROUND_HALF_UP);
        if(amt.toString().equals("0.00")){
            amt = new BigDecimal("0.01");
        }
        amt =amt.signum() == -1 ? new BigDecimal("0.01"): amt;
        //discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? discountPrice : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);  //优惠价格
        payOrderResultInfo.setAmt(amt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.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());
        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmt.toString());
        payOrderResultInfo.setOilsCardFlag("0");
        if(params.get("cardRuleFlagGroup").toString().equals("1")){
            //表示开启共享
            if(params.get("cardEnabledFlagGroup").toString().equals("1")){  //表示开启电子卡功能
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }else {
            //不共享，则查看油站电子卡是否开启
            if(params.get("cardEnabledFlag").toString().equals("1")){
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(payOrderResultInfo.getCardEnabledFlag().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            if(params.get("cardRuleFlagGroup").toString().equals("1")){
                customerCardSetting.setStationId(Integer.valueOf(params.get("groupId").toString()));
            }
            List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
            if(cardRechargeSettingList !=null && cardRechargeSettingList.size() >0){
                String isLabel = cardRechargeSettingList.get(0).getIsLabel(); //标签用户支付时是否享受标签优惠
                if(isLabel.equals("1")){
                    //电子卡支付金额 = 应收金额 - 标签优惠金额
                    BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt);
                    dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;     //如果为负数，则默认设置0.01元
                    payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                    BigDecimal dzkDiscountAmtSum = dzkDiscountAmt; //电子卡总优惠金额
                    payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmtSum.toString());
                }else {
                    payOrderResultInfo.setDzkAmt(receivableAmt.toString());
                    payOrderResultInfo.setDzkDiscountAmt("0");
                }
            }
            CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
            customerElectronicCard.setStationId(Integer.valueOf(params.get("stationId").toString()));
            customerElectronicCard.setCardOilsType(params.get("cardOilsType").toString());
            customerElectronicCard.setUnionId(params.get("unionId").toString());
            customerElectronicCard.setMobilePhone(params.get("userPhone").toString());
            customerElectronicCard.setCustomerName(params.get("customerName").toString());
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(customerElectronicCard, params);
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setOilsCardFlag(map.get("oilsCardFlag"));
            payOrderResultInfo.setCardOilsType(map.get("cardOilsType"));
        }
        return payOrderResultInfo;
    }

    //计算阶梯直降
    public PayOrderResultInfo calculateJieTiZhiJiangDiscount(Map<String ,Object> params){
        PayOrderResultInfo payOrderResultInfo = new PayOrderResultInfo();   //计算结果存放值
        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 = receivableAmt;
        BigDecimal discountPrice = oilPrice;
        BigDecimal gradeDiscountAmt = new BigDecimal(0);    //等级优惠金额
        BigDecimal gradeDiscountPriceAmt = new BigDecimal(0);    //等级优惠价格
        BigDecimal dzkGradeDiscountAmt = new BigDecimal(0);    //计算电子卡金额时所需等级优惠金额值
        BigDecimal dzkDiscountAmt = 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 payOrderResultInfoGrade = this.calculateGradeDiscount(params);
        gradeDiscountAmt = new BigDecimal(payOrderResultInfoGrade.getDiscountAmt());
        gradeDiscountPriceAmt = new BigDecimal(payOrderResultInfoGrade.getGradeDiscountPriceAmt());
        dzkGradeDiscountAmt = gradeDiscountAmt; //同时给电子卡赋值等级优惠金额

        params.put("discountPlanType", "4");
        List<Map> customerMarkertPlanList = customerGradeServices.getCustomerMarkertPlanList(params);
        if(customerMarkertPlanList !=null && customerMarkertPlanList.size() >0){
            for(Map m : customerMarkertPlanList){
                BigDecimal discountAmt_b = new BigDecimal(m.get("discountAmt").toString());   //条件金额
                BigDecimal gasoilDiscountAmt_b = new BigDecimal(m.get("gasoilDiscountAmt").toString());
                String discountTerm = m.get("discountTerm").toString();
                if(discountTerm.equals("1")){
                    if(oilLiters.compareTo(discountAmt_b) ==1 || oilLiters.compareTo(discountAmt_b) ==0){
                        discountPrice = oilPrice.subtract(gasoilDiscountAmt_b);
                        amt = discountPrice.multiply(oilLiters);
                        discountAmt = receivableAmt.subtract(amt);
                        //discountAmt = oilLiters.multiply(gasoilDiscountAmt_b);
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                        dzkDiscountAmt = discountAmt;       //赋值电子卡优惠金额
                        String vipDiscountyPlus = m.get("vipDiscountyPlus").toString();
                        //该营销方案是否叠加等级优惠
                        if(vipDiscountyPlus.equals("1")){
                            //如果叠加等级优惠
                            discountPrice = discountPrice.subtract(gradeDiscountPriceAmt);
                            discountAmt = discountAmt.add(gradeDiscountAmt);
                            amt = receivableAmt.subtract(discountAmt);
                        }
                        break;
                    }
                }else if(discountTerm.equals("2")){
                    if(receivableAmt.compareTo(discountAmt_b) ==1 || receivableAmt.compareTo(discountAmt_b) ==0){
                        discountPrice = oilPrice.subtract(gasoilDiscountAmt_b);
                        amt = discountPrice.multiply(oilLiters);
                        discountAmt = receivableAmt.subtract(amt);
                        //discountAmt = oilLiters.multiply(gasoilDiscountAmt_b);
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                        dzkDiscountAmt = discountAmt;       //赋值电子卡优惠金额
                        String vipDiscountyPlus = m.get("vipDiscountyPlus").toString();
                        //该营销方案是否叠加等级优惠
                        if(vipDiscountyPlus.equals("1")){
                            //如果叠加等级优惠
                            discountPrice = discountPrice.subtract(gradeDiscountPriceAmt);
                            discountAmt = discountAmt.add(gradeDiscountAmt);
                            amt = receivableAmt.subtract(discountAmt);
                        }
                        break;
                    }
                }
            }
        }
        //amt = receivableAmt.subtract(discountAmt);  //应收金额
        amt = amt.setScale(2, BigDecimal.ROUND_HALF_UP);
        if(amt.toString().equals("0.00")){
            amt = new BigDecimal("0.01");
        }
        amt =amt.signum() == -1 ? new BigDecimal("0.01"): amt;
        //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.setDzkDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        payOrderResultInfo.setOilsCardFlag("0");
        if(params.get("cardRuleFlagGroup").toString().equals("1")){
            //表示开启共享
            if(params.get("cardEnabledFlagGroup").toString().equals("1")){  //表示开启电子卡功能
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }else {
            //不共享，则查看油站电子卡是否开启
            if(params.get("cardEnabledFlag").toString().equals("1")){
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(payOrderResultInfo.getCardEnabledFlag().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            if(params.get("cardRuleFlagGroup").toString().equals("1")){
                customerCardSetting.setStationId(Integer.valueOf(params.get("groupId").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")){
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt).subtract(dzkGradeDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        BigDecimal dzkDiscountAmtSum = dzkDiscountAmt.add(dzkGradeDiscountAmt); //电子卡优惠金额
                        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmtSum.toString());
                    }else {
                        //如果电子卡设置执行营销方案不执行等级优惠 则 电子卡支付金额 =实收金额-营销优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmt.toString());
                    }
                }else {
                    if(isGradeSetting.equals("1")){
                        //如果电子卡设置不执行营销方案执行等级优惠 则 电子卡支付金额 =应收金额-等级优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkGradeDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt(dzkGradeDiscountAmt.toString());
                    }else {
                        payOrderResultInfo.setDzkAmt(receivableAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt("0");
                    }
                }
            }
            CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
            customerElectronicCard.setStationId(Integer.valueOf(params.get("stationId").toString()));
            customerElectronicCard.setCardOilsType(params.get("cardOilsType").toString());
            customerElectronicCard.setUnionId(params.get("unionId").toString());
            customerElectronicCard.setMobilePhone(params.get("userPhone").toString());
            customerElectronicCard.setCustomerName(params.get("customerName").toString());
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(customerElectronicCard, params);
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setOilsCardFlag(map.get("oilsCardFlag"));
            payOrderResultInfo.setCardOilsType(map.get("cardOilsType"));
        }
        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 = receivableAmt;
        BigDecimal discountPrice = oilPrice;
        BigDecimal gradeDiscountAmt = new BigDecimal(0);    //等级优惠金额
        BigDecimal gradeDiscountPriceAmt = new BigDecimal("0");
        BigDecimal dzkGradeDiscountAmt = new BigDecimal(0);    //计算电子卡金额时所需等级优惠金额值
        BigDecimal dzkDiscountAmt = 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();   //计算结果存放值
        //计算等级优惠
        PayOrderResultInfo payOrderResultInfoGrade = this.calculateGradeDiscount(params);
        gradeDiscountAmt = new BigDecimal(payOrderResultInfoGrade.getDiscountAmt());
        gradeDiscountPriceAmt = new BigDecimal(payOrderResultInfoGrade.getGradeDiscountPriceAmt());
        dzkGradeDiscountAmt = gradeDiscountAmt; //同时给电子卡赋值等级优惠金额

        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();
            String discountSettingFlag;
            switch (discountTerm){
                case "1":   //按加油升数
                    if(oilLiters.compareTo(discountAmt_b) ==1 || oilLiters.compareTo(discountAmt_b) ==0){
                        discountPrice = oilPrice.subtract(gasoilDiscountAmt_b);
                        amt = discountPrice.multiply(oilLiters);
                        discountAmt = receivableAmt.subtract(amt);
//                        discountAmt = oilLiters.multiply(gasoilDiscountAmt_b);
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                        //会员活动是否开启：1是；0否'
                        if(customerMarkertPlanList.get(0).containsKey("discountSettingFlag") && customerMarkertPlanList.get(0).get("discountSettingFlag").toString() !="") {
                            discountSettingFlag = customerMarkertPlanList.get(0).get("discountSettingFlag").toString();
                            if (discountSettingFlag != null && discountSettingFlag.equals("1")) {
                                String discountType = customerMarkertPlanList.get(0).get("discountType").toString();    //会员日周期类型设置
                                String discountDate = customerMarkertPlanList.get(0).get("discountDate").toString();    //按固定日期
                                String discountActivityAmt = customerMarkertPlanList.get(0).get("discountActivityAmt").toString();  //会员日优惠金额
                                if (StringUtils.isNotBlank(discountType) && StringUtils.isNotBlank(discountDate) && StringUtils.isNotBlank(discountActivityAmt)) {
                                    //当前时间是否是活动会员日
                                    boolean b = isActivityDay(discountType, discountDate);
                                    if (b) {
                                        discountPrice = oilPrice.subtract(new BigDecimal(discountActivityAmt));
                                        amt = discountPrice.multiply(oilLiters);
                                        discountAmt = receivableAmt.subtract(amt);
                                        //discountAmt = oilLiters.multiply(new BigDecimal(discountActivityAmt));
                                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    }
                                }
                            }
                        }
                    }
                    break;
                case "2":   //按加油金额
                    if(receivableAmt.compareTo(discountAmt_b) ==1 || receivableAmt.compareTo(discountAmt_b) ==0){
                        discountPrice = oilPrice.subtract(gasoilDiscountAmt_b);
                        amt = discountPrice.multiply(oilLiters);
                        discountAmt = receivableAmt.subtract(amt);
                        //discountAmt = oilLiters.multiply(gasoilDiscountAmt_b);
                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                        //会员活动是否开启：1是；0否'
                        if(customerMarkertPlanList.get(0).containsKey("discountSettingFlag") && customerMarkertPlanList.get(0).get("discountSettingFlag").toString() !="") {
                            discountSettingFlag = customerMarkertPlanList.get(0).get("discountSettingFlag").toString();
                            if (discountSettingFlag != null && discountSettingFlag.equals("1")) {
                                String discountType = customerMarkertPlanList.get(0).get("discountType").toString();    //会员日周期类型设置
                                String discountDate = customerMarkertPlanList.get(0).get("discountDate").toString();    //按固定日期
                                String discountActivityAmt = customerMarkertPlanList.get(0).get("discountActivityAmt").toString();  //会员日优惠金额
                                if (StringUtils.isNotBlank(discountType) && StringUtils.isNotBlank(discountDate) && StringUtils.isNotBlank(discountActivityAmt)) {
                                    //当前时间是否是活动会员日
                                    boolean b = isActivityDay(discountType, discountDate);
                                    if (b) {
                                        discountPrice = oilPrice.subtract(new BigDecimal(discountActivityAmt));
                                        amt = discountPrice.multiply(oilLiters);
                                        discountAmt = receivableAmt.subtract(amt);
                                        //discountAmt = oilLiters.multiply(new BigDecimal(discountActivityAmt));
                                        discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    }

                                }
                            }
                        }
                    }
                    break;
            }
            dzkDiscountAmt = discountAmt;       //赋值电子卡优惠金额
            String vipDiscountyPlus = customerMarkertPlanList.get(0).get("vipDiscountyPlus").toString();
            //该营销方案是否叠加等级优惠
            if(vipDiscountyPlus.equals("1")){
                //如果叠加等级优惠
                discountPrice = discountPrice.subtract(gradeDiscountPriceAmt);
                discountAmt = discountAmt.add(gradeDiscountAmt);
                amt = receivableAmt.subtract(discountAmt);
            }
        }
//        amt = receivableAmt.subtract(discountAmt);  //应收金额
        amt = amt.setScale(2, BigDecimal.ROUND_HALF_UP);
        if(amt.toString().equals("0.00")){
            amt = new BigDecimal("0.01");
        }
        amt =amt.signum() == -1 ? new BigDecimal("0.01"): amt;
        //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.setDzkDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        payOrderResultInfo.setOilsCardFlag("0");
        if(params.get("cardRuleFlagGroup").toString().equals("1")){
            //表示开启共享
            if(params.get("cardEnabledFlagGroup").toString().equals("1")){  //表示开启电子卡功能
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }else {
            //不共享，则查看油站电子卡是否开启
            if(params.get("cardEnabledFlag").toString().equals("1")){
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(payOrderResultInfo.getCardEnabledFlag().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            if(params.get("cardRuleFlagGroup").toString().equals("1")){
                customerCardSetting.setStationId(Integer.valueOf(params.get("groupId").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")){
                        //都叠加 电子卡支付金额 = 应收金额 - 营销优惠金额 - 等级优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt).subtract(dzkGradeDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;     //如果为负数，则默认设置0.01元
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        BigDecimal dzkDiscountAmtSum = dzkDiscountAmt.add(dzkGradeDiscountAmt); //电子卡总优惠金额
                        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmtSum.toString());
                    }else {
                        //叠加营销方案不叠加等级优惠： 电子卡支付金额 =实收金额-营销优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmt.toString());
                    }
                }else {
                    if(isGradeSetting.equals("1")){
                        //不叠加营销方案叠加等级优惠：电子卡支付金额 =应收金额-等级优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkGradeDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt(dzkGradeDiscountAmt.toString());
                    }else {
                        //都不叠加： 电子卡支付金额 = 应收金额
                        payOrderResultInfo.setDzkAmt(receivableAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt("0");
                    }
                }
            }
            CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
            customerElectronicCard.setStationId(Integer.valueOf(params.get("stationId").toString()));
            customerElectronicCard.setCardOilsType(params.get("cardOilsType").toString());
            customerElectronicCard.setUnionId(params.get("unionId").toString());
            customerElectronicCard.setMobilePhone(params.get("userPhone").toString());
            customerElectronicCard.setCustomerName(params.get("customerName").toString());
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(customerElectronicCard, params);
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setOilsCardFlag(map.get("oilsCardFlag"));
            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 = receivableAmt;
        BigDecimal discountPrice = oilPrice;
        BigDecimal gradeDiscountAmt = new BigDecimal(0);    //等级优惠金额
        BigDecimal dzkGradeDiscountAmt = new BigDecimal(0);    //计算电子卡金额时所需等级优惠金额值
        BigDecimal dzkDiscountAmt = 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();

        //计算等级优惠
        PayOrderResultInfo payOrderResultInfoGrade = this.calculateGradeDiscount(params);
        gradeDiscountAmt = new BigDecimal(payOrderResultInfoGrade.getDiscountAmt());
        dzkGradeDiscountAmt = gradeDiscountAmt;     //同时给电子卡赋值等级优惠金额

        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;
                //会员活动是否开启：1是；0否'
                if(customerMarkertPlanList.get(0).containsKey("discountSettingFlag") && customerMarkertPlanList.get(0).get("discountSettingFlag").toString() !="") {
                    String discountSettingFlag = customerMarkertPlanList.get(0).get("discountSettingFlag").toString();
                    if (discountSettingFlag != null && discountSettingFlag.equals("1")) {
                        String discountType = customerMarkertPlanList.get(0).get("discountType").toString();    //会员日周期类型设置
                        String discountDate = customerMarkertPlanList.get(0).get("discountDate").toString();    //按固定日期
                        String discountActivityAmt = customerMarkertPlanList.get(0).get("discountActivityAmt").toString();  //会员日优惠金额
                        if (StringUtils.isNotBlank(discountType) && StringUtils.isNotBlank(discountDate) && StringUtils.isNotBlank(discountActivityAmt)) {
                            //当前时间是否是会员日
                            boolean b = isActivityDay(discountType, discountDate);
                            if (b) {
                                discountAmt = new BigDecimal(discountActivityAmt);
                            }
                        }
                    }
                }
            }
            dzkDiscountAmt = discountAmt;
            String vipDiscountyPlus = customerMarkertPlanList.get(0).get("vipDiscountyPlus").toString();
            if(vipDiscountyPlus.equals("1")){
                //如果叠加等级优惠
                discountAmt = discountAmt.add(gradeDiscountAmt);
            }
        }
        amt = receivableAmt.subtract(discountAmt);  //应收金额
        amt =amt.signum() == -1 ? new BigDecimal("0.01"): amt;
        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.setDzkDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        payOrderResultInfo.setOilsCardFlag("0");
        if(params.get("cardRuleFlagGroup").toString().equals("1")){
            //表示开启共享
            if(params.get("cardEnabledFlagGroup").toString().equals("1")){  //表示开启电子卡功能
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }else {
            //不共享，则查看油站电子卡是否开启
            if(params.get("cardEnabledFlag").toString().equals("1")){
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(payOrderResultInfo.getCardEnabledFlag().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            if(params.get("cardRuleFlagGroup").toString().equals("1")){
                customerCardSetting.setStationId(Integer.valueOf(params.get("groupId").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")){
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt).subtract(dzkGradeDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        BigDecimal dzkDiscountAmtSum = dzkDiscountAmt.add(dzkGradeDiscountAmt); //电子卡优惠金额
                        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmtSum.toString());
                    }else {
                        //如果电子卡设置执行营销方案不执行等级优惠 则 电子卡支付金额 =实收金额-营销优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmt.toString());
                    }
                }else {
                    if(isGradeSetting.equals("1")){
                        //如果电子卡设置不执行营销方案执行等级优惠 则 电子卡支付金额 =应收金额-等级优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkGradeDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt(dzkGradeDiscountAmt.toString());
                    }else {
                        payOrderResultInfo.setDzkAmt(receivableAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt("0");
                    }
                }
            }
            CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
            customerElectronicCard.setStationId(Integer.valueOf(params.get("stationId").toString()));
            customerElectronicCard.setCardOilsType(params.get("cardOilsType").toString());
            customerElectronicCard.setUnionId(params.get("unionId").toString());
            customerElectronicCard.setMobilePhone(params.get("userPhone").toString());
            customerElectronicCard.setCustomerName(params.get("customerName").toString());
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(customerElectronicCard, params);
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setOilsCardFlag(map.get("oilsCardFlag"));
            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 = receivableAmt;
        BigDecimal discountPrice = oilPrice;
        BigDecimal gradeDiscountAmt = new BigDecimal(0);    //等级优惠金额
        BigDecimal dzkGradeDiscountAmt = new BigDecimal(0);    //计算电子卡金额时所需等级优惠金额值
        BigDecimal dzkDiscountAmt = 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();
        //计算等级优惠
        PayOrderResultInfo payOrderResultInfoGrade = this.calculateGradeDiscount(params);
        gradeDiscountAmt = new BigDecimal(payOrderResultInfoGrade.getDiscountAmt());
        dzkGradeDiscountAmt = gradeDiscountAmt;
        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是；0否'
                if(customerMarkertPlanList.get(0).containsKey("discountSettingFlag") && customerMarkertPlanList.get(0).get("discountSettingFlag").toString() !=""){
                    String discountSettingFlag = customerMarkertPlanList.get(0).get("discountSettingFlag").toString();
                    if(discountSettingFlag !=null && discountSettingFlag.equals("1")){
                        String discountType = customerMarkertPlanList.get(0).get("discountType").toString();    //会员日周期类型设置
                        String discountDate = customerMarkertPlanList.get(0).get("discountDate").toString();    //按固定日期
                        String discountActivityAmt = customerMarkertPlanList.get(0).get("discountActivityAmt").toString();  //会员日优惠金额
                        //当前时间是否是会员日
                        if(StringUtils.isNotBlank(discountType) && StringUtils.isNotBlank(discountDate) && StringUtils.isNotBlank(discountActivityAmt)){
                            boolean b = isActivityDay(discountType, discountDate);
                            if(b){
                                discountAmt = receivableAmt.divide(discountAmt_b, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(discountActivityAmt));  //优惠金额
                                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
                            }
                        }

                    }
                }
            }
            dzkDiscountAmt = discountAmt;
            //是否共享会员等级优惠叠加: 1 代表是； 2 代表否；
            String vipDiscountyPlus = customerMarkertPlanList.get(0).get("vipDiscountyPlus").toString();
            if(vipDiscountyPlus.equals("1")){
                //如果叠加等级优惠
                discountAmt = discountAmt.add(gradeDiscountAmt);
            }
        }
        amt = receivableAmt.subtract(discountAmt);  //应收金额
        amt =amt.signum() == -1 ? new BigDecimal("0.01"): amt;
        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.setDzkDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        payOrderResultInfo.setOilsCardFlag("0");
        if(params.get("cardRuleFlagGroup").toString().equals("1")){
            //表示开启共享
            if(params.get("cardEnabledFlagGroup").toString().equals("1")){  //表示开启电子卡功能
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }else {
            //不共享，则查看油站电子卡是否开启
            if(params.get("cardEnabledFlag").toString().equals("1")){
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }
        logger.info("油站是否开启电子会员卡功能: " +params.get("cardEnabledFlag").toString());
        if(payOrderResultInfo.getCardEnabledFlag().equals("1")){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            if(params.get("cardRuleFlagGroup").toString().equals("1")){
                customerCardSetting.setStationId(Integer.valueOf(params.get("groupId").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")){
                        //如果电子卡设置执行营销方案不执行等级优惠 则 电子卡支付金额 =实收金额-营销优惠-等级优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt).subtract(dzkGradeDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        BigDecimal dzkDiscountAmtSum = dzkDiscountAmt.add(dzkGradeDiscountAmt); //电子卡优惠金额
                        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmtSum.toString());
                    }else {
                        //如果电子卡设置执行营销方案不执行等级优惠 则 电子卡支付金额 =实收金额-营销优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt(dzkDiscountAmt.toString());
                    }
                }else {
                    if(isGradeSetting.equals("1")){
                        //如果电子卡设置不执行营销方案执行等级优惠 则 电子卡支付金额 =应收金额-等级优惠金额
                        BigDecimal dzkAmt = receivableAmt.subtract(dzkGradeDiscountAmt);
                        dzkAmt =dzkAmt.signum() == -1 ? new BigDecimal("0.01"): dzkAmt;
                        payOrderResultInfo.setDzkAmt(dzkAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt(dzkGradeDiscountAmt.toString());
                    }else {
                        payOrderResultInfo.setDzkAmt(receivableAmt.toString());
                        payOrderResultInfo.setDzkDiscountAmt("0");
                    }
                }
            }
            CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
            customerElectronicCard.setStationId(Integer.valueOf(params.get("stationId").toString()));
            customerElectronicCard.setCardOilsType(params.get("cardOilsType").toString());
            customerElectronicCard.setUnionId(params.get("unionId").toString());
            customerElectronicCard.setMobilePhone(params.get("userPhone").toString());
            customerElectronicCard.setCustomerName(params.get("customerName").toString());
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(customerElectronicCard, params);
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setOilsCardFlag(map.get("oilsCardFlag"));
            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 dzkDiscountAmt = discountAmt;  //优惠金额
        BigDecimal amt = receivableAmt;
        BigDecimal discountPrice = oilPrice;
        BigDecimal gradeDiscountPriceAmt = new BigDecimal("0");  //价格优惠金额
        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.setUnionId(params.get("unionId").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())){
                        discountPrice = oilPrice.subtract(new BigDecimal(m.get("discountAmt").toString()));
                        gradeDiscountPriceAmt = new BigDecimal(m.get("discountAmt").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){
                discountPrice = oilPrice.subtract(new BigDecimal(customerGradeList.get(0).get("discountAmt").toString()));
                gradeDiscountPriceAmt = new BigDecimal(customerGradeList.get(0).get("discountAmt").toString());
                discountAmt = oilLiters.multiply(new BigDecimal(customerGradeList.get(0).get("discountAmt").toString()));
                discountAmt = discountAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        }
        amt = receivableAmt.subtract(discountAmt);  //应收金额
        amt =amt.signum() == -1 ? new BigDecimal("0.01"): amt;
        //discountPrice = oilLiters.equals(new BigDecimal("0.00")) ? discountPrice : amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);  //优惠价格

        payOrderResultInfo.setGradeDiscountPriceAmt(gradeDiscountPriceAmt.toString());

        payOrderResultInfo.setAmt(amt.toString());
        payOrderResultInfo.setDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDzkDiscountAmt(discountAmt.toString());
        payOrderResultInfo.setDiscountPrice(discountPrice.toString());
        payOrderResultInfo.setOilLiters(oilLiters.toString());
        payOrderResultInfo.setReceivableAmt(receivableAmt.toString());
        payOrderResultInfo.setOilPrice(oilPrice.toString());
        payOrderResultInfo.setDzkAmt(amt.toString());
        payOrderResultInfo.setOilsCardFlag("0");
        if(params.get("cardRuleFlagGroup").toString().equals("1")){
            //表示开启共享
            if(params.get("cardEnabledFlagGroup").toString().equals("1")){  //表示开启电子卡功能
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }else {
            //不共享，则查看油站电子卡是否开启
            if(params.get("cardEnabledFlag").toString().equals("1")){
                payOrderResultInfo.setCardEnabledFlag("1");
            }else {
                payOrderResultInfo.setCardEnabledFlag("0");
            }
        }
        //电子卡功能是否开启
        logger.info("油站是否开启电子会员卡功能: " +payOrderResultInfo.getCardEnabledFlag());
        if(payOrderResultInfo.getCardEnabledFlag().equals("1")){
            payOrderResultInfo.setDzkAmt(receivableAmt.toString());
            payOrderResultInfo.setDzkDiscountAmt("0");
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(Integer.valueOf(params.get("stationId").toString()));
            if(params.get("cardRuleFlagGroup").toString().equals("1")){
                customerCardSetting.setStationId(Integer.valueOf(params.get("groupId").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());
                    payOrderResultInfo.setDzkDiscountAmt(discountAmt.toString());
                }
            }
            CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
            customerElectronicCard.setStationId(Integer.valueOf(params.get("stationId").toString()));
            customerElectronicCard.setCardOilsType(params.get("cardOilsType").toString());
            customerElectronicCard.setUnionId(params.get("unionId").toString());
            customerElectronicCard.setMobilePhone(params.get("userPhone").toString());
            customerElectronicCard.setCustomerName(params.get("customerName").toString());
            //查询客户余额和卡的类型
            Map<String, String> map = this.selectCardBalance(customerElectronicCard, params);
            payOrderResultInfo.setBalance(map.get("balance"));
            payOrderResultInfo.setOilsCardFlag(map.get("oilsCardFlag"));
            payOrderResultInfo.setCardOilsType(map.get("cardOilsType"));
        }
        return  payOrderResultInfo;
    }

    //查询用户电子会员卡余额
    public Map<String, String>  selectCardBalance(CustomerElectronicCard card, Map params) {
        CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
        customerElectronicCard.setCardOilsType(card.getCardOilsType());
        customerElectronicCard.setStationId(card.getStationId());
        customerElectronicCard.setUnionId(card.getUnionId());
        BigDecimal balance = new BigDecimal(0);
        String cardOilsType1 ="";
        Map<String, String> result = new HashMap<>();
        CustomerCardSetting customerCardSetting = new CustomerCardSetting();
        customerCardSetting.setStationId(card.getStationId());
        if(params.get("cardRuleFlagGroup").equals("1")){    //
            customerCardSetting.setStationId(Integer.valueOf(params.get("groupId").toString()));
            customerElectronicCard.setStationId(Integer.valueOf(params.get("groupId").toString()));
        }
        List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
        if(cardRechargeSettingList !=null && cardRechargeSettingList.size()>0){
            String cardOilsTypeExist = cardRechargeSettingList.get(0).getCardOilsType();
            String[] split = cardOilsTypeExist.split(",");
            List<String> strings = Arrays.asList(split);
            if(strings.contains(card.getCardOilsType())){
                CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getElectronicCardInfoByUnionId(customerElectronicCard);
                if(electronicCardInfo !=null){
                    //已存在卡
                    balance = electronicCardInfo.getAmt();
                    cardOilsType1 = electronicCardInfo.getCardOilsType();
                    result.put("balance",balance.toString());
                    result.put("oilsCardFlag", "1");
                    result.put("cardOilsType",cardOilsType1);
                }else {
                    //如果油站已开启该卡，用户没有卡
                    String currentTime = String.valueOf(System.currentTimeMillis());
                    String customerNo = card.getStationId() + currentTime;
                    customerElectronicCard.setCustomerNo(customerNo);
                    customerElectronicCard.setAmt(new BigDecimal(0));
                    customerElectronicCard.setCreateTime(new Date());
                    customerElectronicCard.setCustomerName(card.getCustomerName());
                    customerElectronicCard.setMobilePhone(card.getMobilePhone());
                    electronicMembershipCardService.insetElectronicCard(customerElectronicCard);
                    CustomerElectronicCard electronicCardInfoNew  = electronicMembershipCardService.getElectronicCardInfoByUnionId(customerElectronicCard);
                    balance = electronicCardInfoNew.getAmt();
                    result.put("balance",balance.toString());
                    result.put("oilsCardFlag", "1");
                    result.put("cardOilsType",electronicCardInfoNew.getCardOilsType());
                }
            }else {
                result.put("oilsCardFlag", "0");
            }
        }else {
            result.put("oilsCardFlag", "0");
        }
        return result;
    }


    /***
     * //营销方案活动日优惠
     * @param discountType              活动日时间类型
     * @param discountDate              活动日时间字符串，格式：1,2,3,4,5
     * @return
     */
    public boolean isActivityDay(String discountType, String discountDate){
        boolean boo= false;
        if(discountDate !=null && discountDate !=""){
            String currentTime = null;          //当前时间
            String[] discountDateArray = discountDate.split(",");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());   //获取当前时间
            switch (discountType){
                case "1":   //  1.按周来
                    int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                    day_Week= day_Week-1;     //减一原因：数据库存的下标从零开始
                    currentTime = String.valueOf(day_Week);
                    break;
                case "2":   //  2.每月的 多少号
                    int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                    day_month = day_month-1;        //减一原因：数据库存的下标从零开始
                    currentTime = String.valueOf(day_month); //当前时间
                    break;
                case "3":   //  3.固定日期
                    currentTime =new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //当前时间
                    break;
            }
            //活动日优惠金额
            for (String s : discountDateArray){
                if(s.equals(currentTime)){
                    boo = true;
                    break;
                }
            }
        }
        return boo;
    }

    /**
     * 根据订单号获取订单信息
     * produces="application/json;charset=UTF-8",consumes = "application/json",
     * @RequestBody String orderno
     * @param
     * @return
     */
    @RequestMapping(value = "/selectOrderInfoByOrdNo", method = RequestMethod.GET)
    @ResponseBody
    public String getPayOrderList(@RequestParam String orderNo){
        Gson gson =new Gson();
        ResultData resultData =null;
        if(StringUtils.isNotBlank(orderNo)){
            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(orderNo);
            resultData = ResultData.success(payOrder);
        }else {
            resultData=ResultData.error(CodeMsg.SEARCH_FAIL);
        }
        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){
        Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData =null;
            if(StringUtils.isNotBlank(openId)){
                AppUserInfo appUserInfo = new AppUserInfo();
                appUserInfo.setMinaOpenid(openId);
//                switch (userType){
//                    case "1":
//                        appUserInfo.setMinaOpenid(openId);
//                        break;
//                    case "2":
//                        appUserInfo.setALiId(openId);
//                        break;
//                }
                List<PayOrder> payOrderList = payOrderService.getOrderListByOpenIdAndUserType(appUserInfo);
                resultData=ResultData.success(payOrderList);
            }else {
                resultData=ResultData.error(CodeMsg.SEARCH_FAIL);
            }

        return gson.toJson(resultData);
    }
}

