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.config.YiJiaRequest;
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 com.saobei.open.sdk.DefaultSaobeiApiClient;
import com.saobei.open.sdk.model.requst.trade.SaobeiMiniPayRequest;
import com.saobei.open.sdk.model.response.trade.SaobeiMiniPayResponse;
import lombok.SneakyThrows;
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.beans.factory.annotation.Value;
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.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@YiJiaRequest()
@CrossOrigin
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 WxPushUtil wxPushUtil;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private  CustomerManagerService customerManagerService;
    @Value("${yijia.path.global-prefix}")
    private String globalPrefix;
    @Value("${yijia.domainName}")
    private String domainName;



    /***
     * 微信子商户支付接口
     * @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 openId = payInfoRequest.getOpenId(); //用户openId
        String userType=payInfoRequest.getUserType();//用户登录类型 1 公众号。2 小程序
        String ordNo = payInfoRequest.getOrdNo();
        AppUserInfo appUserInfo =new AppUserInfo();
        //订单类型 是小程序还是公众号
        appUserInfo.setUserType(userType);
        if(userType.equals("1")){
            //1 是微信
            appUserInfo.setMinaOpenid(openId);
        }else if(userType.equals("2")){
            //2是支付宝
            appUserInfo.setALiId(openId);
        }
        //appUserInfo.setStationId(stationInfos.getGroupId());
        StationInfo stationInfo = new StationInfo();
        stationInfo.setStationId(Integer.valueOf(payInfoRequest.getStationId()));
        StationInfo stationInfos = stationService.selectStationInfo(stationInfo);
        appUserInfo.setStationId(stationInfos.getGroupId());
        AppUserInfo appUserInfos =appUserInfoService.getAppUserInfo(appUserInfo);
        if(appUserInfos!=null){
            //调用聚合支付
            try{
                //根据订单号查询订单信息
                PayOrder payOrder=payOrderService.selectOrderInfoByOrdNo(ordNo);
                if(payOrder!=null ){
                    if(payOrder.getStatus() !=null && payOrder.getStatus().equals("0")){
                        //将业务参数存放在 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", ""); //不参与优惠金额
                        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("appId")); //微信小程序
                                logger.info("支付子商户："+ stationAppIdAndAppSecret.get("appId"));
                            }else if(userType.equals("2")){
                                reqData.put("subAppid", stationAppIdAndAppSecret.get("aliAppId")); //支付宝小程序
                                logger.info("支付子商户："+ stationAppIdAndAppSecret.get("aliAppId"));
                            }
                            reqData.put("mno", stationAppIdAndAppSecret.get("mno")); //商户编号
                            logger.info("商户编号："+ stationAppIdAndAppSecret.get("mno"));
                        }
                        if(userType.equals("1")){
                            //1 是微信小程序
                            reqData.put("payType", "WECHAT"); //支付渠道 WECHAT：微信；ALIPAY:支付宝；UNIONPAY:银联
                            reqData.put("payWay", "03"); //支付方式  02 公众号/服 务窗/js支付 03 小程序
                            reqData.put("userId", appUserInfos.getMinaOpenid()); //用户号 微信：openid； 支付宝：userid；银联：userid；微信&支付宝必传，银联js为非必传
                        }else if(userType.equals("2")){
                            //2 是支付宝
                            reqData.put("payType", "ALIPAY"); //支付渠道 WECHAT：微信；ALIPAY:支付宝；UNIONPAY:银联
                            reqData.put("payWay", "03"); //支付方式  02 公众号/服 务窗/js支付 03 小程序
                            reqData.put("userId", appUserInfos.getALiId()); //用户号 微信：openid； 支付宝：userid；银联：userid；微信&支付宝必传，银联js为非必传
                        }
                        //reqData.put("timeExpire", "10"); //订单失效时间, 以分钟为单位
                        //reqData.put("limitPay", "00"); //限制卡类型: 00-全部 01-限定不能使 用信用卡支付 默认值 00

                        reqData.put("subject", payOrder.getOilName() + " - " +payOrder.getStationName()); //订单标题
                        //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 支付，前台 事变通知地址
                        //globalPrefix
                        String notifyUrl = "https://"+domainName+"/"+globalPrefix+"/getCallback";
                        logger.info("随行付调用回调地址：" + notifyUrl);
                        //reqData.put("notifyUrl", "https://www.huijy.net/api/getCallback"); //回调地址
                        reqData.put("notifyUrl", notifyUrl); //回调地址
                        //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: " + 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.ALREADY_PAY);
                    }
                }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);
    }

    /**
     * 支付接口，前台上传支付信息，支付数据落地生产订单，调用随行付支付接口
     * @param
     * @return
     */
    @RequestMapping(value = "/getPayChannelInfo", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public String getPayChannelInfo(@RequestBody PayInfoRequest payInfoRequest){
        Gson gson =new Gson();
        ResultData resultData =null;
        String openId = payInfoRequest.getOpenId(); //用户openId
        String userType=payInfoRequest.getUserType();//用户登录类型 1 公众号。2 小程序
        String ordNo = payInfoRequest.getOrdNo();
        AppUserInfo appUserInfo =new AppUserInfo();
        //订单类型 是小程序还是公众号
        appUserInfo.setUserType(userType);
        if(userType.equals("1")){
            //1 是微信
            appUserInfo.setMinaOpenid(openId);
        }else if(userType.equals("2")){
            //2是支付宝
            appUserInfo.setALiId(openId);
        }
        //appUserInfo.setStationId(stationInfos.getGroupId());
        StationInfo stationInfo = new StationInfo();
        stationInfo.setStationId(Integer.valueOf(payInfoRequest.getStationId()));
        StationInfo stationInfos = stationService.selectStationInfo(stationInfo);
        appUserInfo.setStationId(stationInfos.getGroupId());
        AppUserInfo appUserInfos =appUserInfoService.getAppUserInfo(appUserInfo);
        if(appUserInfos!=null){
            //调用聚合支付
            try{
                //根据订单号查询订单信息
                PayOrder payOrder=payOrderService.selectOrderInfoByOrdNo(ordNo);
                if(payOrder!=null ){
                    if(payOrder.getStatus() !=null && payOrder.getStatus().equals("0")){
                        if(payInfoRequest.getPayChannelType() !=null && payInfoRequest.getPayChannelType().equals("2")){
                            //云闪付支付方式
                            Map<String, String> staPayChannelInfo = stationService.getStationAppIdAndAppSecret(Integer.valueOf(payInfoRequest.getStationId()));
                            if(staPayChannelInfo !=null && staPayChannelInfo.containsKey("merchantNo") && staPayChannelInfo.containsKey("terminalId")
                                    && staPayChannelInfo.containsKey("yunKey") && staPayChannelInfo.containsKey("appId")) {
                                //秘钥
                                String yunKey = staPayChannelInfo.get("yunKey");                //23570b46a955484d92038f6a18d2b9d6
                                logger.info("==============================云闪付 小程序支付油品 拉起支付 ** 开始 **============================================");
                                DefaultSaobeiApiClient defaultSaobeiApiClient = new DefaultSaobeiApiClient(yunKey); //2ef428f4f76c414282e831baea9e4b0e
                                SaobeiMiniPayRequest requst = new SaobeiMiniPayRequest();
                                requst.setPay_ver("100");
                                requst.setPay_type("010");
                                requst.setService_id("015");
                                requst.setMerchant_no(staPayChannelInfo.get("merchantNo"));                 //商户号   845104816000034
                                requst.setTerminal_id(staPayChannelInfo.get("terminalId"));                 //终端号   18241101
                                requst.setTerminal_trace(payOrder.getOrderNo());                            //订单号   202003252204310000 6683315853083916109905
                                requst.setTerminal_time(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));      //"20200325220431"
                                //云闪付单位为分
                                BigDecimal totalFee = new BigDecimal(payOrder.getAmt().toString()).multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_DOWN);
                                logger.info("该订单金额：" + payOrder.getAmt().toString()+"; 拉起云闪付上送金额（单位：分)：" + totalFee.toString());
                                requst.setTotal_fee(totalFee.toString());
                                requst.setOpen_id(payInfoRequest.getOpenId());  // oRwjv4iHjSUgxNxOJOQ_60Ln7cno   obnG9jhDLvom5fGwuhYysmQTW4qQ

                                //订单内容
                                String orderBody = payOrder.getOilName()+ " - " + payOrder.getOilGun() + "号枪 - " +payOrder.getStationName();
                                requst.setOrder_body(orderBody);
                                //回调地址
                                String notifyUrl = "https://" + this.domainName + "/" + this.globalPrefix + "/getYunPayCallback";
                                logger.info("回调地址：" + notifyUrl);
                                requst.setNotify_url(notifyUrl);
                                //小程序appId
                                requst.setSub_appid(staPayChannelInfo.get("appId"));          //  wxe1135cd390b38a54    wxe568c727d466aef9        智慧易加公众号：wxc8189d3b3a7283e0

                                logger.info("请求报文：" + JSON.toJSONString(requst));
                                SaobeiMiniPayResponse response = (SaobeiMiniPayResponse) defaultSaobeiApiClient.execute(requst);
                                logger.info("返回报文：" + JSON.toJSONString(response));

                                //返回前端字段
                                Map<String, Object> reqData = new HashMap<>();
                                //Map<String, Object> resultMap = new HashMap<>();
                                if(response !=null && response.getResult_code().equals("01")){
                                    reqData.put("timeStamp", response.getTimeStamp());
                                    reqData.put("payPackage", response.getPackage_str());
                                    reqData.put("signType", response.getSignType());
                                    reqData.put("paySign", response.getPaySign());
                                    reqData.put("return_msg", response.getReturn_msg());
                                    reqData.put("merchant_name", response.getMerchant_name());
                                    reqData.put("total_fee", response.getTotal_fee());
                                    reqData.put("terminal_time", response.getTerminal_time());
                                    reqData.put("terminal_trace", response.getTerminal_trace());
                                    reqData.put("code", response.getResult_code());
                                }else if(response !=null && response.getResult_code().equals("02")){
                                    reqData.put("code", response.getResult_code());
                                    reqData.put("return_msg", response.getReturn_msg());
                                }else {
                                    //自己定义
                                    reqData.put("code", "03");
                                    reqData.put("return_msg", "当前支付系统参数配置错误请检查！");
                                }
                                //resultMap.put("respData", reqData);
                                logger.info("云闪付返回给前端字段：" + JSON.toJSONString(reqData));
                                resultData = ResultData.success(reqData);
                                logger.info("==============================云闪付 小程序支付油品 拉起支付 ** 结束 **============================================");
                            }else {
                                resultData = ResultData.error(CodeMsg.STATION_NULL_INFO);
                            }
                        }else{
                            //将业务参数存放在 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", ""); //不参与优惠金额
                            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("appId")); //微信小程序
                                    logger.info("支付子商户："+ stationAppIdAndAppSecret.get("appId"));
                                }else if(userType.equals("2")){
                                    reqData.put("subAppid", stationAppIdAndAppSecret.get("aliAppId")); //支付宝小程序
                                    logger.info("支付子商户："+ stationAppIdAndAppSecret.get("aliAppId"));
                                }
                                reqData.put("mno", stationAppIdAndAppSecret.get("mno")); //商户编号
                                logger.info("商户编号："+ stationAppIdAndAppSecret.get("mno"));
                            }
                            if(userType.equals("1")){
                                //1 是微信小程序
                                reqData.put("payType", "WECHAT"); //支付渠道 WECHAT：微信；ALIPAY:支付宝；UNIONPAY:银联
                                reqData.put("payWay", "03"); //支付方式  02 公众号/服 务窗/js支付 03 小程序
                                reqData.put("userId", appUserInfos.getMinaOpenid()); //用户号 微信：openid； 支付宝：userid；银联：userid；微信&支付宝必传，银联js为非必传
                            }else if(userType.equals("2")){
                                //2 是支付宝
                                reqData.put("payType", "ALIPAY"); //支付渠道 WECHAT：微信；ALIPAY:支付宝；UNIONPAY:银联
                                reqData.put("payWay", "03"); //支付方式  02 公众号/服 务窗/js支付 03 小程序
                                reqData.put("userId", appUserInfos.getALiId()); //用户号 微信：openid； 支付宝：userid；银联：userid；微信&支付宝必传，银联js为非必传
                            }
                            //reqData.put("timeExpire", "10"); //订单失效时间, 以分钟为单位
                            //reqData.put("limitPay", "00"); //限制卡类型: 00-全部 01-限定不能使 用信用卡支付 默认值 00

                            reqData.put("subject", payOrder.getOilName() + " - " +payOrder.getStationName()); //订单标题
                            //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 支付，前台 事变通知地址
                            //globalPrefix
                            String notifyUrl = "https://"+domainName+"/"+globalPrefix+"/getCallback";
                            logger.info("随行付调用回调地址：" + notifyUrl);
                            //reqData.put("notifyUrl", "https://www.huijy.net/api/getCallback"); //回调地址
                            reqData.put("notifyUrl", notifyUrl); //回调地址
                            //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);

                            Map<String, Object> r = new HashMap<>(); //返回前端参数
                            if ("0000".equals(result.get("code"))) {
                                //验签
                                String signResult = result.get("sign").toString();
                                result.remove("sign");
                                String resultStr = RSASignature.getOrderContent(result);
                                System.out.println("resultStr: " + 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("===================验签成功==============");
                                    logger.info("随行付返回字段：" +result);
                                    r.put("code", result.get("code"));
                                    r.put("msg", result.get("msg"));
                                    //net.sf.json.JSONObject result = location.getJSONObject("result").getJSONObject("addressComponent");
                                    JSONObject respData = (JSONObject)result.get("respData");
                                    r.put("payTimeStamp", respData.get("payTimeStamp"));
                                    r.put("ordNo", respData.get("ordNo"));
                                    r.put("payPackage", respData.get("payPackage"));
                                    r.put("bizMsg", respData.get("bizMsg"));
                                    r.put("paySign", respData.get("paySign"));
                                    r.put("bizCode", respData.get("bizCode"));
                                    r.put("payAppId", respData.get("payAppId"));
                                    r.put("sxfUuid", respData.get("sxfUuid"));
                                    r.put("paynonceStr", respData.get("paynonceStr"));
                                    r.put("paySignType", respData.get("paySignType"));
                                    r.put("uuid", respData.get("uuid"));

                                    r.put("orgId", result.get("orgId"));
                                    r.put("signType", result.get("signType"));
                                    r.put("reqId", result.get("reqId"));
                                }
                            }else {
                                r.put("code", result.get("code"));
                                r.put("msg", result.get("msg"));
                            }
                            logger.info("随行付支付时系统返回前端参数字段：" +r);
                            resultData=ResultData.success(r);
                        }
                    }else {
                        resultData=ResultData.error(CodeMsg.ALREADY_PAY);
                    }
                }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 JSONObject getCallback(@RequestBody JSONObject request) throws ParseException {
        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("scene") && request.get("scene") !=null){
            String scene = request.get("scene").toString();
            reqData.put("scene", scene);
        }

        //消 费 者 到 账金额
        if(request.containsKey("refBuyerAmt") && request.get("refBuyerAmt") !=null){
            String refBuyerAmt = request.get("refBuyerAmt").toString();
            reqData.put("refBuyerAmt", refBuyerAmt);
        }

        //buyerAccount 支付宝买家登录账号  掩码；示例：135***1234
        if(request.containsKey("buyerAccount") && request.get("buyerAccount") !=null){
            String buyerAccount = request.get("buyerAccount").toString();
            reqData.put("buyerAccount", buyerAccount);
        }

        //备用
        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)) {
            req.put("code","success");
            req.put("msg","成功");
            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");
                    if(payType.equals("WECHAT")){   //WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
                        payOrder.setPayType("wx");
                    }else if(payType.equals("ALIPAY")){
                        payOrder.setPayType("zfb");
                    }
                    payOrder.setWxAmt(Double.valueOf(amt));
                    payOrder.setDzkAmt(Double.valueOf("0"));
                    payOrder.setPayDate(new Timestamp(new Date().getTime()));    //支付时间
                    payOrder.setReceivedAmt(Double.valueOf(settleAmt)); //settleAmt商家入账金额
                    //修改订单状态
                    int count = payOrderService.getUpdatePayOrder(payOrder);
                    if(count == 1){
                        //将用户消费的信息插入顾客表： 以手机号 油品名称 油站id为条件插入且存入 加油升数、实收金额、油站名称  根据订单号查询用户手机号
                        Map<String, Object> infoMap = payOrderService.getOrderInfoAndUserInfoByOrderNo(payOrder);   //获取该订单手机号、加油升数、实收金额、油站名称
                        logger.info("根据订单查询用户手机号等订单信息"+ infoMap.toString());
                        //手机号必须有
                        if(infoMap != null && infoMap.containsKey("mobilePhone") && infoMap.get("mobilePhone") !=null ){
                            int integral =0;
                            StationInfo stationInfo = new StationInfo();
                            stationInfo.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
                            StationInfo stationInfos = stationService.selectStationInfo(stationInfo);
                            if(stationInfos.getIsLngFlagGroup() !=null && stationInfos.getIsLngFlagGroup().equals("1")){
                                //等于1表示次要业务：LNG集团平台加气（可能会出现）； 插入油站余额记录
                                StationBalanceChange stationBalanceChange = new StationBalanceChange();
                                stationBalanceChange.setStationId(stationInfos.getStationId());
                                stationBalanceChange.setAmt(Double.valueOf(infoMap.get("sellAmt").toString()));
                                stationBalanceChange.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(infoMap.get("payDate").toString()));
                                stationBalanceChange.setType("-");
                                stationBalanceChange.setOrderNo(ordNo);
                                //生成记录
                                payOrderService.insertStationBalanceExchange(stationBalanceChange);
                                StationInfo s = new StationInfo();
                                BigDecimal subtract = new BigDecimal(String.valueOf(stationInfos.getBalance())).subtract(new BigDecimal(infoMap.get("sellAmt").toString()));
                                s.setBalance(subtract.doubleValue());
                                s.setStationId(stationInfos.getStationId());
                                //更新油站余额
                                stationService.updateStationBalance(s);
                                logger.info("LNG加气平台支付更新余额完成！");
                            }else {
                                //当前系统主要业务逻辑
                                CustomerManage customerManage = this.insertCustomerManage(infoMap);                              //插入客户积分返回要插入客户的信息
                                CalculateIntegral calculateIntegral = new CalculateIntegral();
                                calculateIntegral.setOrderNo(ordNo);
                                if(infoMap.containsKey("consumer") && infoMap.get("consumer") !=null){
                                    calculateIntegral.setNickName(infoMap.get("consumer").toString());
                                }else {
                                    calculateIntegral.setNickName("");
                                }
                                calculateIntegral.setGroupId(Integer.valueOf(infoMap.get("groupId").toString()));               //集团ID
                                calculateIntegral.setCustomerGrade(customerManage.getGrade());                                  //客户等级
                                calculateIntegral.setIntegralRuleFlag(stationInfos.getIntegralRuleFlagGroup());                 //是否共享积分规则
                                calculateIntegral.setOpenId(infoMap.get("minaOpenid").toString());                              //客户小程序ID
                                if(infoMap.containsKey("blogOpenid") && StringUtils.isNotBlank(infoMap.get("blogOpenid").toString())){
                                    calculateIntegral.setBlogOpenid(infoMap.get("blogOpenid").toString());
                                }
                                calculateIntegral.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));           //油站ID
                                calculateIntegral.setStationName(infoMap.get("stationName").toString());                        //油站名称
                                calculateIntegral.setAmt(new BigDecimal(infoMap.get("amt").toString()));                        //实收金额
                                calculateIntegral.setOilType(infoMap.get("oilType").toString());                               //订单类型
                                calculateIntegral.setOilName(infoMap.get("oilName").toString());                                //油品名称
                                calculateIntegral.setOilLiters(new BigDecimal(infoMap.get("orderLiters").toString()));          //加油升数
                                calculateIntegral.setUnionId(infoMap.get("unionId").toString());                                //客户unionId
                                calculateIntegral.setNickName(infoMap.get("consumer").toString());                              //客户昵称
                                calculateIntegral.setMobilePhone(infoMap.get("mobilePhone").toString());                        //客户手机号
                                calculateIntegral.setReceivableAmt(new BigDecimal(infoMap.get("receivableAmt").toString()));    //应收金额

                                CustomerPoints customerPoints;
                                //计算积分
                                CalculateIntegral calculateIntegralInfos;
                                if(stationInfos.getIntegralRuleFlagGroup().equals("1")){    //表示积分共享
                                    if(stationInfos.getIntegralFlagGroup().equals("1")){    //集团开启积分功能
                                        //calculateIntegral.setGroupId(stationInfos.getGroupId());
                                        calculateIntegralInfos = this.calculateIntegral(calculateIntegral);
                                        //插入客户所得积分
                                        customerPoints = this.insertUserIntegral(calculateIntegralInfos);
                                        integral =calculateIntegralInfos.getIntegral();
                                        //推送积分
                                        this.pushIntegral(customerPoints, calculateIntegral);
                                    }
                                }else {
                                    if(stationInfos.getIntegralFlag().equals("1")){
                                        //calculateIntegral.setStationId(stationInfos.getStationId());
                                        calculateIntegralInfos = this.calculateIntegral(calculateIntegral);
                                        //插入客户所得积分
                                        customerPoints = this.insertUserIntegral(calculateIntegralInfos);
                                        //推送积分
                                        integral =calculateIntegralInfos.getIntegral();
                                        this.pushIntegral(customerPoints, calculateIntegral);

                                    }
                                }
                            }

                            //获取油枪绑定的POS机信息
                            StationDeviceManager stationDeviceManager = new StationDeviceManager();
                            stationDeviceManager.setGunNo(infoMap.get("oilGun").toString());
                            stationDeviceManager.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
                            List<StationDeviceManager> stationDeviceManagerList = stationService.getStationDeviceManagerList(stationDeviceManager);
                            if(stationDeviceManagerList !=null && stationDeviceManagerList.size() >0){
                                if(stationDeviceManagerList.get(0).getDeviceType() !=null && stationDeviceManagerList.get(0).getDeviceType() !=""){
                                    switch (stationDeviceManagerList.get(0).getDeviceType()){
                                        case "1":
                                            logger.info("小票机打印方式");
                                            infoMap.put("sn", stationDeviceManagerList.get(0).getDeviceNo());
                                            infoMap.put("printSetting", stationInfos.getPrintSetting());
                                            infoMap.put("isLngFlagGroup", stationInfos.getIsLngFlagGroup());
                                            this.printReceipt(infoMap);
                                            break;
                                        case "2":
                                            logger.info("POS机打印方式");
                                            payOrder.setIntegral(String.valueOf(integral));
                                            payOrder.setPrintSetting(stationInfos.getPrintSetting());
                                            payOrder.setIsLngFlagGroup(stationInfos.getIsLngFlagGroup());
                                            if(stationInfos.getIsLngFlagGroup() !=null && stationInfos.getIsLngFlagGroup().equals("1")){
                                                payOrder.setSellAmt(Double.valueOf(infoMap.get("sellAmt").toString()));
                                            }
                                            if(stationDeviceManagerList.get(0).getPosFanoutExchange() !=null && stationDeviceManagerList.get(0).getPosQueue() !=null){
                                                logger.info("POS设备交换机信息:" + stationDeviceManagerList.get(0).getPosFanoutExchange());
                                                payOrder.setPosFanoutExchange(stationDeviceManagerList.get(0).getPosFanoutExchange());
                                                payOrder.setPosQueue(stationDeviceManagerList.get(0).getPosQueue());
                                                payOrder.setDeviceNo(stationDeviceManagerList.get(0).getDeviceNo());
                                                this.posPrintReceipt(payOrder);
                                            }
                                            break;
                                    }
                                }
                            }


                            //logger.info("小票打印方式：" + stationInfo.getPrintDeviceType());
//                            if(stationInfos !=null && stationInfos.getPrintDeviceType() !=null){
//                                switch (stationInfos.getPrintDeviceType()){
//                                    case "1":   //小票机打印
//                                        logger.info("小票机打印");
//                                        Map map = new HashMap();
//                                        map.put("stationId", infoMap.get("stationId").toString());
//                                        map.put("oilGunNo", infoMap.get("oilGun").toString());
//                                        map.put("deviceType", stationInfos.getPrintDeviceType());
//                                        List<Map> listDevices = stationOilGunService.getPrinterSnByStationIdAndOilGunNoList(map);
//                                        infoMap.put("sn", listDevices.get(0).get("printerSn").toString());
//                                        infoMap.put("printSetting", stationInfos.getPrintSetting());
//                                        this.printReceipt(infoMap);
//                                        break;
//                                    case "2":   //POS机打印
//                                        logger.info("POS机打印");
//                                        payOrder.setIntegral(String.valueOf(integral));
//                                        payOrder.setPrintSetting(stationInfos.getPrintSetting());
//                                        this.posPrintReceipt(payOrder);
//                                        break;
//                                }
//                            }
                        }else{
                            logger.info("该用户无手机号！");
                        }
                    }else {
                        logger.info("更新订单状态失败！");
                    }
                }
            }else {
                logger.info("该订单不存在！");
            }
        }else {
            logger.info("验签失败");
            req.put("code","fail");
            req.put("msg","失败");
        }
        logger.info("返回随行付参数信息："+req.toString());
        return req;
    }


    /***
     * 小程序云闪付扫呗回调
     * @param params
     * @return
     */
    @RequestMapping(value = "/getYunPayCallback", consumes = "text/xml", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public net.sf.json.JSONObject getYunPayCallback(@RequestBody String params) throws ParseException {
        logger.info("=============================云闪付（扫呗） 小程序支付完成 回调接口 ** 开始 ** ===============================================");
        net.sf.json.JSONObject result = new net.sf.json.JSONObject();       //返回
        YunPayCallBack yunPayCallBack = JSON.parseObject(params, YunPayCallBack.class);
        logger.info("云闪付扫呗 小程序支付 回调接口返回参数：" + params);
        //logger.info("云闪付扫呗调用回调接口状态码：" + yunPayCallBack.getResult_code());
        if(yunPayCallBack.getResult_code() !=null && yunPayCallBack.getResult_code().equals("01")){
            logger.info("-------------------------云闪付回调成功--------------------------                      ");
            //返给云闪付状态码
            result.put("return_code", "01");
            result.put("return_msg", "success");
            //业务逻辑
            String ordNo = yunPayCallBack.getTerminal_trace();
            List<PayOrder> list = payOrderService.getPayOrderList(ordNo);
            //logger.info("根据订单号，查询订单"+gson.toJson(list));
            if (list != null && list.size() == 1) {
                String status = list.get(0).getStatus();
                if(status !=null && status.equals("0")){
                    PayOrder payOrder = new PayOrder();
                    payOrder.setOrderNo(ordNo);
                    payOrder.setStatus("1");
                    if(yunPayCallBack.getPay_type().equals("010")){   //WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
                        payOrder.setPayType("wx");
                    }else if(yunPayCallBack.getPay_type().equals("020")){
                        payOrder.setPayType("zfb");
                    }
                    payOrder.setWxAmt(Double.valueOf(yunPayCallBack.getReceipt_fee()));
                    payOrder.setDzkAmt(Double.valueOf("0"));
                    payOrder.setPayDate(new Timestamp(new Date().getTime()));    //支付时间
                    payOrder.setReceivedAmt(Double.valueOf(yunPayCallBack.getReceipt_fee())); //settleAmt商家入账金额
                    //修改订单状态
                    int count = payOrderService.getUpdatePayOrder(payOrder);
                    if(count == 1){
                        Map<String, Object> infoMap = payOrderService.getOrderInfoAndUserInfoByOrderNo(payOrder);   //获取该订单手机号、加油升数、实收金额、油站名称
                        logger.info("根据订单查询用户手机号等订单信息"+ infoMap.toString());
                        //手机号必须有
                        if(infoMap != null && infoMap.containsKey("mobilePhone") && infoMap.get("mobilePhone") !=null ){
                            int integral =0;
                            StationInfo stationInfo = new StationInfo();
                            stationInfo.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
                            StationInfo stationInfos = stationService.selectStationInfo(stationInfo);
                            if(stationInfos.getIsLngFlagGroup() !=null && stationInfos.getIsLngFlagGroup().equals("1")){
                                //等于1表示次要业务：LNG集团平台加气（可能会出现）； 插入油站余额记录
                                StationBalanceChange stationBalanceChange = new StationBalanceChange();
                                stationBalanceChange.setStationId(stationInfos.getStationId());
                                stationBalanceChange.setAmt(Double.valueOf(infoMap.get("sellAmt").toString()));
                                stationBalanceChange.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(infoMap.get("payDate").toString()));
                                stationBalanceChange.setType("-");
                                stationBalanceChange.setOrderNo(ordNo);
                                //生成记录
                                payOrderService.insertStationBalanceExchange(stationBalanceChange);
                                StationInfo s = new StationInfo();
                                BigDecimal subtract = new BigDecimal(String.valueOf(stationInfos.getBalance())).subtract(new BigDecimal(infoMap.get("sellAmt").toString()));
                                s.setBalance(subtract.doubleValue());
                                s.setStationId(stationInfos.getStationId());
                                //更新油站余额
                                stationService.updateStationBalance(s);
                                logger.info("LNG加气平台支付更新余额完成！");
                            }else {
                                //当前系统主要业务逻辑
                                CustomerManage customerManage = this.insertCustomerManage(infoMap);                              //插入客户积分返回要插入客户的信息
                                CalculateIntegral calculateIntegral = new CalculateIntegral();
                                calculateIntegral.setOrderNo(ordNo);
                                if(infoMap.containsKey("consumer") && infoMap.get("consumer") !=null){
                                    calculateIntegral.setNickName(infoMap.get("consumer").toString());
                                }else {
                                    calculateIntegral.setNickName("");
                                }
                                calculateIntegral.setGroupId(Integer.valueOf(infoMap.get("groupId").toString()));               //集团ID
                                calculateIntegral.setCustomerGrade(customerManage.getGrade());                                  //客户等级
                                calculateIntegral.setIntegralRuleFlag(stationInfos.getIntegralRuleFlagGroup());                 //是否共享积分规则
                                calculateIntegral.setOpenId(infoMap.get("minaOpenid").toString());                              //客户小程序ID
                                if(infoMap.containsKey("blogOpenid") && StringUtils.isNotBlank(infoMap.get("blogOpenid").toString())){
                                    calculateIntegral.setBlogOpenid(infoMap.get("blogOpenid").toString());
                                }
                                calculateIntegral.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));           //油站ID
                                calculateIntegral.setStationName(infoMap.get("stationName").toString());                        //油站名称
                                calculateIntegral.setAmt(new BigDecimal(infoMap.get("amt").toString()));                        //实收金额
                                calculateIntegral.setOilType(infoMap.get("oilType").toString());                               //订单类型
                                calculateIntegral.setOilName(infoMap.get("oilName").toString());                                //油品名称
                                calculateIntegral.setOilLiters(new BigDecimal(infoMap.get("orderLiters").toString()));          //加油升数
                                calculateIntegral.setUnionId(infoMap.get("unionId").toString());                                //客户unionId
                                calculateIntegral.setNickName(infoMap.get("consumer").toString());                              //客户昵称
                                calculateIntegral.setMobilePhone(infoMap.get("mobilePhone").toString());                        //客户手机号
                                calculateIntegral.setReceivableAmt(new BigDecimal(infoMap.get("receivableAmt").toString()));    //应收金额

                                CustomerPoints customerPoints;
                                //计算积分
                                CalculateIntegral calculateIntegralInfos;
                                if(stationInfos.getIntegralRuleFlagGroup().equals("1")){    //表示积分共享
                                    if(stationInfos.getIntegralFlagGroup().equals("1")){    //集团开启积分功能
                                        //calculateIntegral.setGroupId(stationInfos.getGroupId());
                                        calculateIntegralInfos = this.calculateIntegral(calculateIntegral);
                                        //插入客户所得积分
                                        customerPoints = this.insertUserIntegral(calculateIntegralInfos);
                                        integral =calculateIntegralInfos.getIntegral();
                                        //推送积分
                                        this.pushIntegral(customerPoints, calculateIntegral);
                                    }
                                }else {
                                    if(stationInfos.getIntegralFlag().equals("1")){
                                        //calculateIntegral.setStationId(stationInfos.getStationId());
                                        calculateIntegralInfos = this.calculateIntegral(calculateIntegral);
                                        //插入客户所得积分
                                        customerPoints = this.insertUserIntegral(calculateIntegralInfos);
                                        //推送积分
                                        integral =calculateIntegralInfos.getIntegral();
                                        this.pushIntegral(customerPoints, calculateIntegral);
                                    }
                                }
                            }

                            //获取油枪绑定的POS机信息
                            StationDeviceManager stationDeviceManager = new StationDeviceManager();
                            stationDeviceManager.setGunNo(infoMap.get("oilGun").toString());
                            stationDeviceManager.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
                            List<StationDeviceManager> stationDeviceManagerList = stationService.getStationDeviceManagerList(stationDeviceManager);
                            if(stationDeviceManagerList !=null && stationDeviceManagerList.size() >0){
                                if(stationDeviceManagerList.get(0).getDeviceType() !=null && stationDeviceManagerList.get(0).getDeviceType() !=""){
                                    switch (stationDeviceManagerList.get(0).getDeviceType()){
                                        case "1":
                                            logger.info("小票机打印方式");
                                            infoMap.put("sn", stationDeviceManagerList.get(0).getDeviceNo());
                                            infoMap.put("printSetting", stationInfos.getPrintSetting());
                                            infoMap.put("isLngFlagGroup", stationInfos.getIsLngFlagGroup());
                                            this.printReceipt(infoMap);
                                            break;
                                        case "2":
                                            logger.info("POS机打印方式");
                                            payOrder.setIntegral(String.valueOf(integral));
                                            payOrder.setPrintSetting(stationInfos.getPrintSetting());
                                            payOrder.setIsLngFlagGroup(stationInfos.getIsLngFlagGroup());
                                            if(stationInfos.getIsLngFlagGroup() !=null && stationInfos.getIsLngFlagGroup().equals("1")){
                                                payOrder.setSellAmt(Double.valueOf(infoMap.get("sellAmt").toString()));
                                            }
                                            if(stationDeviceManagerList.get(0).getPosFanoutExchange() !=null && stationDeviceManagerList.get(0).getPosQueue() !=null){
                                                logger.info("POS设备交换机信息:" + stationDeviceManagerList.get(0).getPosFanoutExchange());
                                                payOrder.setPosFanoutExchange(stationDeviceManagerList.get(0).getPosFanoutExchange());
                                                payOrder.setPosQueue(stationDeviceManagerList.get(0).getPosQueue());
                                                payOrder.setDeviceNo(stationDeviceManagerList.get(0).getDeviceNo());
                                                this.posPrintReceipt(payOrder);
                                            }
                                            break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }else {
            result.put("return_code", "02");
            result.put("return_msg", "fail");
        }
        logger.info("返给云闪付结果信息：" + result);
        logger.info("    =======================================云闪付（扫呗） 小程序支付完成 回调接口 ** 结束 ** ===============================================");
        return result;
    }

    //插入客户信息
    public CustomerManage insertCustomerManage(Map infoMap) throws ParseException {
        CustomerManage customerManage = new CustomerManage();   //存放客户信息
        customerManage.setGroupId(Integer.valueOf(infoMap.get("groupId").toString()));
        customerManage.setUnionId(infoMap.get("unionId").toString());
        customerManage.setMinaUserId(Integer.valueOf(infoMap.get("consumerId").toString()));
        customerManage.setPhoneNumber(infoMap.get("mobilePhone").toString());
        customerManage.setCustomerName(infoMap.get("consumer").toString());
        customerManage.setRegtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(infoMap.get("registeDate").toString()));
        customerManage.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));    //油站ID
        customerManage.setOilName(infoMap.get("oilName").toString());    //油品名称
        CustomerManage c = new CustomerManage();   //存放客户信息
        c.setUnionId(infoMap.get("unionId").toString());
        c.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));    //油站ID
        c.setOilName(infoMap.get("oilName").toString());    //油品名称
        CustomerManage existCustomer = customerManagerService.getCustomerManageInfo(c);         //已存在用户信息 existCustomer
        //判断该用户是否已存在
        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());
            //直降时存入等级名称和等级ID
            List<Map> customerGradeInfo = customerGradeServices.getCustomerGradeListOrderByDesc(infoMap);  //直降
            logger.info("该站直降等级信息："+ customerGradeInfo);
            for (Map m: customerGradeInfo){
                if(Double.valueOf(customerManage.getAmt().toString()) >= Double.valueOf(m.get("memberConditStart").toString())){
                    customerManage.setGrade(m.get("id").toString());     //存入等级ID
                    break;
                }
            }
            logger.info("直降等级信息是否存入客户表："+ "直降ID："+ customerManage.getGrade());
            customerManagerService.updateCustomerInfo(customerManage);
        }else{  //该客户不存在时插入
            //直降时存入等级名称和等级ID
            List<Map> customerGradeInfo = customerGradeServices.getCustomerGradeList(infoMap);  //直降
            logger.info("该站直降等级信息："+ customerGradeInfo);
            if(customerGradeInfo !=null && customerGradeInfo.size() >0){
                customerManage.setGrade(customerGradeInfo.get(0).get("id").toString());     //存入等级ID
            }
            logger.info("直降等级信息是否存入客户表："+ "直降ID："+ 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);
        }
        return customerManage;
    }


    //POS机打印小票
    public void posPrintReceipt(PayOrder payOrder){
        Map<String, Object> infoMap = payOrderService.getOrderInfoAndUserInfoByOrderNo(payOrder);
        Map<String, Object> m = new HashMap<>();

        if(payOrder.getTransactionId() !=null){
            m.put("transactionId", payOrder.getTransactionId());
        }
        if(payOrder.getIntegral() !=null){
            m.put("integral", payOrder.getIntegral());
        }
        if(infoMap !=null && infoMap.containsKey("oilPersonnel") && infoMap.get("oilPersonnel") !=null){
            m.put("oilPersonnel", infoMap.get("oilPersonnel").toString());
        }
        if(infoMap !=null && infoMap.containsKey("orderNo") && infoMap.get("orderNo") !=null){
            m.put("orderNo", infoMap.get("orderNo").toString());
        }
        //if(infoMap !=null && infoMap.containsKey("amt") && infoMap.get("amt") !=null){
            if(payOrder.getIsLngFlagGroup() !=null && payOrder.getIsLngFlagGroup().equals("1")){
                m.put("amt", infoMap.get("sellAmt").toString());
                m.put("discountAmt", infoMap.get("sellDiscountAmt").toString());
            }else {
                m.put("amt", infoMap.get("amt").toString());
                m.put("discountAmt", infoMap.get("discountAmt").toString());
            }

        //}
        if(infoMap !=null && infoMap.containsKey("receivableAmt") && infoMap.get("receivableAmt") !=null){
            m.put("receivableAmt", infoMap.get("receivableAmt").toString());
        }
//        if(infoMap !=null && infoMap.containsKey("discountAmt") && infoMap.get("discountAmt") !=null){
//            m.put("discountAmt", infoMap.get("discountAmt").toString());
//        }
        if(infoMap !=null && infoMap.containsKey("oilName") && infoMap.get("oilName") !=null){
            m.put("oilName", infoMap.get("oilName").toString());
        }
        if(infoMap !=null && infoMap.containsKey("oilGun") && infoMap.get("oilGun") !=null){
            m.put("oilGun", infoMap.get("oilGun").toString());
        }
        if(infoMap !=null && infoMap.containsKey("createdDate") && infoMap.get("createdDate") !=null){
            //格式化日期
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createdDate = sdf.format(infoMap.get("createdDate"));
            m.put("createdDate", createdDate);
        }
        if(infoMap !=null && infoMap.containsKey("payDate") && infoMap.get("payDate") !=null){
            //格式化日期
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String payDate = sdf.format(infoMap.get("payDate"));
            m.put("payDate", payDate);
        }
        if(infoMap !=null && infoMap.containsKey("payType") && infoMap.get("payType") !=null){
            String payType = "";
            if(infoMap.get("payType").equals("wx")){
                payType ="微信";
            }
            if(infoMap.get("payType").equals("dzk")){
                payType ="电子卡";
            }
            m.put("payType", payType);
        }
        if(infoMap !=null && infoMap.containsKey("mobilePhone") && infoMap.get("mobilePhone") !=null){
            String phone =infoMap.get("mobilePhone")+"";
            //手机号中间四位****代替
            phone = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
            m.put("mobilePhone", phone);
        }
        if(infoMap !=null && infoMap.containsKey("orderLiters") && infoMap.get("orderLiters") !=null){
            m.put("orderLiters", infoMap.get("orderLiters").toString());
        }
        if(infoMap !=null && infoMap.containsKey("stationName") && infoMap.get("stationName") !=null){
            m.put("stationName", infoMap.get("stationName").toString());
        }
        if(infoMap !=null && infoMap.containsKey("oilPirce") && infoMap.get("oilPirce") !=null){
            m.put("oilPirce", infoMap.get("oilPirce").toString());
        }
        if(infoMap !=null && infoMap.containsKey("stationId") && infoMap.get("stationId") !=null){
            m.put("stationId", infoMap.get("stationId").toString());
        }
//        if(infoMap !=null && infoMap.containsKey("orderType") && infoMap.get("orderType") !=null){
//            m.put("orderType", infoMap.get("orderType").toString());
//        }
        if(infoMap !=null && infoMap.containsKey("oilType") && infoMap.get("oilType") !=null){
            if(infoMap.get("oilType").equals("3")){
                m.put("orderType", "noOil");
            }else {
                m.put("orderType", "oil");
            }
        }
        logger.info("要推送的订单的信息：" +m.toString());
        //定义推送格式
        Map<String, Object> params = new HashMap<>();
        params.put("messageTitle", "pos");
        params.put("messageType", "sys");
        //获取油枪绑定的POS机信息
//        StationDeviceManager stationDeviceManager = new StationDeviceManager();
//        stationDeviceManager.setDeviceType("2");
//        stationDeviceManager.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
//        stationDeviceManager.setGunNo(infoMap.get("oilGun").toString());
//        StationDeviceManager stationDeviceManagerInfo = stationService.getStationDeviceManager(stationDeviceManager);
//      if(stationDeviceManagerInfo !=null && stationDeviceManagerInfo.getPosFanoutExchange() !=null && stationDeviceManagerInfo.getPosQueue() !=null){
        params.put("posFanoutExchange", payOrder.getPosFanoutExchange());
        params.put("posQueue", payOrder.getPosQueue());
        params.put("tusn", payOrder.getDeviceNo());
        params.put("printSetting", payOrder.getPrintSetting()); //小票打印方式
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(m);
        Map<String, Object> map = new HashMap<>();
        map.put("contentData", list);
        params.put("messageContent", map);
        logger.info("开始推送消息：" +JSONObject.toJSONString(params));
        String resultString = PosPrinterUtil.sendPosPrintDirectMessage(params);
        JSONObject jsonObject = JSONObject.parseObject(resultString);
        if(jsonObject.containsKey("code") && jsonObject.get("code").toString().equals("200")){
            //如果打印成功 添加小票数量
            PayOrder p = new PayOrder();
            p.setPrintCount(1);
            p.setOrderNo(infoMap.get("orderNo").toString());
            payOrderService.getUpdatePayOrder(p);
        }
        //}

    }

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

        if(StringUtils.isNotBlank(infoMap.get("oilPersonnel").toString())){
            oilPersonnelP =infoMap.get("oilPersonnel").toString();
        }
        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("payDate") && infoMap.get("payDate") !=null ){
            //格式化日期
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            payDateP =sdf.format(infoMap.get("payDate"));
        }
        if(infoMap.containsKey("oilGun") && infoMap.get("oilGun") !=null ){
            oilGunP =infoMap.get("oilGun").toString();
        }
        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("oilType") && !infoMap.get("oilType").equals("3")) {
            //加油升数
            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("isLngFlagGroup") && infoMap.get("isLngFlagGroup") !=null && infoMap.get("isLngFlagGroup").toString().equals("1")){
                discountAmtP =infoMap.get("sellDiscountAmt")+"";
            }else {
                discountAmtP =infoMap.get("discountAmt")+"";
            }
            receiptNameP = "油品订单";
        }else {
            orderLitersP ="0.00";
            oilPirceP = "0.00";
            discountAmtP ="0.00";
            receivableAmtP=infoMap.get("amt")+"";
            receiptNameP = "非油品订单";
        }
        if(infoMap.containsKey("receivableAmt") && infoMap.get("receivableAmt") !=null ){
            receivableAmtP =infoMap.get("receivableAmt")+"";
        }

        if(infoMap.containsKey("isLngFlagGroup") && infoMap.get("isLngFlagGroup") !=null && infoMap.get("isLngFlagGroup").toString().equals("1")){
            amtP =infoMap.get("sellAmt")+"";
        }else {
            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("payType") && infoMap.get("payType") !=null ){
            if(infoMap.get("payType").equals("wx")){
                payWayP ="微信";
            }else {
                payWayP ="电子卡";
            }

        }

        content1 = "<CB>"+receiptNameP+"--顾客联</CB><BR>";
        content1 += "<BR>";
        content1 += "--------------------------------<BR>";
        content1 += "<BR>";
        content1 += "<BOLD><B>原价： "+receivableAmtP+" 元</B></BOLD><BR>";
        content1 += "订单号："+orderNoP+"  <BR>";
        content1 += "支付方式： "+payWayP+" <BR>";
        content1 += "下单时间："+createdDateP+" <BR>";
        content1 += "付款时间："+payDateP+" <BR>";
        content1 += "油站："+stationNameP+"  <BR>";
        content1 += "油枪："+oilGunP+"号枪<BR>";
        content1 += "加油员："+oilPersonnelP+"<BR>";
        if(infoMap.containsKey("oilType") && !infoMap.get("oilType").toString().equals("3")){
            content1 += "油品： "+oilNameP+"  <BR>";
            content1 += "油量： "+orderLitersP+"  升<BR>";
            content1 += "单价： "+oilPirceP+" L/元<BR>";
        }
        if(infoMap.containsKey("oilType") && !infoMap.get("oilType").toString().equals("3")){
            content1 += "优惠： "+discountAmtP+" 元<BR>";
        }
        content1 += "支付： "+amtP+" 元<BR>";
        content1 += "手机号： "+mobilePhoneP+" <BR>";
        content1 += "加油员："+oilPersonnelP+"<BR>";
        content1 += "<BR>";
        //content1 += "--------------------------------<BR>";
        //content1 += "<BR>";

        content2 = "<CB>"+receiptNameP+"--商户联</CB><BR>";
        content2 += "<BR>";
        content2 += "--------------------------------<BR>";
        content2 += "<BR>";
        content2 += "<BOLD><B>原价： "+receivableAmtP+" 元</B></BOLD><BR>";
        content2 += "订单号："+orderNoP+"  <BR>";
        content2 += "支付方式： "+payWayP+" <BR>";
        content2 += "下单时间："+createdDateP+" <BR>";
        content2 += "付款时间："+payDateP+" <BR>";
        content2 += "油站："+stationNameP+"  <BR>";
        content2 += "油枪："+oilGunP+"号枪<BR>";
        if(infoMap.containsKey("oilType") && !infoMap.get("oilType").toString().equals("3")){
            content2 += "油品： "+oilNameP+" <BR>";
            content2 += "油量： "+orderLitersP+" 升<BR>";
            content2 += "单价： "+oilPirceP+" L/元<BR>";
        }
        if(infoMap.containsKey("oilType") && !infoMap.get("oilType").toString().equals("3")){
            content2 += "优惠： "+discountAmtP+" 元<BR>";
        }
        content2 += "支付： "+amtP+" 元<BR>";
        content2 += "手机号： "+mobilePhoneP+" <BR>";
        content2 += "加油员："+oilPersonnelP+"<BR>";
        content2 += "<BR>";
        //获取打印机编号
        //sn = "921611605";     //测试打印机 sn：921611605 key：72338zma

        sn = infoMap.get("sn").toString();
        //开始打印
        String printInfo="";    //打印信息
        if(infoMap.containsKey("printSetting") && infoMap.get("printSetting").toString()!= null && infoMap.get("printSetting").toString()!=""){
            switch (infoMap.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);
        }
    }

    //计算积分
    public CalculateIntegral calculateIntegral(CalculateIntegral calculateIntegral){
        int integral =0;
        IntegralRule integralRule = new IntegralRule();
        integralRule.setStationId(calculateIntegral.getStationId());
        //获取油站的积分规则是否共享
        String integralRuleFlag = calculateIntegral.getIntegralRuleFlag();
        if(StringUtils.isNotBlank(integralRuleFlag) && integralRuleFlag.equals("1")){
            //如果共享则先根据集团ID查询集团规则
            integralRule.setStationId(calculateIntegral.getGroupId());
        }
        integralRule.setOilName(calculateIntegral.getOilName());
        //获取该油站的积分规则
        List<IntegralRule> integralRuleList = integralRuleService.getIntegralRule(integralRule);
        if(integralRuleList !=null && integralRuleList.size() >0){
            logger.info("该油站积分规则信息：" + integralRuleList.toString());
            Date emptyDate = integralRuleList.get(0).getEmptyDate();
            //积分规则有效时间 为null时 表示永久有效
            if(emptyDate ==null || emptyDate.compareTo(new Date()) == 1 || emptyDate.compareTo(new Date()) == 0){
                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(!StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && !StringUtils.isNotBlank(integralRuleDetail.getGread())){
                            //等级和规则类型null为时表示非油品, 没有按照实收，应收，加油升数
                            if (calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==1 || calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_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 (StringUtils.isNotBlank(integralRuleDetail.getGread()) && integralRuleDetail.getRuleType().equals("1")){  //按照实收金额
                            if(calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                if(integralRuleDetail.getGread().equals("0")){      //等级为0时，表示所有人
                                    divide = calculateIntegral.getAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_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.getGread().equals(calculateIntegral.getCustomerGrade())){       //如果等级相同
                                    divide = calculateIntegral.getAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_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(StringUtils.isNotBlank(integralRuleDetail.getGread()) && integralRuleDetail.getRuleType().equals("2")){    //按应收金额
                            if(calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==1 || calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                if(integralRuleDetail.getGread().equals("0")){
                                    divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_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.getGread().equals(calculateIntegral.getCustomerGrade())){
                                    divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_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(integralRuleDetail.getGread().equals("0")){
                                    divide = calculateIntegral.getOilLiters().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_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.getGread().equals(calculateIntegral.getCustomerGrade())){
                                    divide = calculateIntegral.getOilLiters().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_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);
        }
        return calculateIntegral;
    }

    //插入用户积分信息或者更新用户积分信息
    public CustomerPoints insertUserIntegral(CalculateIntegral calculateIntegral){
        CustomerPoints customerPoints = new CustomerPoints();
        customerPoints.setRecentlyPoints(calculateIntegral.getIntegral());  //用户当前所获得的积分
        customerPoints.setStationId(calculateIntegral.getStationId());  //油站ID
        if(StringUtils.isNotBlank(calculateIntegral.getIntegralRuleFlag()) && calculateIntegral.getIntegralRuleFlag().equals("1")){
            customerPoints.setStationId(calculateIntegral.getGroupId());
        }
        customerPoints.setMinaOpenId(calculateIntegral.getOpenId());    //用户小程序ID
        customerPoints.setCustomerName(calculateIntegral.getNickName());
        if(calculateIntegral.getBlogOpenid() !=null){
            customerPoints.setBlogOpenId(calculateIntegral.getBlogOpenid());
        }
        customerPoints.setUnionId(calculateIntegral.getUnionId());      //用户unionId
        //获取客户积分信息
        CustomerPoints customerPointsInfo = customerPointsService.getCustomerPointsInfoByUnionId(customerPoints);
        if(customerPointsInfo !=null){
            logger.info("当前存在客户："+ customerPointsInfo.getMinaOpenId());
            logger.info("当前客户原有剩余积分："+ customerPointsInfo.getPoints().toString());
            CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
            customerPointsRecord.setCreateTime(new Date());
            customerPointsRecord.setCustomerName(calculateIntegral.getNickName());
            customerPointsRecord.setStationName(calculateIntegral.getStationName());
            customerPointsRecord.setStationId(calculateIntegral.getStationId());
            customerPointsRecord.setRecordType("+");
            customerPointsRecord.setUnionId(customerPointsInfo.getUnionId());
            customerPointsRecord.setIntegral(calculateIntegral.getIntegral());
            customerPointsRecord.setOrderNo(calculateIntegral.getOrderNo());
            //插入客户记录表
            customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);

            //如果已存在客户则 客户余额积分= 当前客户已有积分 + 本次所得积分
            BigDecimal surplusIntegral =new BigDecimal(customerPointsInfo.getPoints()).add(new BigDecimal(calculateIntegral.getIntegral()));
            customerPoints.setPoints(surplusIntegral.intValue());
            logger.info("本次加油后客户应有总积分："+ customerPoints.getPoints().toString());
            //用户已累积积分
            BigDecimal add = new BigDecimal(customerPointsInfo.getAccumulatePoints()).add(new BigDecimal(calculateIntegral.getIntegral()));
            customerPoints.setAccumulatePoints(add.intValue());
            customerPoints.setRecentConsumptionDate(new Date());
            //更新客户积分
            customerPointsService.updateCustomerPointsInfo(customerPoints);
            logger.info("更新客户积分信息成功！");
        }else {
            logger.info("当前系统不存在该客户积分信息");
            CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
            customerPointsRecord.setCreateTime(new Date());
            customerPointsRecord.setCustomerName(calculateIntegral.getNickName());
            customerPointsRecord.setStationName(calculateIntegral.getStationName());
            customerPointsRecord.setStationId(calculateIntegral.getStationId());
            customerPointsRecord.setRecordType("+");
            customerPointsRecord.setUnionId(calculateIntegral.getUnionId());
            customerPointsRecord.setIntegral(calculateIntegral.getIntegral());
            customerPointsRecord.setOrderNo(calculateIntegral.getOrderNo());
            customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);

            customerPoints.setUnionId(calculateIntegral.getUnionId());
            customerPoints.setPoints(calculateIntegral.getIntegral());
            customerPoints.setConsumptionPoints(0);
            customerPoints.setMobilePhone(calculateIntegral.getMobilePhone());
            customerPoints.setCustomerName(calculateIntegral.getNickName());
            customerPoints.setStationName(calculateIntegral.getStationName());
            customerPoints.setAccumulatePoints(calculateIntegral.getIntegral());
            customerPoints.setInvalidPoints(0);
            customerPoints.setRecentConsumptionDate(new Date());
            customerPoints.setCreateTime(new Date());
            //新增客户积分
            customerPointsService.insertCustomerPointsInfo(customerPoints);
            logger.info("新增客户积分信息成功！");
        }
        return customerPoints;
    }

    //公众号推送积分
    public void pushIntegral(CustomerPoints customerPoints, CalculateIntegral calculateIntegral){
        String gzhAppId ="";
        String gzhAppSecret ="";
        String stationName = "";        //油站名称
        logger.info("客户小程序openId：" + customerPoints.getMinaOpenId());
        logger.info("客户公众号openId：" + calculateIntegral.getBlogOpenid());
        logger.info("客户所加油的油站ID：" + calculateIntegral.getStationId());
        if(calculateIntegral.getStationId() !=null){
            Map<String, String> m = stationService.getStationAppIdAndAppSecret(calculateIntegral.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");
            }
            //String blogOpenId = customerPoints.getBlogOpenId();     //公众号openId
            if(calculateIntegral.getBlogOpenid() !=null){
                //推送模板
                List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
                wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+calculateIntegral.getNickName()+"，您好：\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(customerPoints.getRecentlyPoints())));
                wxMpTemplate.add(new WxMpTemplateData("From", stationName));
                wxMpTemplate.add(new WxMpTemplateData("remark",
                        "截止至" + new SimpleDateFormat(" yyyy年MM月dd日HH时mm分").format(new Date())+"，您在"+stationName+"的可用积分为 "+customerPoints.getPoints().toString()+" 分"));
                GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
                gzhNewsTemplate.setStationId(calculateIntegral.getStationId());
                gzhNewsTemplate.setTemplateType("1");
                GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(gzhNewsTemplate);
                if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                    wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), calculateIntegral.getBlogOpenid(), wxMpTemplate);
                }
            }

        }
    }


    @RequestMapping(value = "/posPrintReceiptCeshi", consumes = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public String posPrintReceiptCeshi(@RequestBody PayOrder payOrder){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        Map<String, Object> infoMap = payOrderService.getOrderInfoAndUserInfoByOrderNo(payOrder);
        Map<String, Object> m = new HashMap<>();

        if(payOrder.getTransactionId() !=null){
            m.put("transactionId", payOrder.getTransactionId());
        }
        if(payOrder.getIntegral() !=null){
            m.put("integral", payOrder.getIntegral());
        }
        if(infoMap !=null && infoMap.containsKey("orderNo") && infoMap.get("orderNo") !=null){
            m.put("orderNo", infoMap.get("orderNo").toString());
        }
        if(infoMap !=null && infoMap.containsKey("amt") && infoMap.get("amt") !=null){
            m.put("amt", infoMap.get("amt").toString());
        }
        if(infoMap !=null && infoMap.containsKey("receivableAmt") && infoMap.get("receivableAmt") !=null){
            m.put("receivableAmt", infoMap.get("receivableAmt").toString());
        }
        if(infoMap !=null && infoMap.containsKey("discountAmt") && infoMap.get("discountAmt") !=null){
            m.put("discountAmt", infoMap.get("discountAmt").toString());
        }
        if(infoMap !=null && infoMap.containsKey("oilName") && infoMap.get("oilName") !=null){
            m.put("oilName", infoMap.get("oilName").toString());
        }
        if(infoMap !=null && infoMap.containsKey("oilGun") && infoMap.get("oilGun") !=null){
            m.put("oilGun", infoMap.get("oilGun").toString());
        }
        if(infoMap !=null && infoMap.containsKey("createdDate") && infoMap.get("createdDate") !=null){
            //格式化日期
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createdDate = sdf.format(infoMap.get("createdDate"));
            m.put("createdDate", createdDate);
        }
        if(infoMap !=null && infoMap.containsKey("payDate") && infoMap.get("payDate") !=null){
            //格式化日期
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String payDate = sdf.format(infoMap.get("payDate"));
            m.put("payDate", payDate);
        }
        if(infoMap !=null && infoMap.containsKey("payType") && infoMap.get("payType") !=null){
            String payType = "";
            if(infoMap.get("payType").equals("wx")){
                payType ="微信";
            }
            if(infoMap.get("payType").equals("dzk")){
                payType ="电子卡";
            }
            m.put("payType", payType);
        }
        if(infoMap !=null && infoMap.containsKey("mobilePhone") && infoMap.get("mobilePhone") !=null){
            String phone =infoMap.get("mobilePhone")+"";
            //手机号中间四位****代替
            phone = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
            m.put("mobilePhone", phone);
        }
        if(infoMap !=null && infoMap.containsKey("orderLiters") && infoMap.get("orderLiters") !=null){
            m.put("orderLiters", infoMap.get("orderLiters").toString());
        }
        if(infoMap !=null && infoMap.containsKey("stationName") && infoMap.get("stationName") !=null){
            m.put("stationName", infoMap.get("stationName").toString());
        }
        if(infoMap !=null && infoMap.containsKey("oilPirce") && infoMap.get("oilPirce") !=null){
            m.put("oilPirce", infoMap.get("oilPirce").toString());
        }
        if(infoMap !=null && infoMap.containsKey("stationId") && infoMap.get("stationId") !=null){
            m.put("stationId", infoMap.get("stationId").toString());
        }
//        if(infoMap !=null && infoMap.containsKey("orderType") && infoMap.get("orderType") !=null){
//            m.put("orderType", infoMap.get("orderType").toString());
//        }
        if(infoMap !=null && infoMap.containsKey("oilType") && infoMap.get("oilType") !=null){
            if(infoMap.get("oilType").equals("3")){
                m.put("orderType", "noOil");
            }else {
                m.put("orderType", "oil");
            }
        }
        logger.info("要推送的订单的信息：" +m.toString());
        //定义推送格式
        Map<String, Object> params = new HashMap<>();
        params.put("messageTitle", "pos");
        params.put("messageType", "sys");
        //获取油枪绑定的POS机信息
        StationDeviceManager stationDeviceManager = new StationDeviceManager();
        stationDeviceManager.setDeviceType("2");
        stationDeviceManager.setStationId(Integer.valueOf(infoMap.get("stationId").toString()));
        stationDeviceManager.setGunNo(infoMap.get("oilGun").toString());
        StationDeviceManager stationDeviceManagerInfo = stationService.getStationDeviceManager(stationDeviceManager);
        if(stationDeviceManagerInfo !=null && stationDeviceManagerInfo.getPosFanoutExchange() !=null && stationDeviceManagerInfo.getPosQueue() !=null){
            params.put("posFanoutExchange", stationDeviceManagerInfo.getPosFanoutExchange());
            params.put("posQueue", stationDeviceManagerInfo.getPosQueue());
            params.put("tusn", stationDeviceManagerInfo.getDeviceNo());
            params.put("printSetting", payOrder.getPrintSetting()); //小票打印方式
            List<Map<String, Object>> list = new ArrayList<>();
            list.add(m);
            Map<String, Object> map = new HashMap<>();
            map.put("contentData", list);
            params.put("messageContent", map);
            logger.info("开始推送消息：" +JSONObject.toJSONString(params));
            String resultString = PosPrinterUtil.sendPosPrintDirectMessage(params);
            JSONObject jsonObject = JSONObject.parseObject(resultString);
            if(jsonObject.containsKey("code") && jsonObject.get("code").toString().equals("200")){
                //如果打印成功 添加小票数量
                PayOrder p = new PayOrder();
                p.setPrintCount(1);
                p.setOrderNo(infoMap.get("orderNo").toString());
                payOrderService.getUpdatePayOrder(p);
            }
        }
        return  gson.toJson(resultData);
    }

}
