package com.platform.yijia.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.google.gson.Gson;
import com.platform.yijia.param.request.RechargeBalance;
import com.platform.yijia.pojo.*;
import com.platform.yijia.service.*;
import com.platform.yijia.utils.*;
import com.platform.yijia.utils.weixinapp.WxPushUtil;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 * <Title> ElectronicMembershipCardController </Title>
 * <Description> 电子会员卡（储蓄卡）功能模块 </Description>
 * @Author JK
 * @Date 2021年3月22日
 */
@Controller
@RequestMapping("/demo")
public class ElectronicMembershipCardController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(ElectronicMembershipCardController.class);

    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private StationService stationService;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private CustomerGradeServices customerGradeServices;
    @Resource
    private  CustomerManagerService customerManagerService;
    @Resource
    private CustomerPointsService customerPointsService;
    @Resource
    private IntegralRuleService integralRuleService;
    @Resource
    private CustomerPointsRecordService customerPointsRecordService;

    //查询该油站是否启用电子会员卡
    @RequestMapping(value = "/getStationCardEnabledFlag", method = RequestMethod.GET)
    @ResponseBody
    public String getStationCardEnabledFlag(@RequestParam Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null){
            String stationCardEnabledFlag = electronicMembershipCardService.getStationCardEnabledFlag(stationId);
            resultData = ResultData.success(stationCardEnabledFlag);
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取用户电子会员卡（储蓄卡）列表
    @RequestMapping(value = "/getElectronicCardList", method = RequestMethod.GET)
    @ResponseBody
    public String getElectronicCardList(@RequestParam Integer stationId, String unionId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        logger.info("获取用户电子会员卡信息参数：油站ID："+ stationId+"用户unionId："+unionId);
        if(stationId !=null && unionId !=null && unionId !=""){
            CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
            customerElectronicCard.setStationId(stationId);
            customerElectronicCard.setUnionId(unionId);
            List<CustomerElectronicCard> electronicCardList = electronicMembershipCardService.getElectronicCardList(customerElectronicCard);
            resultData = ResultData.success(electronicCardList);
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //用户充值电子会员卡（储蓄卡）生成充值记录
    @RequestMapping(value = "/rechargeBalance", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String rechargeBalance(@RequestBody RechargeBalance rechargeBalance){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(rechargeBalance !=null){
            BigDecimal amt = new BigDecimal(rechargeBalance.getAmt());
            //String openId = rechargeBalance.getOpenId();    //公众号的openId
            Integer stationId = rechargeBalance.getStationId();
            //BigDecimal presentAmt = new BigDecimal(rechargeBalance.getPresentAmt());
            String payType = rechargeBalance.getPayType();
            String customerName = rechargeBalance.getCustomerName();
            String cardOilsType = rechargeBalance.getCardOilsType();
            String unionId = rechargeBalance.getUnionId();
            String stationName = rechargeBalance.getStationName();
            String stationCardEnabledFlag = electronicMembershipCardService.getStationCardEnabledFlag(stationId);
            logger.info("充值金额："+amt);
            logger.info("支付类型："+payType);
            logger.info("充值卡类型："+cardOilsType);
            logger.info("充值金额："+amt);
            logger.info("油站ID："+stationId);
            logger.info("充值unionId："+unionId);
            //是否启用电子卡功能
            if(stationCardEnabledFlag.equals("1")){
                CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();      //电子会员卡使用记录
                CustomerCardSetting customerCardSetting = new CustomerCardSetting();        //电子卡优惠规则设置
                customerCardSetting.setStationId(stationId);
                customerCardSetting.setCardOilsType(cardOilsType);
                customerCardSetting.setOrderBy("DESC");
                //获取用户要充值电子卡的优惠规则信息
                List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
                if(cardRechargeSettingList !=null && cardRechargeSettingList.size() ==1){
                    String discountTime = cardRechargeSettingList.get(0).getDiscountTime();
                    //stationName = cardRechargeSettingList.get(0).getStationName();
                    String[] dctime={};     //会员充值活动时间
                    if(discountTime.contains(",")){
                        dctime =discountTime.split(",");
                    }else {
                        dctime =new String[1];
                        dctime[0] = discountTime;
                    }
                    String currentTime =null;
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());   //获取当前时间
                    //循环优惠规则明细
                    for (CustomerCardSettingDetail cardDetail : cardRechargeSettingList.get(0).getCustomerCardSettingDetailList()){
                        if(amt.compareTo(cardDetail.getDiscountAmtEnd()) ==-1 || amt.compareTo(cardDetail.getDiscountAmtEnd()) ==0){
                            //String isDiscountCoupon = cardRechargeSettingList.get(0).getIsDiscountCoupon();       //是否使用优惠券
                            //充值优惠类型
                            if(cardDetail.getSettingRuleType().equals("1")){ //按充值金额
                                BigDecimal presentAmt = cardDetail.getPresentAmt(); //当前赠送金额
                                if(cardRechargeSettingList.get(0).getDiscountTimeSetting().equals("1") && dctime !=null){
                                    String discountTimeType = cardRechargeSettingList.get(0).getDiscountTimeType();     //获取日期类型
                                    switch (discountTimeType){
                                        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 str : dctime){
                                        if(str.equals(currentTime)){  //如果当前时间在会员日活动时间内
                                            //计算会员日内的总赠送积分
                                            if(cardRechargeSettingList.get(0).getPresentScale() !=null){
                                                presentAmt = presentAmt.multiply(new BigDecimal(cardRechargeSettingList.get(0).getPresentScale())).add(presentAmt);
                                            }
                                            break;
                                        }
                                    }
                                }
                                customerCardUseRecord.setAmt(amt);
                                customerCardUseRecord.setPresentAmt(presentAmt);
                            }else if(cardDetail.getSettingRuleType().equals("2")){      //按充值金额的比例
                                BigDecimal presentAmt = amt.multiply(cardDetail.getPresentAmt().divide(new BigDecimal(100))); //当前赠送金额比例的赠送积分
                                if(cardRechargeSettingList.get(0).getDiscountTimeSetting().equals("1") && dctime !=null){
                                    String discountTimeType = cardRechargeSettingList.get(0).getDiscountTimeType();     //获取日期类型
                                    switch (discountTimeType){
                                        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 str : dctime){
                                        if(str.equals(currentTime)){  //如果当前时间在会员日活动时间内
                                            //计算会员日期内的总赠送积分
                                            if(cardRechargeSettingList.get(0).getPresentScale() !=null){
                                                presentAmt = presentAmt.multiply(new BigDecimal(cardRechargeSettingList.get(0).getPresentScale())).add(presentAmt);
                                            }
                                            break;
                                        }
                                    }
                                }
                                customerCardUseRecord.setAmt(amt);
                                customerCardUseRecord.setPresentAmt(presentAmt);
                                //customerCardUseRecord.setBalance(amt.add(presentAmt));
                            }
                            break;
                        }
                    }
                }else {
                    customerCardUseRecord.setAmt(amt);
                    customerCardUseRecord.setPresentAmt(new BigDecimal(0));
                }
                customerCardUseRecord.setUnionId(unionId);
                customerCardUseRecord.setStationId(stationId);
                customerCardUseRecord.setCardOilsType(cardOilsType);
                customerCardUseRecord.setStationName(stationName);
                customerCardUseRecord.setCustomerName(customerName);
                customerCardUseRecord.setUsageType("+");
                customerCardUseRecord.setPayType(payType);      //1表示微信
                customerCardUseRecord.setCreateTime(new Date());
                customerCardUseRecord.setStatus("0");

                CustomerElectronicCard c = new CustomerElectronicCard();    //电子会员卡
                c.setUnionId(unionId);
                c.setStationId(stationId);
                c.setCardOilsType(cardOilsType);
                CustomerElectronicCard electronicCardInfoByUnionId = electronicMembershipCardService.getElectronicCardInfoByUnionId(c);
                if(electronicCardInfoByUnionId !=null && electronicCardInfoByUnionId.getCustomerNo() !=null){
                    customerCardUseRecord.setCustomerNo(electronicCardInfoByUnionId.getCustomerNo());
                    customerCardUseRecord.setAmt(electronicCardInfoByUnionId.getAmt());
//                    BigDecimal amt1 = electronicCardInfoByUnionId.getAmt(); //客户原有金额
//                    BigDecimal amt2 = amt.add(customerCardUseRecord.getPresentAmt());   //客户本次共充值金额：充值金额+赠送金额
//                    customerCardUseRecord.setBalance(amt1.add(amt2));
                }
                //订单规则 时间+6位随机数
                Random random = new Random();
                String str="";
                for(int i=0; i<6; i++){
                    str+=random.nextInt(10);
                }
                String orderNo = System.nanoTime()+str;
                customerCardUseRecord.setOrderNo(orderNo);
                electronicMembershipCardService.insetCardUseRecordRecharge(customerCardUseRecord);      //插入电子会员卡的使用记录
                resultData = ResultData.success(orderNo);
            }
        }
        return gson.toJson(resultData);
    }

    //电子卡支付
    @RequestMapping(value = "/dzkPaySet", method = RequestMethod.GET)
    @ResponseBody
    @Transactional
    public  String dzkPaySet(@RequestParam String ordNo) throws ParseException {
        Gson gson =new Gson();
        ResultData resultData =ResultData.success(CodeMsg.SELECT_ORDER_ERROR);
        if(ordNo !=null){
            PayOrder payOrder = new PayOrder();
            payOrder.setOrderNo(ordNo);
            //获取用户订单信息
            Map<String, Object> resultMap = payOrderService.getOrderInfoAndUserInfoByOrderNo(payOrder);
            if(resultMap !=null && resultMap.get("status").toString().equals("0")){
                String stationId = resultMap.get("stationId").toString();
                String oilName =resultMap.get("oilName").toString();
                String mobilePhone =resultMap.get("mobilePhone").toString();
                String unionId =resultMap.get("unionId").toString();
                String minaOpenid =resultMap.get("minaOpenid").toString();
                String consumerId =resultMap.get("consumerId").toString();
                String registeDate =resultMap.get("registeDate").toString();
                String stationName =resultMap.get("stationName").toString();
                String consumer =resultMap.get("consumer").toString();
                String oilLiters = resultMap.get("orderLiters").toString();   //orderLiters
                String receivableAmt = resultMap.get("receivableAmt").toString();
                String amt = resultMap.get("amt").toString();
                String orderType = resultMap.get("orderType").toString();

                CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();  //电子会员卡插入消费记录
                BigDecimal balance = null;                                                  //电子会员卡余额
                CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
                String cardOilsType ="";
                switch (oilName){                               //根据油品名称存储电子卡油品类型 1.柴油 2 汽油
                    case "92#":
                        cardOilsType ="1";
                        break;
                    case "95#":
                        cardOilsType ="1";
                        break;
                    case "97#":
                        cardOilsType ="1";
                        break;
                    case "0#":
                        cardOilsType ="2";
                        break;
                    case "-10#":
                        cardOilsType ="2";
                        break;
                    case "-20#":
                        cardOilsType ="2";
                        break;
                }
                customerElectronicCard.setCardOilsType(cardOilsType);
                customerElectronicCard.setUnionId(resultMap.get("unionId").toString());
                customerElectronicCard.setStationId(Integer.valueOf(resultMap.get("stationId").toString()));
                //获取用户电子会员卡信息
                CustomerElectronicCard cardInfo = electronicMembershipCardService.getElectronicCardInfoByUnionId(customerElectronicCard);
                if(cardInfo !=null ){
                    customerCardUseRecord.setOrderNo(ordNo);                                        //电子会员卡记录订单号
                    customerCardUseRecord.setUnionId(cardInfo.getUnionId());                        //电子会员卡记录用户唯一标识
                    customerCardUseRecord.setCustomerNo(cardInfo.getCustomerNo());
                    customerCardUseRecord.setAmt(new BigDecimal(amt));      //电子会员卡记录用户余额
                    customerCardUseRecord.setStatus("1");
                    customerCardUseRecord.setCardOilsType(cardInfo.getCardOilsType());
                    customerCardUseRecord.setBalance(cardInfo.getAmt().subtract(new BigDecimal(amt)));
                    customerCardUseRecord.setStationName(cardInfo.getStationName());
                    customerCardUseRecord.setStationId(cardInfo.getStationId());
                    customerCardUseRecord.setUsageType("-");
                    customerCardUseRecord.setCustomerName(payOrder.getConsumer());
                    customerCardUseRecord.setCreateTime(new Date());
                    balance = cardInfo.getAmt();
                }
                //判断订单金额是否小于电子会员卡的余额
                if(balance !=null && customerCardUseRecord.getAmt().compareTo(balance) == -1){
                    electronicMembershipCardService.insetCardUseRecordConsumption(customerCardUseRecord);
                    //更新电子会员卡余额
                    CustomerElectronicCard c = new CustomerElectronicCard();
                    c.setAmt(balance.subtract(customerCardUseRecord.getAmt()));
                    c.setUnionId(customerCardUseRecord.getUnionId());
                    c.setStationId(customerCardUseRecord.getStationId());
                    c.setCardOilsType(cardOilsType);
                    electronicMembershipCardService.updateElectronicCardInfoByUnionId(c);
                    payOrder.setPayType("dzk");   //支付方式                                                 //支付类型
                    payOrder.setStatus("1");
                    payOrder.setPayDate(new Date());    //支付时间
                    payOrder.setReceivedAmt(Double.valueOf(amt));
                    payOrderService.getUpdatePayOrder(payOrder);
                    //更新客户表
                    CustomerManage customerManage = new CustomerManage();
                    customerManage.setStationId(Integer.valueOf(stationId));
                    customerManage.setMinaOpenid(minaOpenid);
                    customerManage.setOilName(oilName);
                    customerManage.setPhoneNumber(mobilePhone);
                    Map<String, Object> params_1 = new HashMap<>();
                    params_1.put("stationId", stationId);
                    params_1.put("oilName", oilName);
                    //获取该油站的优惠方式
                    String discountPlanType = stationService.getStationDiscountWay(stationId);
                    logger.info("油站优惠方式："+discountPlanType);
                    CustomerManage customerManageInfo = customerManagerService.getCustomerManageInfo(customerManage);
                    if(customerManageInfo !=null){
                        customerManage.setPhoneNumber(mobilePhone);
                        customerManage.setAmt(customerManageInfo.getAmt().add(new BigDecimal(amt)));
                        customerManage.setLiters(customerManageInfo.getLiters().add(new BigDecimal(oilLiters)));
                        if(discountPlanType !=null && discountPlanType.equals("1")){
                            List<Map> customerGradeInfo = customerGradeServices.getCustomerGradeList(params_1);  //直降
                            logger.info("该站直降等级信息："+ customerGradeInfo);
                            for (Map m: customerGradeInfo){
                                if(Double.valueOf(customerManage.getAmt().toString()) >= Double.valueOf(m.get("memberConditStart").toString()) && Double.valueOf(customerManage.getAmt().toString()) < Double.valueOf(m.get("memberConditEnd").toString())){
                                    customerManage.setGrade(m.get("grade").toString());     //存入等级名称
                                    customerManage.setMemberGrade(m.get("id").toString());     //存入等级ID
                                    break;
                                }
                            }
                            logger.info("直降等级信息是否存入客户表："+ "直降ID："+ customerManage.getMemberGrade()+ "直降名称： "+customerManage.getGrade());
                        }
                        customerManagerService.updateCustomerInfo(customerManage);
                    }else {
                        customerManage.setCustomerName(consumer);
                        customerManage.setStationName(stationName);
                        customerManage.setLiters(new BigDecimal(oilLiters));
                        customerManage.setAmt(new BigDecimal(amt));
                        customerManage.setPhoneNumber(mobilePhone);
                        customerManage.setMinaUserId(Integer.valueOf(consumerId));
                        customerManage.setUnionId(unionId);
                        customerManage.setRegtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(registeDate));
                        if(discountPlanType !=null && discountPlanType.equals("1")){
                            List<Map> customerGradeInfo = customerGradeServices.getCustomerGradeList(params_1);  //直降
                            logger.info("该站直降等级信息："+ customerGradeInfo);
                            if(customerGradeInfo !=null && customerGradeInfo.size() >0){
                                customerManage.setGrade(customerGradeInfo.get(0).get("grade").toString());     //存入等级名称
                                customerManage.setMemberGrade(customerGradeInfo.get(0).get("id").toString());     //存入等级ID
                            }
                            logger.info("直降等级信息是否存入客户表："+ "直降ID："+ customerManage.getMemberGrade()+ "直降名称： "+customerManage.getGrade());
                        }
                        customerManagerService.insertCustomerInfo(customerManage);
                    }

                    //电子卡消费公众号通知
                    if(cardInfo.getBlogOpenid() !=null){
                        String gzhAppId ="";
                        String gzhAppSecret ="";
                        Map<String, String> m = stationService.getStationAppIdAndAppSecret(cardInfo.getStationId());
                        if(m !=null && m.containsKey("stationName") && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
                            stationName = m.get("stationName");
                            gzhAppId = m.get("gzhAppId");
                            gzhAppSecret = m.get("gzhAppSecret");
                            //推送模板
                            List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
                            wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+cardInfo.getCustomerName()+"，您好：\n" + "您在"+stationName+"的最新消费交易信息如下"));
                            wxMpTemplate.add(new WxMpTemplateData("keyword1", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
                            wxMpTemplate.add(new WxMpTemplateData("keyword2", stationName));
                            wxMpTemplate.add(new WxMpTemplateData("keyword3", oilName));
                            wxMpTemplate.add(new WxMpTemplateData("keyword4", "电子卡"));
                            wxMpTemplate.add(new WxMpTemplateData("keyword5", amt));
                            wxMpTemplate.add(new WxMpTemplateData("remark","感谢您在"+stationName+"本次消费，当前还剩余额 "+c.getAmt()+"元，祝您生活愉快~！"));
                            GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
                            gzhNewsTemplate.setStationId(cardInfo.getStationId());
                            gzhNewsTemplate.setTemplateType("5");
                            GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(gzhNewsTemplate);
                            if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                                wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), cardInfo.getBlogOpenid(), wxMpTemplate);
                            }
                        }
                    }

                    StationPayManage stationPayManage = new StationPayManage();
                    stationPayManage.setStationId(Integer.valueOf(stationId));
                    StationPayManage stationPayManageInfo = stationService.selectStationPayManage(stationPayManage);
                    //是否启用积分功能
                    if(stationPayManageInfo !=null && stationPayManageInfo.getIntegralFlag().equals("1")){
                        //计算积分
                        CalculateIntegral calculateIntegral = new CalculateIntegral();
                        calculateIntegral.setAmt(new BigDecimal(amt));
                        calculateIntegral.setReceivableAmt(new BigDecimal(receivableAmt));
                        calculateIntegral.setOilLiters(new BigDecimal(oilLiters));
                        calculateIntegral.setOilName(oilName);
                        calculateIntegral.setOilType(orderType);
                        calculateIntegral.setStationId(Integer.valueOf(stationId));
                        calculateIntegral.setUnionId(unionId);
                        calculateIntegral.setOpenId(minaOpenid);   //小程序openId
                        //计算积分且推送积分
                        calculateIntegralAndPushIntegral(calculateIntegral, customerManage);
                    }
                    resultData = ResultData.success(CodeMsg.SUCCESS);
                }else {
                    resultData=ResultData.error(CodeMsg.BALANCE_NOT_EENOUGH);
                }
            }
            else {
                resultData=ResultData.error(CodeMsg.NO_ORDER);
            }
        }

        return gson.toJson(resultData);
    }

    //用户充值电子会员卡（储蓄卡）拉起随行付支付接口
    @RequestMapping(value = "/rechargeBalanceSXFPay", method = RequestMethod.POST)
    @ResponseBody
    public String rechargeBalanceSXFPay(@RequestBody RechargeBalance rechargeBalance){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(rechargeBalance !=null){
            String amt = rechargeBalance.getAmt();
            String openId = rechargeBalance.getOpenId();    //公众号的openId
            Integer stationId = rechargeBalance.getStationId();
            String userType = rechargeBalance.getUserType();
            String subject = rechargeBalance.getSubject();
            String orderNo = rechargeBalance.getOrderNo();
            //将业务参数存放在 JSON 对象中
            JSONObject reqData = new JSONObject();
            Map<String, String> resultMap = stationService.getStationAppIdAndAppSecret(stationId);
            if(resultMap !=null && resultMap.containsKey("gzhAppId") && resultMap.containsKey("mno")){
                logger.info("=================================电子会员卡（储蓄卡）充值功能调用随行付接口================================");
                try {
                    if(userType.equals("1")){
                        //1 是公众号
                        reqData.put("payWay", "02"); //支付方式  02 公众号/服 务窗/js支付 03 小程序
                        reqData.put("userId", openId); //用户号 微信：openid； 支付宝：userid；银联：userid；微信&支付宝必传，银联js为非必传
                        reqData.put("subAppid", resultMap.get("gzhAppId")); //微信公众号
                        logger.info("支付子商户："+ resultMap.get("gzhAppId"));
                    }else if(userType.equals("2")){
                        reqData.put("payWay", "03"); //支付方式  02 公众号/服 务窗/js支付 03 小程序
                        reqData.put("userId", openId); //用户号 微信：openid； 支付宝：userid；银联：userid；微信&支付宝必传，银联js为非必传
                        reqData.put("subAppid", resultMap.get("appId")); //微信小程序
                        logger.info("支付子商户："+ resultMap.get("appId"));
                    }
                    reqData.put("mno", resultMap.get("mno")); //商户编号
                    logger.info("商户编号："+ resultMap.get("mno"));
                    reqData.put("ordNo", orderNo); //商户订单号
                    reqData.put("amt", amt); //订单总金额
                    reqData.put("payType", "WECHAT"); //支付渠道
                    reqData.put("subject", subject); //订单标题
                    reqData.put("tradeSource", "01"); //交易来源 01服务商，02收银台，03硬件
                    reqData.put("trmIp", "172.16.2.1");//商家ip地址
                    reqData.put("outFrontFailUrl", ""); //js 支付，前台 事变通知地址
                    reqData.put("notifyUrl", "https://www.huijy.net/demo/getCardRechargeCallback"); //回调地址
//                    reqData.put("notifyUrl", "https://www.huijy.net/api/getCardRechargeCallback"); //回调地址
//                    reqData.put("subMechId", ""); //子商户号
//                    reqData.put("amt", "0.01");
//                    reqData.put("discountAmt", ""); //参与优惠金额
//                    reqData.put("unDiscountAmt", ""); //不参与优惠金额
//                    reqData.put("timeExpire", "10"); //订单失效时间, 以分钟为单位
//                    reqData.put("limitPay", "00"); //限制卡类型: 00-全部 01-限定不能使 用信用卡支付 默认值 00
//                    reqData.put("hbFqNum", "6"); //花呗分期数,仅可上送 6 或 12
//                    reqData.put("customerIp", ""); //持卡人ip地址，银联js支付时必传
//                    reqData.put("outFrontUrl", ""); //js 支付，前台 成功通知地址
//                    reqData.put("needReceipt", "00"); //电子发票功能 微信开具电子 发票使用
//                    reqData.put("ledgerAccountFlag", "00"); //是否做分账 分账交易使 用；00：做； 01：不做；不传默认为不做分账
//                    reqData.put("ledgerAccountEffectTime", "00"); //分账有效时间 单位为天；是 否做分账选择 00 时该字段必传
//                    reqData.put("ruleId", "00"); //同 步 分 账 规 则 id
//                    reqData.put("fusruleId", "00"); //同步分账规则
//                    reqData.put("ylTrmNo", ""); //银联终端号
//                    reqData.put("terminalId", ""); //TQ机具编号
//                    reqData.put("deviceNo ", "1111"); //设备号
//                    reqData.put("identityFlag", ""); //是否是实名支付
//                    reqData.put("buyerIdType", "IDCARD"); //证件类型
//                    reqData.put("buyerIdNo", "410523198701054018"); //证件号
//                    reqData.put("buyerName", "张三"); //买家姓名
//                    reqData.put("mobileNum", ""); //手机号
//                    reqData.put("extend", ""); //备用
                    String req= SXFPaySign.getSXFPay(reqData);
                    logger.debug("参数信息："+req);
                    System.out.println("req:" + req);
                    //此处不要改变reqData里面值的顺序用LinkedHashMap
                    HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
                    //组装加密串
                    String signContent = RSASignature.getOrderContent(reqMap);
                    System.out.println("拼接后的参数：" + signContent);
                    logger.debug("拼接后的参数："+signContent);
                    //sign
                    String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
                    System.out.println("============签名:" + sign);
                    reqMap.put("sign", sign);
                    String reqStr = JSON.toJSONString(reqMap);
                    System.out.println("请求参数:" + reqMap);
                    System.out.println("请求参数:" + reqStr);
                    //调用第三方接口地址
                    //String url = "https://openapi-test.tianquetech.com/order/jsapiScan";//测试地址
                    String url = "https://openapi.suixingpay.com/order/jsapiScan";//生产地址
                    String resultJson = HttpUtils.connectPostUrl(url, reqStr);
                    System.out.println("返回信息：" + resultJson);
                    //   logger.debug("返回信息："+resultJson);
                    //不要对reqData排序 所以用LinkedHashMap
                    HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
                    if ("0000".equals(result.get("code"))) {
                        //验签
                        String signResult = result.get("sign").toString();
                        result.remove("sign");
                        String resultStr = RSASignature.getOrderContent(result);
                        System.out.println(resultStr);
                        //sign
                        String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
                        System.out.println("resultSign:" + resultSign);
                        //组装加密串
                        if (RSASignature.doCheck(resultStr, signResult, SXFPaySign.sxfPublic)) {
                            System.out.println("===================验签成功==============");
                        }
                    }
                    resultData=ResultData.success(result);
                }catch (Exception e){
                    resultData=ResultData.error(CodeMsg.YEWU_FAIL,"订单支付失败");
                    e.printStackTrace();
                }
            }
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //用户电子会员卡（储蓄卡）充值功能随行付回调功能
    @RequestMapping(value = "/getCardRechargeCallback", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public void getCardRechargeCallback(@RequestBody JSONObject request){
        logger.info("=========================电子会员卡（储蓄卡）充值功能随行付回调功能===============================");
        logger.info("电子会员卡（储蓄卡）充值功能随行付回调返回过来的参数："+request);
        //logger.info("ordNo信息：" + request.get("ordNo").toString());
        //logger.info("sign信息：" + request.get("sign").toString());
        Gson gson =new Gson();
        String sxfUuid=request.get("sxfUuid").toString();     //随行付落单号
        String payWay=request.get("payWay").toString();     //随行付交易方式
        String payTime=request.get("payTime").toString();   //随行付交易时间
        String uuid=request.get("uuid").toString();         //随行付交易流水号
        String mno=request.get("mno").toString();//发起交易的商户编号
        String ordNo=request.get("ordNo").toString();//商户生成的订单号
        String amt=request.get("amt").toString();//金额
        String buyerId=request.get("buyerId").toString();//用户登录
        String transactionId=request.get("transactionId").toString();//用户登录
        String drType=request.get("drType").toString();//借贷记标识 1-借,2-贷，3-其他
        String payType=request.get("payType").toString();//对订单的描述，取值范围：WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
        String payBank=request.get("payBank").toString();//付款银行银行编码，例如 ICBC
        String pointAmount=request.get("pointAmount").toString();//代金券金额
        String totalOffstAmt=request.get("totalOffstAmt").toString();//消 费 者 付 款金额
        String settleAmt=request.get("settleAmt").toString();//商家入账金额
        String timeStamp=request.get("timeStamp").toString();//响应时间
        String sign=request.get("sign").toString();//签名
        String bizCode=request.get("bizCode").toString();//业务返回码
        String bizMsg=request.get("bizMsg").toString();//业 务 返 回 信息
        String openid=request.get("openid").toString();//微 信 或 支 付宝身份id()opendid userid
        String channelId=request.get("channelId").toString();//渠道商户号
        String subMechId=request.get("subMechId").toString();//子商户号
        String finishTime=request.get("finishTime").toString();//交易完成时间
        String clearDt=request.get("clearDt").toString();
        String settlementBatchNo=request.get("settlementBatchNo").toString();
        //String origOrdNo=request.get("origOrdNo").toString();//反交易退款异步通知
        //String origUuid=request.get("origUuid").toString();//token
        //String scene=request.get("scene").toString();//用户登录
        //String buyerAccount=request.get("buyerAccount").toString();//
        //String realRefundAmount=request.get("realRefundAmount").toString();//商家出账金额
        //String recFeeAmt=request.get("recFeeAmt").toString();//交易手续费
        //String recFeeRate=request.get("recFeeRate").toString();//交易手续费率
        //String refBuyerAmt=request.get("refBuyerAmt").toString();//消 费 者 到 账金额
        //String extend = extend=request.get("extend").toString();//备用

        //将业务参数存放在 JSON 对象中
        JSONObject reqData = new JSONObject();
        //备用
        if(request.containsKey("extend") && request.get("extend") !=null){
            String extend = request.get("extend").toString();
            reqData.put("extend", extend);
        }
        //优惠券参数
        if(request.containsKey("promotionDetail") && request.get("promotionDetail") !=null){
            String promotionDetail = request.get("promotionDetail").toString();
            reqData.put("promotionDetail", promotionDetail);
        }
        //商家出账金额
        if(request.containsKey("realRefundAmount") && request.get("realRefundAmount") !=null){
            String realRefundAmount = request.get("realRefundAmount").toString();
            reqData.put("realRefundAmount", realRefundAmount);
        }
        //szltFlag
        if(request.containsKey("szltFlag") && request.get("szltFlag") !=null){
            String szltFlag = request.get("szltFlag").toString();
            reqData.put("szltFlag", szltFlag);
        }
        //recFeeAmt
        if(request.containsKey("recFeeAmt") && request.get("recFeeAmt") !=null){
            String recFeeAmt = request.get("recFeeAmt").toString();
            reqData.put("recFeeAmt", recFeeAmt);
        }
        //szltRecfeeAmt
        if(request.containsKey("szltRecfeeAmt") && request.get("szltRecfeeAmt") !=null){
            String szltRecfeeAmt = request.get("szltRecfeeAmt").toString();
            reqData.put("szltRecfeeAmt", szltRecfeeAmt);
        }

        reqData.put("sxfUuid",sxfUuid);
        reqData.put("payWay",payWay);
        reqData.put("payTime",payTime);
        reqData.put("uuid",uuid);
        reqData.put("mno",mno);
        reqData.put("ordNo",ordNo);
        reqData.put("amt",amt);
        reqData.put("buyerId",buyerId);
        reqData.put("transactionId",transactionId);
        reqData.put("drType",drType);
        reqData.put("payType",payType);
        reqData.put("payBank",payBank);
        reqData.put("pointAmount",pointAmount);
        reqData.put("totalOffstAmt",totalOffstAmt);
        reqData.put("settleAmt",settleAmt);
        reqData.put("timeStamp",timeStamp);
        reqData.put("bizCode",bizCode);
        reqData.put("bizMsg",bizMsg);
        reqData.put("openid",openid);
        reqData.put("channelId",channelId);
        reqData.put("subMechId",subMechId);
        reqData.put("finishTime",finishTime);
        reqData.put("clearDt",clearDt);
        reqData.put("settlementBatchNo",settlementBatchNo);
        //reqData.put("realRefundAmount",realRefundAmount);
        //reqData.put("recFeeAmt",recFeeAmt);
        //reqData.put("recFeeRate",recFeeRate);
        //reqData.put("buyerAccount",buyerAccount);
        //reqData.put("origOrdNo",origOrdNo);
        //reqData.put("origUuid",origUuid);
        //reqData.put("scene",scene);
        //reqData.put("refBuyerAmt",refBuyerAmt);
        //reqData.put("extend",extend);
        //根据回调信息，先进行验签，验签后修改状态
        logger.info("打印参数信息"+gson.toJson(reqData));
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(gson.toJson(reqData), LinkedHashMap.class, Feature.OrderedField);
        //验签
        String resultStr = RSASignature.getOrderContent(result);
        //JSONObject req = new JSONObject();
        System.out.println(resultStr);
        if (RSASignature.doCheck(resultStr, sign, SXFPaySign.sxfPublic)) {
            logger.info("验签成功");
            //随行付回调验签成功更新客户电子卡余额 和 更新客户充值记录状态
            CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
            customerCardUseRecord.setOrderNo(ordNo);
            CustomerCardUseRecord customerCardUseRecordInfo = electronicMembershipCardService.getCardRecordByOrderNo(customerCardUseRecord);
            // 0表示未支付  1表示已支付
            if(customerCardUseRecordInfo !=null && customerCardUseRecordInfo.getStatus().equals("0")){
                logger.info("客户unionId：" +customerCardUseRecordInfo.getUnionId());
                logger.info("充值单号：" + ordNo);
                CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
                customerElectronicCard.setUnionId(customerCardUseRecordInfo.getUnionId());
                customerElectronicCard.setStationId(customerCardUseRecordInfo.getStationId());
                //customerCardUseRecord.setStationId(customerCardUseRecordInfo.getStationId());
                //是否有赠送金额
                BigDecimal presentAmt =new BigDecimal(0);
                //BigDecimal cardSumAmt = null;
                if(customerCardUseRecordInfo.getPresentAmt() !=null){
                    presentAmt = customerCardUseRecordInfo.getPresentAmt();  //客户充值赠送金额
                    logger.info("客户充值赠送金额：" +presentAmt.toString());
                }
                customerElectronicCard.setRecentlyTime(new Date());
                customerElectronicCard.setCardOilsType(customerCardUseRecordInfo.getCardOilsType());
                logger.info("查询客户电子卡信息所传递参数： 油站ID："+customerElectronicCard.getStationId()+"; 客户unionId：" + customerElectronicCard.getUnionId()+"; 卡的类型："+ customerElectronicCard.getCardOilsType());
                //获取客户充值的得电子卡信息
                CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getElectronicCardInfoByUnionId(customerElectronicCard);
                if(electronicCardInfo !=null){
                    logger.info("客户当前原有金额：" + electronicCardInfo.getAmt().toString());
                    customerElectronicCard.setAmt(electronicCardInfo.getAmt().add(new BigDecimal(amt)).add(presentAmt));
                    //更新客户要充值的电子会员卡的信息
                    if(customerElectronicCard.getStationId()!=null && customerElectronicCard.getUnionId() !=null){
                        logger.info("客户当前充值后应有金额：" + customerElectronicCard.getAmt().toString());
                        electronicMembershipCardService.updateElectronicCardInfoByUnionId(customerElectronicCard);
                    }
                    customerCardUseRecord.setStatus("1");
                    customerCardUseRecord.setBalance(customerElectronicCard.getAmt());
                    customerCardUseRecord.setOrderNo(ordNo);
                    //更新充值记录的状态和余额
                    electronicMembershipCardService.updateCardRecordStatusByOrderNo(customerCardUseRecord);
                    logger.info("===========客户电子会员卡充值成功已到账====");
                    logger.info("===========开始微信公众号推送消息功能：");
                    String stationName = electronicCardInfo.getStationName();
                    String blogOpenid = electronicCardInfo.getBlogOpenid();
                    Integer stationId = electronicCardInfo.getStationId();      //油站ID
                    String customerName = electronicCardInfo.getCustomerName(); //客户名称
                    BigDecimal balance = customerElectronicCard.getAmt();   //当前余额
                    String customerNo = electronicCardInfo.getCustomerNo();     //电子卡号
                    //获取要推送充值成功模板的ID
                    GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
                    gzhNewsTemplate.setTemplateType("3");   //3 代表电子会员卡充值成功模板类型
                    gzhNewsTemplate.setStationId(stationId);
                    GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(gzhNewsTemplate);
                    if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                        logger.info("推送消息的油站ID："+ gzhNewsTemplateInfo.getStationId().toString());
                        logger.info("当前要推送消息所用使用的模板ID："+ gzhNewsTemplateInfo.getTemplateId());
                        List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
                        String cardName = customerCardUseRecordInfo.getCardOilsType() =="1"? "汽油":"柴油";
                        wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+customerName+"，您好：\n" + "您在"+stationName+"的"+cardName+"电子会员卡充值成功信息如下"));
                        wxMpTemplate.add(new WxMpTemplateData("keyword1", customerNo));
                        wxMpTemplate.add(new WxMpTemplateData("keyword2", amt + " 元"));
                        wxMpTemplate.add(new WxMpTemplateData("keyword3", presentAmt.toString()+ " 元"));
                        wxMpTemplate.add(new WxMpTemplateData("keyword4", balance.toString()+ " 元"));
                        wxMpTemplate.add(new WxMpTemplateData("keyword5", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
                        wxMpTemplate.add(new WxMpTemplateData("remark","感谢您在"+ stationName+"的本次充值！"));
                        logger.info("要推送的消息内容：" +wxMpTemplate.toString());
                        Map<String, String> m = stationService.getStationAppIdAndAppSecret(stationId);
                        if(m !=null && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
                            String gzhAppId = m.get("gzhAppId");
                            String gzhAppSecret = m.get("gzhAppSecret");
                            if(electronicCardInfo.getBlogOpenid() !=null){
                                wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), blogOpenid, wxMpTemplate);
                                logger.info("电子会员卡公众号消息推送成功，推送人："+ blogOpenid);
                                logger.info("===================================本次充值流程结束===========================================");

                            }

                        }

                    }
                }
            }
        }else {
            logger.info("验签失败");
        }
    }

    //获取用户电子会员卡（储蓄卡）充值消费记录
    @RequestMapping(value = "/getCardRecordList", method = RequestMethod.GET)
    @ResponseBody
    public String getCardRecordList(@RequestParam Integer stationId, String unionId, String usageType){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null && unionId !=null){
            CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
            customerCardUseRecord.setUsageType(usageType); // '1' 代表充值 '0' 代表消费
            customerCardUseRecord.setStationId(stationId);
            customerCardUseRecord.setUnionId(unionId);
            List<CustomerCardUseRecord> cardUseRecordList = electronicMembershipCardService.getCardUseRecordList(customerCardUseRecord);
            resultData = ResultData.success(cardUseRecordList);
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //查询油站电子会员卡（储蓄卡）充值设置规则
    @RequestMapping(value = "/getCardRechargeSettingList", method = RequestMethod.GET)
    @ResponseBody
    public String getCardRechargeSettingList(@RequestParam Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null){
            CustomerCardSetting customerCardSetting = new CustomerCardSetting();
            customerCardSetting.setStationId(stationId);
            //customerCardSetting.setCardOilsType(cardOilsType);
            customerCardSetting.setOrderBy("ASC");  //优惠规则升序排序
            List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
            resultData = ResultData.success(cardRechargeSettingList);
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    /*
     * 计算消费生成积分
     * 注释：  1.判断油站配置的优惠类型
     *        2.如果是等级直降则存在等级取对应等级的积分规则，否则按照其他优惠方式
     */
    public void calculateIntegralAndPushIntegral(CalculateIntegral calculateIntegral, CustomerManage customerManage){
        int integral =0;
        //获取该油站的优惠方式
        String discountPlanType = stationService.getStationDiscountWay(calculateIntegral.getStationId().toString());
        IntegralRule integralRule = new IntegralRule();
        integralRule.setStationId(calculateIntegral.getStationId());
        integralRule.setEmptyDate(new Date());
        integralRule.setOilName(calculateIntegral.getOilName());
        integralRule.setOilType(calculateIntegral.getOilType());
        //获取该油站的积分规则
        List<IntegralRule> integralRuleList = integralRuleService.getIntegralRule(integralRule);
        if(integralRuleList !=null && integralRuleList.size() >0){
            logger.info("该油站积分规则信息：" + integralRuleList.toString());
            List<IntegralRuleDetail> integralRuleDetailList = integralRuleList.get(0).getIntegralRuleDetailList();
            String currentTime = null;          //当前时间
            String datePickerTime=null;         //活动时间
            String[] datePickerTimeArray ={};
            String integralActivity = integralRuleList.get(0).getIntegralActivity();
            String integralProportion =null;
            if(integralActivity !=null && integralActivity.equals("1")){
                datePickerTime = integralRuleList.get(0).getDatePickerTime();
                integralProportion = integralRuleList.get(0).getIntegralProportion();
                if(datePickerTime.contains(",")){
                    datePickerTimeArray = datePickerTime.split(",");
                }else {
                    datePickerTimeArray= new String[1];
                    datePickerTimeArray[0] = datePickerTime;
                }
            }
            if(integralRuleDetailList !=null && integralRuleDetailList.size() >0){
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());   //获取当前时间
                for (IntegralRuleDetail integralRuleDetail : integralRuleDetailList){
                    if(integralRuleDetail.getOilType().equals("1")){    //油品
                        if (integralRuleDetail.getRuleType().equals("1")){  //按照实收金额
                            if(calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //判断油站配置的优惠类型
                                if(discountPlanType.equals("1") && integralRuleDetail.getGread() !=null && customerManage.getGrade().equals(integralRuleDetail.getGread())){   //等级直降
                                    divide = calculateIntegral.getAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_HALF_DOWN);
                                    multiply = divide.multiply(integralRuleDetail.getIntegral());
                                }else {
                                    divide = calculateIntegral.getAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_HALF_DOWN);
                                    multiply = divide.multiply(integralRuleDetail.getIntegral());
                                }
                                if(integralActivity !=null && integralActivity.equals("1") &&  datePickerTimeArray !=null && integralProportion !=null){
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker){
                                        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 : datePickerTimeArray){
                                        if(s.equals(currentTime)){
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral =multiply.intValue();
                                logger.info("本次客户所得积分：" + integral);
                                break;
                            }
                        }else if (integralRuleDetail.getRuleType().equals("2")){    //按应收金额
                            if(calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==1 || calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //判断油站配置的优惠类型
                                if(discountPlanType.equals("1") && integralRuleDetail.getGread() !=null && customerManage.getGrade().equals(integralRuleDetail.getGread())){   //等级直降
                                    divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_HALF_DOWN);
                                    multiply = divide.multiply(integralRuleDetail.getIntegral());
                                }else {
                                    divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_HALF_DOWN);
                                    multiply = divide.multiply(integralRuleDetail.getIntegral());
                                }
                                if(integralActivity !=null && integralActivity.equals("1") && datePickerTimeArray !=null && integralProportion !=null){
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker){
                                        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 : datePickerTimeArray){
                                        if(s.equals(currentTime)){
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral = multiply.intValue();
                                logger.info("本次客户所得积分：" + integral);
                                break;
                            }
                        }else if (integralRuleDetail.getRuleType().equals("3")){    //按照加油升数
                            if(calculateIntegral.getOilLiters().compareTo(integralRuleDetail.getRuleTerms()) ==1 || calculateIntegral.getOilLiters().compareTo(integralRuleDetail.getRuleTerms()) ==0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //判断油站配置的优惠类型
                                if(discountPlanType.equals("1") && integralRuleDetail.getGread() !=null && customerManage.getGrade().equals(integralRuleDetail.getGread())){   //等级直降
                                    divide = calculateIntegral.getOilLiters().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_HALF_DOWN);
                                    multiply = divide.multiply(integralRuleDetail.getIntegral());
                                }else {
                                    divide = calculateIntegral.getOilLiters().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_HALF_DOWN);
                                    multiply = divide.multiply(integralRuleDetail.getIntegral());
                                }
                                if(integralActivity !=null && integralActivity.equals("1") && datePickerTimeArray !=null && integralProportion !=null){
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker){
                                        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 : datePickerTimeArray){
                                        if(s.equals(currentTime)){
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral =multiply.intValue();
                                logger.info("本次客户所得积分：" + integral);
                                break;
                            }
                        }
                    }else if (integralRuleDetail.getOilType().equals("2")){     //非油品
                        if (calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==1 || calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==0){
                            BigDecimal divide = null;
                            BigDecimal multiply = null;
                            //判断油站配置的优惠类型
                            if(discountPlanType.equals("1") && integralRuleDetail.getGread() !=null && customerManage.getGrade().equals(integralRuleDetail.getGread())){   //等级直降
                                divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_HALF_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());
                            }else {
                                divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_HALF_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());
                            }
                            if(integralActivity !=null && integralActivity.equals("1") && datePickerTimeArray !=null && integralProportion !=null){
                                String datePicker = integralRuleList.get(0).getDatePicker();    //获取日期类型
                                switch (datePicker){
                                    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 : datePickerTimeArray){
                                    if(s.equals(currentTime)){
                                        multiply = multiply.multiply(new BigDecimal(integralProportion));
                                        break;
                                    }
                                }
                            }
                            integral = multiply.intValue();
                            logger.info("本次客户所得积分：" + integral);
                            break;
                        }
                    }
                }
            }
            calculateIntegral.setIntegral(integral);
            this.pushIntegral(calculateIntegral);
        }
    }

    //更新积分并公众号推送积分
    public void pushIntegral(CalculateIntegral calculateIntegral){
        String gzhAppId ="";
        String gzhAppSecret ="";
        String stationName = "";        //油站名称
        BigDecimal surplusIntegral=null;
        String customerName =calculateIntegral.getNickName();       //客户昵称
        String openId = calculateIntegral.getOpenId();      //客户小程序ID
        Integer stationId = calculateIntegral.getStationId();   //油站ID
        int integral = calculateIntegral.getIntegral();     //当前加油积分
        String unionId = calculateIntegral.getUnionId();
        String mobilePhone = calculateIntegral.getMobilePhone();
        logger.info("客户小程序openId：" + openId);
        if(StringUtils.isNotBlank(calculateIntegral.getOpenId())){
            Map<String, String> m = stationService.getStationAppIdAndAppSecret(stationId);
            if(m !=null && m.containsKey("stationName") && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
                stationName = m.get("stationName");
                gzhAppId = m.get("gzhAppId");
                gzhAppSecret = m.get("gzhAppSecret");
            }
            CustomerPoints customerPoints = new CustomerPoints();
            customerPoints.setStationId(calculateIntegral.getStationId());
            customerPoints.setMinaOpenId(openId);
            customerPoints.setUnionId(calculateIntegral.getUnionId());
            CustomerPoints customerPointsInfo = customerPointsService.getCustomerPointsInfoByUnionId(customerPoints);
            if(customerPointsInfo !=null){
                logger.info("当前存在客户："+ customerPointsInfo.getMinaOpenId());
                logger.info("当前客户原有剩余积分："+ customerPointsInfo.getPoints().toString());
                customerName =customerPointsInfo.getCustomerName();
                surplusIntegral =new BigDecimal(customerPointsInfo.getPoints()).add(new BigDecimal(integral));
                CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                customerPointsRecord.setCreateTime(new Date());
                customerPointsRecord.setCustomerName(customerName);
                customerPointsRecord.setStationName(stationName);
                customerPointsRecord.setStationId(stationId);
                customerPointsRecord.setRecordType("+");
                customerPointsRecord.setUnionId(customerPointsInfo.getUnionId());
                customerPointsRecord.setIntegral(integral);
                customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);
                //customerPoints.setUnionId(customerPointsInfo.getUnionId());
                customerPoints.setPoints(surplusIntegral.intValue());
                logger.info("本次加油后客户应有总积分："+ customerPoints.getPoints().toString());
                //用户已累积积分
                BigDecimal add = new BigDecimal(customerPointsInfo.getAccumulatePoints()).add(new BigDecimal(integral));
                customerPoints.setAccumulatePoints(add.intValue());
                //更新客户积分
                customerPointsService.updateCustomerPointsInfo(customerPoints);
                logger.info("更新客户积分信息成功！");
                String blogOpenId = customerPointsInfo.getBlogOpenId();     //公众号openId
                if(blogOpenId !=null){
                    //推送模板
                    List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
                    wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+customerName+"，您好：\n" + "您在"+stationName+"的积分最新交易信息如下"));
                    wxMpTemplate.add(new WxMpTemplateData("time", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
                    wxMpTemplate.add(new WxMpTemplateData("type", "增加"));
                    wxMpTemplate.add(new WxMpTemplateData("Point", String.valueOf(integral)));
                    wxMpTemplate.add(new WxMpTemplateData("From", stationName));
                    wxMpTemplate.add(new WxMpTemplateData("remark",
                            "截止至" + new SimpleDateFormat(" yyyy年MM月dd日HH时mm分").format(new Date())+"，您在"+stationName+"的可用积分为 "+surplusIntegral.toString()+" 分"));
                    GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
                    gzhNewsTemplate.setStationId(stationId);
                    gzhNewsTemplate.setTemplateType("1");
                    GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(gzhNewsTemplate);
                    if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                        wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), blogOpenId, wxMpTemplate);
                    }
                }

            }else {
                logger.info("当前系统不存在该客户积分信息");
                //customerName =userName;
                surplusIntegral =new BigDecimal(integral);
                CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                customerPointsRecord.setCreateTime(new Date());
                customerPointsRecord.setCustomerName(customerName);
                customerPointsRecord.setStationName(stationName);
                customerPointsRecord.setStationId(stationId);
                customerPointsRecord.setRecordType("+");
                customerPointsRecord.setUnionId(unionId);
                customerPointsRecord.setIntegral(integral);
                customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);

                customerPoints.setUnionId(unionId);
                customerPoints.setPoints(surplusIntegral.intValue());
                customerPoints.setPoints(integral);
                customerPoints.setConsumptionPoints(0);
                customerPoints.setMobilePhone(mobilePhone);
                customerPoints.setCustomerName(customerName);
                customerPoints.setStationName(stationName);
                customerPoints.setAccumulatePoints(integral);
                customerPoints.setInvalidPoints(0);
                customerPoints.setCreateTime(new Date());
                //新增客户积分
                customerPointsService.insertCustomerPointsInfo(customerPoints);
                logger.info("新增客户积分信息成功！");
            }

        }
    }

}
