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.*;
import com.platform.yijia.pojo.*;
import com.platform.yijia.service.*;
import com.platform.yijia.utils.*;
import com.platform.yijia.utils.redis.RedisCacheUtil;
import com.platform.yijia.utils.weixinapp.WeiXinUserUtil;
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.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/demo")
public class PayController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(PayController.class);
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private StationOilGunService stationOilGunService;
    @Resource
    private CustomerGradeServices customerGradeServices;
    @Resource
    private StationService stationService;
    @Resource
    private CustomerPointsService customerPointsService;
    @Resource
    private IntegralRuleService integralRuleService;
    @Resource
    private CustomerPointsRecordService customerPointsRecordService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private  ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private  CustomerManagerService customerManagerService;




    /***
     * 微信子商户支付接口
     * @param weChatPaySetRequest
     * @return
     */
    @RequestMapping(value = "/weChatPaySet", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public  String weChatPaySet(@RequestBody WeChatPaySetRequest weChatPaySetRequest){
        Gson gson = new Gson();
        ResultData resultData = null;    //返回结果
        try {
            String type = weChatPaySetRequest.getType();    //获取配置类型
            JSONObject reqData = new JSONObject();          //微信子商户支付参数配置
            reqData.put("mno", weChatPaySetRequest.getMno());                           //商编
            reqData.put("subMchIdsubMchId", weChatPaySetRequest.getSubMchIdsubMchId()); //获取微信子商号
            if(type != null  && type !=""){
                reqData.put("type", type);
                //根据类型设置必传参数
                switch (type){
                    case "01":  //支付Appid
                        reqData.put("accountType", weChatPaySetRequest.getAccountType());   // 支付Appid类型  配置类型为01时必传
                        reqData.put("subAppid", weChatPaySetRequest.getSubAppid());         // 支付Appid      配置类型为01，02时必传
                        break;
                    case "02":  //关注Appid
                        reqData.put("subAppid", weChatPaySetRequest.getSubAppid());         // 支付Appid      配置类型为01，02时必传
                        reqData.put("subscribeAppid", weChatPaySetRequest.getSubscribeAppid());  // 推荐关注公众号Appid 配置类型为02时与推荐关注  小程序Appid二选一
                        reqData.put("receiptAppid", weChatPaySetRequest.getReceiptAppid());     // 推荐关注小程序Appid 配置类型为02时与推荐关注 公众号Appid二选一
                        break;
                    case "03":  //jsapi授权目录
                        reqData.put("jsapiPath", weChatPaySetRequest.getJsapiPath());       // jsapi授权目录 配置类型为03时必传
                        break;
                }
            }

            String sxfPay = SXFPaySign.getSXFPay(reqData);      //封装传参信息，增加公共信息，增加业务信息
            logger.debug("参数信息："+ sxfPay);
            System.out.println("req:" + sxfPay);
            //此处不要改变reqData里面值的顺序用LinkedHashMap
            HashMap reqMap = JSON.parseObject(sxfPay, 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));
            reqMap.put("sign", sign);
            String reqStr = JSON.toJSONString(reqMap);
            System.out.println("请求参数:" + reqMap);
            System.out.println("请求参数:" + reqStr);

            //String url = "https://openapi-test.tianquetech.com/merchant/weChatPaySet/addConf";    //测试环境
            String url = "https://openapi.tianquetech.com/merchant/weChatPaySet/addConf";       //生产环境
            //访问第三方接口
            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();
        }
        return  gson.toJson(resultData);
    }

    /**
     * 支付接口，前台上传支付信息，支付数据落地生产订单，调用随行付支付接口
     * @param
     * @return
     */
    @RequestMapping(value = "/getJhPayInfo", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public String getJhPayInfo(@RequestBody PayInfoRequest payInfoRequest){
        Gson gson =new Gson();
        ResultData resultData =null;
        //String token=payInfoRequest.getToken();//token
        String openId = payInfoRequest.getOpenId(); //用户openId
        String userType=payInfoRequest.getUserType();//用户登录类型 1 公众号。2 小程序
        //String mno=payInfoRequest.getMno();//获取商户号
        Integer orderId =payInfoRequest.getOrderId();
        //根据token 和登录类型 身份验证
        AppUserInfo appUserInfo =new AppUserInfo();
        //订单类型 是小程序还是公众号
        appUserInfo.setUserType(userType);
        if(userType.equals("1")){
            //1 是公众号
            appUserInfo.setBlogOpenid(openId);
        }else if(userType.equals("2")){
            //2是小程序
            appUserInfo.setMinaOpenid(openId);
        }
        List<AppUserInfo> appUserInfoList =appUserInfoService.Authentication(appUserInfo);

        if(appUserInfoList!=null&&appUserInfoList.size()==1){
            //调用聚合支付
            try{
                //根据订单号查询订单信息
                PayOrder payOrder=payOrderService.searchPayOrder(orderId);
                if(payOrder!=null){
                    //将业务参数存放在 JSON 对象中
                    JSONObject reqData = new JSONObject();

                    reqData.put("ordNo", payOrder.getOrderNo()); //商户订单号
                    //reqData.put("subMechId", ""); //子商户号
                    reqData.put("amt", payOrder.getAmt()); //订单总金额
                    //reqData.put("amt", "0.01");
                    //reqData.put("discountAmt", ""); //参与优惠金额
                    //reqData.put("unDiscountAmt", ""); //不参与优惠金额
                    reqData.put("payType", "WECHAT"); //支付渠道
                    Map<String, String> stationAppIdAndAppSecret = stationService.getStationAppIdAndAppSecret(Integer.valueOf(payInfoRequest.getStationId()));
                    if(stationAppIdAndAppSecret !=null && stationAppIdAndAppSecret.containsKey("appId") && stationAppIdAndAppSecret.containsKey("mno")){
                        if(userType.equals("1")){
                            reqData.put("subAppid", stationAppIdAndAppSecret.get("gzhAppId")); //微信公众号
                            logger.info("支付子商户："+ stationAppIdAndAppSecret.get("gzhAppId"));
                        }else if(userType.equals("2")){
                            reqData.put("subAppid", stationAppIdAndAppSecret.get("appId")); //微信小程序
                            logger.info("支付子商户："+ stationAppIdAndAppSecret.get("appId"));
                        }
                        reqData.put("mno", stationAppIdAndAppSecret.get("mno")); //商户编号
                        logger.info("商户编号："+ stationAppIdAndAppSecret.get("mno"));
                    }
                    if(userType.equals("1")){
                        //1 是公众号
                        reqData.put("payWay", "02"); //支付方式  02 公众号/服 务窗/js支付 03 小程序
                        reqData.put("userId", appUserInfoList.get(0).getBlogOpenid()); //用户号 微信：openid； 支付宝：userid；银联：userid；微信&支付宝必传，银联js为非必传
                    }else if(userType.equals("2")){
                        //2是小程序
                        reqData.put("payWay", "03"); //支付方式  02 公众号/服 务窗/js支付 03 小程序
                        reqData.put("userId", appUserInfoList.get(0).getMinaOpenid()); //用户号 微信：openid； 支付宝：userid；银联：userid；微信&支付宝必传，银联js为非必传
                    }
                    //reqData.put("timeExpire", "10"); //订单失效时间, 以分钟为单位
                    //reqData.put("limitPay", "00"); //限制卡类型: 00-全部 01-限定不能使 用信用卡支付 默认值 00

                    if(StringUtils.isNotBlank(payInfoRequest.getSubject())){
                        reqData.put("subject", payInfoRequest.getSubject()); //订单标题
                    }else {
                        reqData.put("subject", "聚合支付测试"); //订单标题
                    }
                    //reqData.put("hbFqNum", "6"); //花呗分期数,仅可上送 6 或 12
                    reqData.put("tradeSource", "01"); //交易来源 01服务商，02收银台，03硬件
                    reqData.put("trmIp", "172.16.2.1");//商家ip地址
                    // reqData.put("customerIp", ""); //持卡人ip地址，银联js支付时必传


                    //reqData.put("outFrontUrl", ""); //js 支付，前台 成功通知地址
                    reqData.put("outFrontFailUrl", ""); //js 支付，前台 事变通知地址
                    //reqData.put("notifyUrl", "https://www.huijy.net/api/getCallback"); //回调地址
                    reqData.put("notifyUrl", "https://www.huijy.net/demo/getCallback"); //回调地址
                    //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);
                }else {
                    resultData=ResultData.error(CodeMsg.YEWU_FAIL,"未查询到订单");
                }
            }catch (Exception e){
                resultData=ResultData.error(CodeMsg.YEWU_FAIL,"订单支付失败");
                e.printStackTrace();
            }
        }else{
            //返回失败支付失败信息
            resultData=ResultData.error(CodeMsg.USER_NOT_EXSIST);
        }
        return gson.toJson(resultData);
    }

    /**
     * 验证商户信息查询
     */
    @RequestMapping(value = "/getJhPayMnoInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getJhPayMnoInfo(@RequestParam String mno){
        try {
            JSONObject reqData = new JSONObject();
            reqData.put("mno", mno); //商户编号
            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/merchant/merchantInfoQuery";//测试地址
            String url = "https://openapi.tianquetech.com/merchant/merchantInfoQuery";//生产地址
            String resultJson = HttpUtils.connectPostUrl(url, reqStr);
            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("===================验签成功==============");
//                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 关单接口
     */
    @RequestMapping(value = "/getPayOrderClose", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public String getPayOrderClose(@RequestBody PayCloseRequestParamter payCloseRequestParamter) {
        String results="";
        Gson gson =new Gson();
        String mno=payCloseRequestParamter.getMno();
        String origOrderNo=payCloseRequestParamter.getOrigOrderNo();
        String origUuid=payCloseRequestParamter.getOrigUuid();
        String token=payCloseRequestParamter.getToken();
        String userType=payCloseRequestParamter.getUserType();
        boolean flag =appUserInfoService.selectAppUserInfo(token,userType);
        ResultData resultData =null;
        if(flag){
            try {
                JSONObject reqData = new JSONObject();
                reqData.put("mno",mno); //商户编号
                reqData.put("origOrderNo",origOrderNo);//系统商户订单号
                reqData.put("origUuid", origUuid);//随行付订单号
                String req= SXFPaySign.getSXFPay(reqData);
                //此处不要改变reqData里面值的顺序用LinkedHashMap
                HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
                //组装加密串
                String signContent = RSASignature.getOrderContent(reqMap);
                System.out.println("拼接后的参数：" + 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/query/close";//测试地址
                String url = "https://openapi.tianquetech.com/query/close";//生产地址
                String resultJson =  HttpUtils.connectPostUrl(url, reqStr);
                System.out.println("返回信息：" + 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.USER_NOT_EXSIST);
        }

        return  gson.toJson(resultData);
    }
    /**
     * 异步回调通知
     */
    @RequestMapping(value = "/getCallback", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public void getCallback(@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("验签成功");
            //验签成功，修改订单状态
            List<PayOrder> list = payOrderService.getPayOrderList(ordNo);
            logger.info("根据订单号，查询订单"+gson.toJson(list));
            if (list != null && list.size() == 1) {
                String status = list.get(0).getStatus();
                //状态为未支付 0  修改状态为1已支付
                if (status.equals("0")) {
                    PayOrder payOrder = new PayOrder();
                    payOrder.setOrderNo(ordNo);
                    payOrder.setStatus("1");
                    payOrder.setPayType("wx");
                    payOrder.setWxAmt(Double.valueOf(amt));
                    payOrder.setPayDate(new Date());    //支付时间
                    payOrder.setReceivedAmt(Double.valueOf(settleAmt)); //settleAmt商家入账金额
                    //修改订单状态
                    int count = payOrderService.getUpdatePayOrder(payOrder);
                    if(count == 1){
                        req.put("code","success");
                        req.put("msg","修改订单状态成功");
                        logger.info(req.toString());

                        //将用户消费的信息插入顾客表： 以手机号 油品名称 油站id为条件插入且存入 加油升数、实收金额、油站名称  根据订单号查询用户手机号
                        Map<String, Object> infoMap = payOrderService.getOrderInfoAndUserInfoByOrderNo(payOrder);   //获取该订单手机号、加油升数、实收金额、油站名称
                        logger.info("根据订单查询用户手机号等信息infoMap"+ infoMap.toString());
                        //手机号必须有
                        if(infoMap != null && infoMap.containsKey("mobilePhone") && infoMap.get("mobilePhone") !=null ){
                            //插入客户积分返回要插入客户的信息
                            //insertCustomerGroup(infoMap);
                            CustomerManage customerManage = insertCustomerManage(infoMap);
                            StationPayManage stationPayManage = new StationPayManage();
                            stationPayManage.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
                            StationPayManage stationPayManageInfo = stationService.selectStationPayManage(stationPayManage);
                            //是否启用积分功能
                            if(stationPayManageInfo !=null && stationPayManageInfo.getIntegralFlag().equals("1")){
                                //计算积分并推送
                                CalculateIntegral calculateIntegral = new CalculateIntegral();
                                calculateIntegral.setOpenId(infoMap.get("minaOpenid").toString());
                                calculateIntegral.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
                                calculateIntegral.setAmt(new BigDecimal(infoMap.get("amt").toString()));
                                if(infoMap.containsKey("orderType") && infoMap.get("orderType").toString().equals("1")){
                                    calculateIntegral.setOilType(infoMap.get("orderType").toString());
                                    calculateIntegral.setOilName(infoMap.get("oilName").toString());
                                    calculateIntegral.setOilLiters(new BigDecimal(infoMap.get("orderLiters").toString()));
                                }else if(infoMap.containsKey("orderType") && infoMap.get("orderType").toString().equals("2")){
                                    calculateIntegral.setOilType(infoMap.get("orderType").toString());
                                }
                                calculateIntegral.setUnionId(infoMap.get("unionId").toString());
                                calculateIntegral.setNickName(infoMap.get("consumer").toString());
                                calculateIntegral.setMobilePhone(infoMap.get("mobilePhone").toString());
                                calculateIntegral.setReceivableAmt(new BigDecimal(infoMap.get("receivableAmt").toString()));
                                //计算积分并推送
                                this.calculateIntegralAndPushIntegral(calculateIntegral, customerManage);
                            }
                            //打印小票
                            this.printReceipt(infoMap);
                        }else{
                            logger.info("该用户无手机号！");
                        }
                    }
                }
            }
        }else {
            logger.info("验签失败");
            req.put("code","fail");
            req.put("msg","失败");
        }
    }

    /***
     * 插入客户信息
     * @param infoMap
     * @return
     */
    public CustomerManage insertCustomerManage(Map infoMap){
        CustomerManage customerManage = new CustomerManage();   //存放客户信息
        customerManage.setGroupId(Integer.valueOf(infoMap.get("groupId").toString()));
        AppUserInfo appUserInfo = new AppUserInfo();    //存放查询用户信息
        appUserInfo.setMobilePhone(infoMap.get("mobilePhone").toString());
        appUserInfo.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
        //从客户信息表查询数据用于插入客户表 使用List原因：app_user_info存在小程序和公众号两种信息
        List<AppUserInfo> appUserInfoList = payOrderService.getUserInfoByOpenId(appUserInfo);
        Date blogRegTime = null;    //公众号注册时间
        Date minaRegTime = null;    //小程序注册时间
        if(appUserInfoList != null && appUserInfoList.size() >0){
            for(AppUserInfo u : appUserInfoList){
                //向客户表插入小程序和公众号的openId 用户表ID 用户手机号 注册时间
                if(u.getUnionId() !=null && u.getUnionId() !=""){
                    customerManage.setUnionId(u.getUnionId());
                }
                switch (u.getUserType()){
                    case "1":
                        customerManage.setBlogOpenid(u.getBlogOpenid());
                        customerManage.setBlogUserId(u.getUserId());
                        customerManage.setPhoneNumber(u.getMobilePhone());
                        customerManage.setCustomerName(u.getBlogNickName());
                        blogRegTime =u.getRegisteDate();
                        break;
                    case "2":
                        customerManage.setMinaOpenid(u.getMinaOpenid());
                        customerManage.setMinaUserId(u.getUserId());
                        customerManage.setPhoneNumber(u.getMobilePhone());
                        customerManage.setCustomerName(u.getBlogNickName());
                        minaRegTime = u.getRegisteDate();
                        break;
                }
            }
            //判断公众号和小程序时间取最早的时间
            if(blogRegTime !=null && minaRegTime != null){
                if(blogRegTime.compareTo(minaRegTime) >0){
                    customerManage.setRegtime(minaRegTime);
                }else if(blogRegTime.compareTo(minaRegTime) <0){
                    customerManage.setRegtime(blogRegTime);
                }else if(blogRegTime.compareTo(minaRegTime) ==0){
                    //相等时随便取一个
                    customerManage.setRegtime(minaRegTime);
                }
            }else if(blogRegTime == null){
                customerManage.setRegtime(minaRegTime);
            }else if(minaRegTime == null){
                customerManage.setRegtime(blogRegTime);
            }
        }

        customerManage.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));    //油站ID
        customerManage.setOilName(infoMap.get("oilName").toString());    //油品名称
        customerManage.setStationName(infoMap.get("stationName").toString());   //存入油站名称

        CustomerManage existCustomer = customerManagerService.getCustomerManageInfo(customerManage);         //已存在用户信息 existCustomer
        logger.info("查询出客户是否存在数据 null表示没有: " + existCustomer);

        //获取该油站的优惠方式
        String discountPlanType = stationService.getStationDiscountWay(infoMap.get("stationId").toString());
        logger.info("油站优惠方式："+discountPlanType);

        //判断该用户是否已存在
        if(existCustomer != null){  //存在该用户时更新
            if(existCustomer.getAmt() !=null){
                customerManage.setAmt(existCustomer.getAmt().add(BigDecimal.valueOf((Double) infoMap.get("amt"))));//存入金额 累加原来金额
            }else {
                customerManage.setAmt(BigDecimal.valueOf((Double) infoMap.get("amt")));
            }

            //此处用于更新没有会员ID的用户
            if(!StringUtils.isNotBlank(existCustomer.getMemberId())){
                String customerId=infoMap.get("groupId").toString()+infoMap.get("stationId").toString()+System.nanoTime();
                customerManage.setMemberId(customerId);
            }

            if(infoMap.containsKey("orderType") && infoMap.get("orderType").equals("1")) {
                if (existCustomer.getLiters() != null) {
                    customerManage.setLiters(existCustomer.getLiters().add(BigDecimal.valueOf((Double) infoMap.get("orderLiters"))));//存入升数 累加原来升数
                } else {
                    customerManage.setLiters(BigDecimal.valueOf((Double) infoMap.get("orderLiters")));
                }
            }
            logger.info("存在客户 更新时手机号参数: " + customerManage.getPhoneNumber());

            if(discountPlanType !=null && discountPlanType.equals("1")){
                //直降时存入等级名称和等级ID
                List<Map> customerGradeInfo = customerGradeServices.getCustomerGradeList(infoMap);  //直降
                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);
            //payOrderService.updateCustomer(customerManage); //存在 更新
        }else{  //该客户不存在时插入
            if(discountPlanType !=null && discountPlanType.equals("1")){
                //直降时存入等级名称和等级ID
                List<Map> customerGradeInfo = customerGradeServices.getCustomerGradeList(infoMap);  //直降
                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());
            }
            customerManage.setAmt(BigDecimal.valueOf((Double) infoMap.get("amt")));    //存入金额
            if(infoMap.containsKey("orderType") && infoMap.get("orderType").equals("1")){
                customerManage.setLiters(BigDecimal.valueOf((Double) infoMap.get("orderLiters")));    //存入升数
            }
            logger.info("不存在客户 新增时参数: " + customerManage.toString());
            //客户会员号
            String memberId=infoMap.get("groupId").toString()+infoMap.get("stationId").toString()+System.nanoTime();
            //客户会员号
            CustomerManage cm = new CustomerManage();
            cm.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
            cm.setPhoneNumber(infoMap.get("mobilePhone").toString());
            List<CustomerManage> customerManageInfoList = customerManagerService.getCustomerManageInfoList(cm);
            if(customerManageInfoList !=null && customerManageInfoList.size()>0){
                if(StringUtils.isNotBlank(customerManageInfoList.get(0).getMemberId())){
                    customerManage.setMemberId(customerManageInfoList.get(0).getMemberId());
                }else {
                    customerManage.setMemberId(memberId);
                }
            }else {
                customerManage.setMemberId(memberId);
            }
            customerManagerService.insertCustomerInfo(customerManage);
            //payOrderService.insertCustomer(customerManage);//不存在 新增
        }
        return customerManage;
    }

    /**
     * 打印小票
     */
    public void printReceipt(Map infoMap) {
        //打印机打印小票
        String content1;
        String content2;
        String orderNoP = "";
        String createdDateP ="";
        String stationNameP ="";
        String oilNameP ="";
        String orderLitersP ="";
        String oilPirceP ="";
        String receivableAmtP = "";
        String discountAmtP = "";
        String amtP = "";
        String mobilePhoneP = "";
        String payWayP = "";
        String sn;  //打印机编号

        if(StringUtils.isNotBlank(infoMap.get("orderNo").toString())){
            orderNoP =infoMap.get("orderNo").toString();
        }
        if(infoMap.containsKey("createdDate") && infoMap.get("createdDate") !=null ){
            //格式化日期
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            createdDateP =sdf.format(infoMap.get("createdDate"));
        }
        if(infoMap.containsKey("stationName") && infoMap.get("stationName") !=null ){
            stationNameP =infoMap.get("stationName").toString();
        }
        if(infoMap.containsKey("oilName") && infoMap.get("oilName") !=null ){
            oilNameP =infoMap.get("oilName").toString();
        }
        if(infoMap.containsKey("orderType") && infoMap.get("orderType").equals("1")) {
            //加油升数
            if (infoMap.containsKey("orderLiters") && infoMap.get("orderLiters") != null) {
                orderLitersP = infoMap.get("orderLiters") + "";
            }
            //油价
            if (infoMap.containsKey("oilPirce") && infoMap.get("oilPirce") != null) {
                oilPirceP = infoMap.get("oilPirce") + "";
            }
            if(infoMap.containsKey("discountAmt") && infoMap.get("discountAmt") !=null ){
                discountAmtP =infoMap.get("discountAmt")+"";
            }
        }else if(infoMap.containsKey("orderType") && infoMap.get("orderType").equals("2")) {
            orderLitersP ="0.00";
            oilPirceP = "0.00";
            discountAmtP ="0.00";
            receivableAmtP=infoMap.get("amt")+"";
        }
        if(infoMap.containsKey("receivableAmt") && infoMap.get("receivableAmt") !=null ){
            receivableAmtP =infoMap.get("receivableAmt")+"";
        }

        if(infoMap.containsKey("amt") && infoMap.get("amt") !=null ){
            amtP =infoMap.get("amt")+"";
        }
        if(infoMap.containsKey("mobilePhone") && infoMap.get("mobilePhone") !=null ){
            String phone =infoMap.get("mobilePhone")+"";
            //手机号中间四位****代替
            mobilePhoneP = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
        }
        if(infoMap.containsKey("payWay") && infoMap.get("payWay") !=null ){
            if(infoMap.get("payWay").equals("02") || infoMap.get("payWay").equals("03")){
                payWayP ="微信";
            }
        }

        content1 = "<CB>支付小票--顾客联</CB><BR>";
        content1 += "订单号："+orderNoP+"  <BR>";
        content1 += "时间："+createdDateP+" <BR>";
        content1 += "油站："+stationNameP+"  <BR>";
        if(infoMap.containsKey("orderType") && infoMap.get("orderType").toString().equals("1")){
            content1 += "油品： "+oilNameP+"  <BR>";
            content1 += "油量： "+orderLitersP+"  升<BR>";
            content1 += "单价： "+oilPirceP+" L/元<BR>";
        }
        content1 += "<BOLD><B>原价： "+receivableAmtP+" 元</B></BOLD><BR>";
        if(infoMap.containsKey("orderType") && infoMap.get("orderType").toString().equals("1")){
            content1 += "优惠： "+discountAmtP+" 元<BR>";
        }
        content1 += "支付： "+amtP+" 元<BR>";
        content1 += "支付方式： "+payWayP+" <BR>";
        content1 += "<BR>";
        //content1 += "--------------------------------<BR>";
        content1 += "<BR>";

        content2 = "<CB>支付小票--商户联</CB><BR>";
        content2 += "订单号："+orderNoP+" <BR>";
        content2 += "时间："+createdDateP+"<BR>";
        content2 += "油站："+stationNameP+" <BR>";
        if(infoMap.containsKey("orderType") && infoMap.get("orderType").toString().equals("1")){
            content2 += "油品： "+oilNameP+" <BR>";
            content2 += "油量： "+orderLitersP+" 升<BR>";
            content2 += "单价： "+oilPirceP+" L/元<BR>";
        }
        content2 += "<BOLD><B>原价： "+receivableAmtP+" 元</B></BOLD><BR>";
        if(infoMap.containsKey("orderType") && infoMap.get("orderType").toString().equals("1")){
            content2 += "优惠： "+discountAmtP+" 元<BR>";
        }
        content2 += "支付： "+amtP+" 元<BR>";
        content2 += "手机号： "+mobilePhoneP+" <BR>";
        content2 += "支付方式： "+payWayP+" <BR>";
        content2 += "<BR>";
        //获取打印机编号
        //sn = "921611605";     //测试打印机 sn：921611605 key：72338zma
        Map params  =new HashMap();
        params.put("stationId", infoMap.get("stationId").toString());
        params.put("oilGunNo", infoMap.get("oilGun").toString());
        Map m = stationOilGunService.getPrinterSnByStationIdAndOilGunNo(params);
        if(m !=null && m.containsKey("printerSn") && m.get("printerSn").toString()!= null && m.get("printerSn").toString()!=""){
            sn = m.get("printerSn").toString();
            //开始打印
            String printInfo="";    //打印信息
            if(m.containsKey("printSetting") && m.get("printSetting").toString()!= null && m.get("printSetting").toString()!=""){
                switch (m.get("printSetting").toString()){
                    case "1":   //1 客户联
                        printInfo = FeiEPrinterUtil.printReceipt(sn, content1);
                        break;
                    case "2":   //2 商户联
                        printInfo = FeiEPrinterUtil.printReceipt(sn, content2);
                        break;
                    case "3":   //3商户联和客户联
                        printInfo = FeiEPrinterUtil.printReceipt(sn, content1 + content2);
                        break;
                }
            }
            JSONObject jsonObject = JSONObject.parseObject(printInfo);
            if(jsonObject != null && jsonObject.getString("msg").equals("ok")){
                logger.info("打印成功：" + jsonObject.toString());
                //如果打印成功 添加小票数量
                PayOrder p = new PayOrder();
                p.setPrintCount(1);
                p.setOrderNo(infoMap.get("orderNo").toString());
                payOrderService.getUpdatePayOrder(p);
            }
        }else {
            logger.info("请正确配置打印机");
        }
    }

    /**
     * 计算消费生成积分
     * 注释：  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);
            customerManage.setIntegral(integral);
            customerManagerService.updateCustomerInfo(customerManage);
            this.pushIntegral(calculateIntegral);
        }
    }

    /*
     * 更新积分并公众号推送积分
     * @param stationId 油站ID
     * @param integral  本次所得积分
     * @param openId    小程序用户openID
     */
    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("新增客户积分信息成功！");
            }

        }
    }

}
