package com.nmgs.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nmgs.entity.Consistant;
import com.nmgs.mapper.Mapper;
import com.nmgs.service.UserTableService;
import com.nmgs.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
@Transactional
public class QCodeInfoServiceImpl {
    SimpleDateFormat df=new SimpleDateFormat("yyyyMMdd");
    @Autowired
    public Mapper mapperI;
    private static String  DBType= PropertiesUtil.getValue("DBType");
    public UserTableService userTableService;
    @Autowired
    public void setUserTableService(UserTableService userTableService) {
        this.userTableService = userTableService;
    }

    public  IntegralStarSetupServiceImpl integralStarSetupServiceImpl;
    @Autowired
    public void setIntegralStarSetupServiceImpl(IntegralStarSetupServiceImpl integralStarSetupServiceImplT) {
        this.integralStarSetupServiceImpl = integralStarSetupServiceImplT;
    }


    public MessagePushServiceImpl messagePushServiceImpl;
    @Autowired
    public void setMessagePushServiceImpl(MessagePushServiceImpl messagePushServiceImpl) {
        this.messagePushServiceImpl = messagePushServiceImpl;
    }

    /**
     *利用redis做缓存
     * @param openId 用户微信iD
     * @param integrateType 积分类型
     * @param rebateIntegrate 兑换积分
     * @return
     */
    public String getQcodeInfoByUserIdRedis(String openId,  String integrateType, String rebateIntegrate){
        JSONObject jo=new JSONObject();
        jo.put("openId",openId);
        jo.put("integrateType",integrateType);
        jo.put("rebateIntegrate",rebateIntegrate);
        jo.put("createTime",PubTools.getCurrentDate());//二维码生成时间，20s之后过期

        //判断用户是否被冻结

        List userStarByOepnIdTemp = this.userTableService.getUserByOpenId(openId);

        if(userStarByOepnIdTemp.size()<1){
            return  "-2";
        }else {
            Object obj = userStarByOepnIdTemp.get(0);
            Map<String, Object> obj1 = (Map<String, Object>) obj;

            String certification = obj1.get("CERTIFICATION").toString();//认证状态
            if ("5".equals(certification)) {
                return "-3";
            }
        }

        //生成一个二维码流水号
        //xxxx xxxx（8位时间戳16进制） |xxxx(4位流水序号16进制)|xxxx（4位兑换积分16进制）|xxxx（4位校验码，16进制）"}
        String content="";
        String dateTimes=df.format(new Date());
        String serialsT="";
        String rebateIntegrateT=rebateIntegrate;
        Random random = new Random();
        int res = 1000+random.nextInt(9000);
        int serials = Consistant.serials+1;
        Consistant.serials=serials;
        if(serials<10){
            serialsT="000"+serials;
        }else if(serials >=10 && serials<100){
            serialsT="00"+serials;
            Consistant.serials=serials;
        }else if(serials >=10 && serials<100){
            serialsT="00"+serials;
        }else if(serials >=100 && serials<1000){
            serialsT="0"+serials;
        }else if(serials >=1000 && serials<10000){
            serialsT=""+serials;
        }else{
            serialsT="1000";
            Consistant.serials=999;
        }
        Long seconds = (new Date()).getTime()/1000;
        String dataStr=Long.toHexString(seconds);
        String serialsTStr=Integer.toHexString(Integer.parseInt(serialsT));
        if(serialsTStr.length()<4){
          int diff=  4 - serialsTStr.length()  ;
          if(diff==3){
              serialsTStr="000"+serialsTStr;
          }else  if(diff==2){
              serialsTStr="00"+serialsTStr;
          }else  if(diff==1){
              serialsTStr="0"+serialsTStr;
          }
        }
        String rebateIntegrateTStr=Integer.toHexString(Integer.parseInt(rebateIntegrateT));
        if(rebateIntegrateTStr.length()<4){
            int diff=  4 - rebateIntegrateTStr.length()  ;
            if(diff==3){
                rebateIntegrateTStr="000"+rebateIntegrateTStr;
            }else  if(diff==2){
                rebateIntegrateTStr="00"+rebateIntegrateTStr;
            }else  if(diff==1){
                rebateIntegrateTStr="0"+rebateIntegrateTStr;
            }
        }
        String resStr=Integer.toHexString(res);
        if(resStr.length()<4){
            int diff=  4 - resStr.length()  ;
            if(diff==3){
                resStr="000"+resStr;
            }else  if(diff==2){
                resStr="00"+resStr;
            }else  if(diff==1){
                resStr="0"+resStr;
            }
        }
        content=  dataStr+"|" +serialsTStr+"|"+ rebateIntegrateTStr +"|"+resStr;
      //  content=  dateTimes+"|" +serialsT +"|"+rebateIntegrateT+"|"+res;
        LogUtil.WriteLog_Info("用户："+openId+"---->核销积分"+integrateType+"生成的流水号======"+content,"QCodeInfoServiceImpl");
       // Consistant.map.put(content,jo);
        Long l = redisConfigUtil.setIntegral(content, jo.toJSONString());
        if(l<0){
           return "5";
        }
        return content;
    }

    /**
     *
     * @param openId 用户微信iD
     * @param integrateType 积分类型
     * @param rebateIntegrate 兑换积分
     * @return
     */
    public String getQcodeInfoByUserId(String openId,  String integrateType, String rebateIntegrate){
        JSONObject jo=new JSONObject();
        jo.put("openId",openId);
        jo.put("integrateType",integrateType);
        jo.put("rebateIntegrate",rebateIntegrate);
        jo.put("createTime",PubTools.getCurrentDate());//二维码生成时间，20s之后过期

        //判断用户是否被冻结

        List userStarByOepnIdTemp = this.userTableService.getUserByOpenId(openId);

        if(userStarByOepnIdTemp.size()<1){
            return  "-2";
        }else {
            Object obj = userStarByOepnIdTemp.get(0);
            Map<String, Object> obj1 = (Map<String, Object>) obj;

            String certification = obj1.get("CERTIFICATION").toString();//认证状态
            if ("5".equals(certification)) {
                return "-3";
            }
        }

        //生成一个二维码流水号
        //xxxx xxxx（8位时间戳16进制） |xxxx(4位流水序号16进制)|xxxx（4位兑换积分16进制）|xxxx（4位校验码，16进制）"}
        String content="";
        String dateTimes=df.format(new Date());
        String serialsT="";
        String rebateIntegrateT=rebateIntegrate;
        Random random = new Random();
        int res = 1000+random.nextInt(9000);
        int serials = Consistant.serials+1;
        Consistant.serials=serials;
        if(serials<10){
            serialsT="000"+serials;
        }else if(serials >=10 && serials<100){
            serialsT="00"+serials;
            Consistant.serials=serials;
        }else if(serials >=10 && serials<100){
            serialsT="00"+serials;
        }else if(serials >=100 && serials<1000){
            serialsT="0"+serials;
        }else if(serials >=1000 && serials<10000){
            serialsT=""+serials;
        }else{
            serialsT="1000";
            Consistant.serials=999;
        }
        Long seconds = (new Date()).getTime()/1000;
        String dataStr=Long.toHexString(seconds);
        String serialsTStr=Integer.toHexString(Integer.parseInt(serialsT));
        if(serialsTStr.length()<4){
            int diff=  4 - serialsTStr.length()  ;
            if(diff==3){
                serialsTStr="000"+serialsTStr;
            }else  if(diff==2){
                serialsTStr="00"+serialsTStr;
            }else  if(diff==1){
                serialsTStr="0"+serialsTStr;
            }
        }
        String rebateIntegrateTStr=Integer.toHexString(Integer.parseInt(rebateIntegrateT));
        if(rebateIntegrateTStr.length()<4){
            int diff=  4 - rebateIntegrateTStr.length()  ;
            if(diff==3){
                rebateIntegrateTStr="000"+rebateIntegrateTStr;
            }else  if(diff==2){
                rebateIntegrateTStr="00"+rebateIntegrateTStr;
            }else  if(diff==1){
                rebateIntegrateTStr="0"+rebateIntegrateTStr;
            }
        }
        String resStr=Integer.toHexString(res);
        if(resStr.length()<4){
            int diff=  4 - resStr.length()  ;
            if(diff==3){
                resStr="000"+resStr;
            }else  if(diff==2){
                resStr="00"+resStr;
            }else  if(diff==1){
                resStr="0"+resStr;
            }
        }
        content=  dataStr+"|" +serialsTStr+"|"+ rebateIntegrateTStr +"|"+resStr;
        //  content=  dateTimes+"|" +serialsT +"|"+rebateIntegrateT+"|"+res;
        LogUtil.WriteLog_Info("用户："+openId+"---->核销积分"+integrateType+"生成的流水号======"+content,"QCodeInfoServiceImpl");
         Consistant.map.put(content,jo);
        return content;
    }

    /**
     * @param content 二维码内容
     * @return
     */
    public String removeContent(String content){
        Object content1 = Consistant.map.get(content);
        if(!PubTools.isEmpty(content1)){
            Consistant.map.remove(content);
        }

        Long l = redisConfigUtil.delIntegral(content);
        if(l<0){
            LogUtil.WriteLog_Error("removeContent 删除缓存中key失败，redis 连接失败了","QCodeInfoServiceImpl");
        }
        return "1";
    }

    /**
     *
     * @param content 二维码流水号
     * @param serverOperationId 商超用户ID
     * @param payMoney 实际支付金额
     * @return
     */
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})
    public JSONObject solveQcode(String content, String serverOperationId,String orderId, Double payMoney,Double discountMoneyBefore,Double discountMoney) throws Exception {
        String ret="-2";// -1 代表接口处理失败 1 处理成功  2 用户不存在 3 兑换积分大于用户可用积分 4 二维码信息过期 5 商户不存在 6 积分类型与消费方式不匹配 7 商户角色未设置 8 用户已冻结 9 折扣金额与消费积分不一致 10 请重新生成二维码 11  订单中商户与核销中的商户不匹配  12 订单已核销
       JSONObject retJo=new JSONObject();
       String openId="";
        try{
           LogUtil.WriteLog_Info("积分核减操作开始====="+PubTools.getCurrentDate()+"=======params==={content:"+content+",serverOperationId:"+serverOperationId+",discountMoney:"+discountMoney+"}","QCodeInfoServiceImpl");
           //查询金额与积分的兑换比例，一元兑换积分
           String sqlTemp="select t.VALUE/100 AS VALUE ,t.EVERYMONEY/100 AS EVERYMONEY from PAY_INTEGRATION_NUMBER_TABLE t where t.TYPE='@TYPE@'";
           String rollbackTime=PubTools.getCurrentDate();
           Object content1 = Consistant.map.get(content);
            if(content1 != null){
               JSONObject joMap=(JSONObject)content1;
                openId= PubTools.isEmpty(joMap.get("openId"))?"":joMap.get("openId").toString();
               String integrateTypeParam= PubTools.isEmpty(joMap.get("integrateType"))?"":joMap.get("integrateType").toString();
               String rebateIntegrate= PubTools.isEmpty(joMap.get("rebateIntegrate"))?"":joMap.get("rebateIntegrate").toString();
               String createTime= PubTools.isEmpty(joMap.get("createTime"))?"":joMap.get("createTime").toString();
               Long s = PubTools.dateDiff(createTime, rollbackTime, "S");
               LogUtil.WriteLog_Info("二维码生成时间长度====="+s,"QCodeInfoServiceImpl");
               retJo.put("openId",openId);

               String integrateType="";
               String consumeIntegral="";
               String enabledIntegral="";
               int userIdNew=0;
               //校验用户状态
               List userByOpenId = userTableService.getUserByOpenId(openId);
               Object obj = userByOpenId.get(0);
               Map<String, Object> obj1 = (Map<String, Object>) obj;
               String certification = obj1.get("CERTIFICATION").toString();//认证状态
               if(userByOpenId.size()<1){
                   Object contentNew = Consistant.map.get(content);
                   if(!PubTools.isEmpty(contentNew)){
                       Consistant.map.remove(content);
                   }
                   ret="2";
                   retJo.put("ret",ret);
                   return  retJo;
               }
               if ("5".equals(certification)) {
                   ret = "8";
                   retJo.put("ret", ret);
                   Object contentNew = Consistant.map.get(content);
                   if(!PubTools.isEmpty(contentNew)){
                       Consistant.map.remove(content);
                   }
                   return retJo;
               }

               //先查询商户角色
               String serviceRole = "";
               String inputMoney = "";//是否需要商户端输入金额
               String serivceOperatorRole = "SELECT saot.ID,saot.USERNAME,saot.ROLEID,saot.SERVICEAREAID,saoc.INPUTMENEY FROM SERVICE_AREA_OPERATORS_TABLE saot,SERVICE_AREA_OPERATORS_COMPANY_TEXT saoc  " +
                       " WHERE saoc.ID = saot.COMPANYID AND saot.JOBNUMBER='" + serverOperationId + "'";
               List serviceOperatorList = this.mapperI.selectforlist(serivceOperatorRole);
               if (serviceOperatorList.size() < 1) {//商户不存在
                   ret = "5";
                   retJo.put("ret", ret);
                   return retJo;
               }
               boolean isCheckDiscountMoney=false;
               if(userByOpenId.size()>0){
                   //String startLevel= obj1.get("STARLEVEL").toString();//星级
                   String ENABLEINTEGRATION = obj1.get("ENABLEINTEGRATION").toString();//用户可用公共积分
                   String OILENABLEINTEGRATION = obj1.get("OILENABLEINTEGRATION").toString();//加油可用积分
                   String GASENABLEINTEGRATION = obj1.get("GASENABLEINTEGRATION").toString();//加气可用积分
                   String SPENABLEINTEGRATION = obj1.get("SPENABLEINTEGRATION").toString();//消费可用积分
                   String CAFENABLEINTEGRATION = obj1.get("CAFENABLEINTEGRATION").toString();//餐饮可用积分
                   String OGENABLEINTEGRATION = obj1.get("OGENABLEINTEGRATION").toString();//加油、加气可用积分
                   String CPENABLEINTEGRATION = obj1.get("CPENABLEINTEGRATION").toString();//餐饮、消费可用积分
                    userIdNew = Integer.parseInt(obj1.get("ID").toString());//人员id
                   if (s > 30) {
                       Consistant.map.remove(content);
                       ret = "4";
                       retJo.put("ret", ret);
                       return retJo;
                   }
                   //核验商户角色与积分消费类型是否匹配

                   if (serviceOperatorList.size() >0 ) {
                       //校验用户与角色出示二维码积分消费类型是否匹配
                       Map<String, Object> mapServiceOperator = (Map<String, Object>) serviceOperatorList.get(0);
                       serviceRole = mapServiceOperator.get("ROLEID").toString();
                      /* serviceAreaId = mapServiceOperator.get("SERVICEAREAID").toString();*/
                       inputMoney = mapServiceOperator.get("INPUTMENEY").toString();
                   }
                   if("1".equals(inputMoney)){
                       isCheckDiscountMoney=true;
                   }
                   //根据商户角色判断消费类型
                   if (PubTools.isNull(serviceRole)) {
                       LogUtil.WriteLog_Info("商户角色未设置", "QCodeInfoServiceImpl");
                       ret = "7";
                       retJo.put("ret", ret);
                       return retJo;
                   } else {
                       if ("3".equals(serviceRole) || "1".equals(serviceRole)) {
                           if (!"FPG".equals(integrateTypeParam)) {
                               ret = "6";
                               retJo.put("ret", ret);
                               Consistant.map.remove(content);
                               return retJo;
                           }
                       }
                       if ("2".equals(serviceRole) || "4".equals(serviceRole)) {
                           if (!"FCS".equals(integrateTypeParam) && !"FCA".equals(integrateTypeParam)) {
                               ret = "6";
                               retJo.put("ret", ret);
                               Consistant.map.remove(content);
                               return retJo;
                           }
                       }
                       //如果是餐饮预约， 则直接改了状态即可
                     /*  if("FCA".equals(integrateTypeParam)){
                           String updateAppointSql="UPDATE APPOINTMENT_INFO_TABLE SET COMPLETESTATUS='Y' WHERE ID="+rebateIntegrate;
                           this.mapperI.update(updateAppointSql);
                           LogUtil.WriteLog_Info("积分核减=====修改预约记录为已核销", "QCodeInfoServiceImpl");
                           ret = "1";
                           retJo.put("ret", ret);
                           return retJo;
                       }
*/


                       if ("1".equals(serviceRole)) {
                           integrateType = "FP";
                       } else if ("2".equals(serviceRole)) {
                           integrateType = "FC";
                       } else if ("3".equals(serviceRole)) {
                           integrateType = "FG";
                       } else if ("4".equals(serviceRole)) {
                           integrateType = "FS";
                       } else {

                       }
                   }
                   //查询用户累积获取的总积分
                   String totalAddIntegralSql = "SELECT COALESCE(MAX(ilt.TOTALADDINTEGRATION),0)  AS TOTALADDINTEGRATION FROM INTEGRATION_LIST_TABLE ilt,WEIXN_USER_TABLE ut WHERE ilt.USERID = ut.ID AND ut.OPENID='" + openId + "'";
                   double totalAddIntegral = 0.0;
                   double rebateIntegrateSave = 0.0;
                   switch (integrateType) {
                       case "FP"://加油
                           retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(OGENABLEINTEGRATION)));
                           String sqlFp = sqlTemp.replace("@TYPE@", integrateType);
                           List selectforlist = this.mapperI.selectforlist(sqlFp);
                           //判断兑换积分是否够本次折扣
                           int rebateIn = 1;
                           if (selectforlist.size() > 0) {
                               Map<String, Object> o = (Map<String, Object>) selectforlist.get(0);
                               BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(o.get("VALUE").toString()));
                               bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                               rebateIn=bd.intValue();
                           }
                           //根据折扣金额计算积分
                           Double rebateIntegrateI = Double.parseDouble(rebateIntegrate);
                           Double rebateIntegrateIZK=PubTools.doubleSave1(discountMoney*rebateIn);
                           //double enabledIntegFc=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(CAFENABLEINTEGRATION);
                           if(isCheckDiscountMoney){
                               if((rebateIntegrateIZK  -  rebateIntegrateI) != 0){
                                   ret = "9";
                                   retJo.put("PAYINTEGRAL", rebateIntegrateI);
                                   retJo.put("discountMoney", rebateIntegrateIZK);
                                   retJo.put("ret", ret);
                                   return retJo;
                               }
                           }
                           //double enabledInteg=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(OILENABLEINTEGRATION);
                           double enabledInteg = Double.parseDouble(OGENABLEINTEGRATION);
                           if (rebateIntegrateI > enabledInteg) {
                               ret = "3";
                               retJo.put("PAYINTEGRAL", rebateIntegrateI);
                               retJo.put("ret", ret);
                               return retJo;
                           } else {
                               rebateIntegrateSave=rebateIntegrateI;
                               retJo.put("PAYINTEGRAL", rebateIntegrateI);
                           }
                           break;
                       case "FG"://加气
                           retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(OGENABLEINTEGRATION)));
                           String sqlFg = sqlTemp.replace("@TYPE@", integrateType);
                           List selectforlistFg = this.mapperI.selectforlist(sqlFg);
                           //判断兑换积分是否够本次折扣
                           int rebateInFg = 1;
                           if (selectforlistFg.size() > 0) {
                               Map<String, Object> o = (Map<String, Object>) selectforlistFg.get(0);
                               BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(o.get("VALUE").toString()));
                               bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                               rebateInFg=bd.intValue();
                           }
                           //根据折扣金额计算积分
                           //  int rebateIntegrateI=Integer.parseInt(rebateIntegrate);
                           Double rebateIntegrateIFgZk=PubTools.doubleSave1(discountMoney*rebateInFg);
                           Double rebateIntegrateIFg = Double.parseDouble(rebateIntegrate);
                           // double enabledIntegFg=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(GASENABLEINTEGRATION);

                           //折扣金额与输入的积分是否一致
                           if(isCheckDiscountMoney) {
                               if ((rebateIntegrateIFgZk - rebateIntegrateIFg) != 0) {
                                   ret = "9";
                                   retJo.put("PAYINTEGRAL", rebateIntegrateIFg);
                                   retJo.put("discountMoney", rebateIntegrateIFgZk);
                                   retJo.put("ret", ret);
                                   return retJo;
                               }
                           }
                           double enabledIntegFg = Double.parseDouble(OGENABLEINTEGRATION);
                           if (rebateIntegrateIFg > enabledIntegFg) {
                               ret = "3";
                               retJo.put("PAYINTEGRAL", rebateIntegrateIFg);
                               retJo.put("ret", ret);
                               return retJo;
                           } else {
                               rebateIntegrateSave=rebateIntegrateIFg;
                               retJo.put("PAYINTEGRAL", rebateIntegrateIFg);
                           }
                           break;
                       case "FC"://餐饮
                           retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(CPENABLEINTEGRATION)));
                           String sqlFc = sqlTemp.replace("@TYPE@", integrateType);
                           List selectforlistFc = this.mapperI.selectforlist(sqlFc);
                           //判断兑换积分是否够本次折扣
                           int rebateInFc = 1;
                           if (selectforlistFc.size() > 0) {
                               Map<String, Object> o = (Map<String, Object>) selectforlistFc.get(0);
                               BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(o.get("VALUE").toString()));
                               bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                               rebateInFc=bd.intValue();
                           }
                           //根据折扣金额计算积分
                           Double rebateIntegrateIFcZK=discountMoney*rebateInFc;
                           Double rebateIntegrateIFc = Double.parseDouble(rebateIntegrate);
                           //double enabledIntegFc=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(CAFENABLEINTEGRATION);
                           if(isCheckDiscountMoney) {
                               if ((rebateIntegrateIFcZK - rebateIntegrateIFc) != 0) {
                                   ret = "9";
                                   retJo.put("PAYINTEGRAL", rebateIntegrateIFc);
                                   retJo.put("discountMoney", rebateIntegrateIFcZK);
                                   retJo.put("ret", ret);
                                   return retJo;
                               }
                           }
                           double enabledIntegFc = Double.parseDouble(CPENABLEINTEGRATION);
                           if (rebateIntegrateIFc > enabledIntegFc) {
                               ret = "3";
                               retJo.put("PAYINTEGRAL", rebateIntegrateIFc);
                               retJo.put("ret", ret);
                               return retJo;
                           } else {
                               //进行积分核减
                               rebateIntegrateSave=rebateIntegrateIFc;
                               retJo.put("PAYINTEGRAL", rebateIntegrateIFc);
                           }
                           break;
                       case "FS"://消费
                           retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(CPENABLEINTEGRATION)));
                           String sqlFs = sqlTemp.replace("@TYPE@", integrateType);
                           List selectforlistFs = this.mapperI.selectforlist(sqlFs);
                           //判断兑换积分是否够本次折扣
                           int rebateInFs = 1;
                           if (selectforlistFs.size() > 0) {
                               Map<String, Object> o = (Map<String, Object>) selectforlistFs.get(0);
                               BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(o.get("VALUE").toString()));
                               bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                               rebateInFs=bd.intValue();
                           }
                           //根据折扣金额计算积分

                           //  int rebateIntegrateI=Integer.parseInt(rebateIntegrate);
                           Double rebateIntegrateIFsZK=discountMoney*rebateInFs;
                           Double rebateIntegrateIFs = Double.parseDouble(rebateIntegrate);
                           //double enabledIntegFs=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(SPENABLEINTEGRATION);


                           //double enabledIntegFc=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(CAFENABLEINTEGRATION);
                           if(isCheckDiscountMoney) {
                               if ((rebateIntegrateIFsZK - rebateIntegrateIFs) != 0) {
                                   ret = "9";
                                   retJo.put("PAYINTEGRAL", rebateIntegrateIFs);
                                   retJo.put("discountMoney", rebateIntegrateIFsZK);
                                   retJo.put("ret", ret);
                                   return retJo;
                               }
                           }
                           double enabledIntegFs = Double.parseDouble(CPENABLEINTEGRATION);
                           if (rebateIntegrateIFs > enabledIntegFs) {
                               ret = "3";
                               retJo.put("PAYINTEGRAL", rebateIntegrateIFs);
                               retJo.put("ret", ret);
                               return retJo;
                           } else {
                               //进行积分核减
                               rebateIntegrateSave=rebateIntegrateIFs;
                               retJo.put("PAYINTEGRAL", rebateIntegrateIFs);
                           }
                           break;
                       default:
                           break;
                   }


                   //进行积分核减
                  /* List selectforlistTotalAdd = this.mapperI.selectforlist(totalAddIntegralSql);
                   if (selectforlistTotalAdd.size() > 0) {
                       Map<String, Object> o = (Map<String, Object>) selectforlistTotalAdd.get(0);
                       totalAddIntegral = Double.parseDouble(o.get("TOTALADDINTEGRATION").toString());
                   }*/
                   //1、积分流水记录新加
                   String sqlMax = "select COALESCE(max(ID),0) AS  ID from integration_list_table";
                   List selectforlistMax = this.mapperI.selectforlist(sqlMax);
                   //判断兑换积分是否够本次折扣
                   int maxId = 1;
                   if (selectforlistMax.size() > 0) {
                       Map<String, Object> o = (Map<String, Object>) selectforlistMax.get(0);
                       maxId = Integer.parseInt(o.get("ID").toString());
                   }
                   String cafterSql = "INSERT INTO integration_list_table ( ID, USERID, LASTINTEGRATION, PAYINTEGRATION, RESTINTEGRATION, PAYTIME, PAYTYPE,OGENABLEINTEGRATION,CPENABLEINTEGRATION )\n" +
                           "VALUES\n" +
                           "\t(\n" +
                           "\t\t" + (maxId + 1) + ",\n" +
                           "\t\t"+userIdNew+",\n" +
                           "\t\t" + PubTools.doubleSave1(Double.parseDouble(ENABLEINTEGRATION) * 100) + ",\n" +
                           "\t\t" + PubTools.doubleSave1(rebateIntegrateSave * 100) + ",\n" +
                           "\t\t" + PubTools.doubleSave1(((Double.parseDouble(ENABLEINTEGRATION) - rebateIntegrateSave) * 100)) + ",\n" +
                           "\t\tto_date('" + rollbackTime + "','yyyy-MM-dd HH24:mi:ss'),\n" +
                           "\t'" + integrateType + "', \n" ;
                   if("4".equals(DBType)){
                       cafterSql = "INSERT INTO integration_list_table ( ID, USERID, LASTINTEGRATION, PAYINTEGRATION, RESTINTEGRATION, PAYTIME, PAYTYPE,OGENABLEINTEGRATION,CPENABLEINTEGRATION )\n" +
                               "VALUES\n" +
                               "\t(\n" +
                               "\t\t" + (maxId + 1) + ",\n" +
                               "\t\t"+userIdNew+",\n" +
                               "\t\t" + PubTools.doubleSave1(Double.parseDouble(ENABLEINTEGRATION) * 100) + ",\n" +
                               "\t\t" + PubTools.doubleSave1(rebateIntegrateSave * 100) + ",\n" +
                               "\t\t" + PubTools.doubleSave1(((Double.parseDouble(ENABLEINTEGRATION) - rebateIntegrateSave) * 100)) + ",\n" +
                               "\t\tstr_to_date('" + rollbackTime + "','%Y-%m-%d %H:%i:%s'),\n" +
                               "\t'" + integrateType + "', \n" ;
                   }


                   if("FP".equals(integrateType) || "FG".equals(integrateType)){
                       cafterSql +=  "\t" + PubTools.doubleSave1(((Double.parseDouble(OGENABLEINTEGRATION) - rebateIntegrateSave) * 100)) + ", \n" +
                           "\t" + PubTools.doubleSave1(Double.parseDouble(CPENABLEINTEGRATION) * 100) + " \n" ;
                   }else if("FC".equals(integrateType) || "FS".equals(integrateType)) {
                       cafterSql +="\t" + PubTools.doubleSave1(((Double.parseDouble(OGENABLEINTEGRATION)) * 100)) + ", \n" +
                            "\t" + PubTools.doubleSave1((Double.parseDouble(CPENABLEINTEGRATION) - rebateIntegrateSave) * 100)+" " ;
                   }else{

                   }
                      cafterSql+=  "\t)";
                   this.mapperI.insert(cafterSql);
                   consumeIntegral=rebateIntegrateSave+"";
                   LogUtil.WriteLog_Info("积分核减=====积分流水已插入", "QCodeInfoServiceImpl");
                   //2、新加一条消费记录
                   String sqlIntegralList = "insert into CAFTER_TABLE(ID,\n" +
                           "ACARNO,\n" +
                           "USERID,\n" +
                           "CAFTERTIME,\n" +
                           "USERJOBNUMBER,\n" +
                           "TRIMINTEGRAL," +
                           "INTEGRATIONLISTID,\n" +
                           "ORDERID,CONTENT) values (\n" +
                           "  (select COALESCE(max(t.ID),0)+1 from CAFTER_TABLE t),''," +
                           ""+userIdNew+",to_date('" + rollbackTime + "','yyyy-MM-dd HH24:mi:ss'),'" + serverOperationId + "','SUCCESS'," + (maxId + 1) + ",'" + orderId + "','" + content + "'" +
                           ")";
                   if("4".equals(DBType)){
                       sqlIntegralList = "insert into CAFTER_TABLE(ID,\n" +
                               "ACARNO,\n" +
                               "USERID,\n" +
                               "CAFTERTIME,\n" +
                               "USERJOBNUMBER,\n" +
                               "TRIMINTEGRAL," +
                               "INTEGRATIONLISTID,\n" +
                               "ORDERID,CONTENT) values (\n" +
                               "  (select COALESCE(max(t.ID),0)+1 from CAFTER_TABLE t),''," +
                               ""+userIdNew+",str_to_date('" + rollbackTime + "','%Y-%m-%d %H:%i:%s'),'" + serverOperationId + "','SUCCESS'," + (maxId + 1) + ",'" + orderId + "','" + content + "'" +
                               ")";
                   }
                   this.mapperI.insert(sqlIntegralList);
                   //进行预约核销
                   /*String appointMentSql="";
                   if("FS".equals(integrateType)){
                        appointMentSql="SELECT ID FROM APPOINTMENT_INFO_TABLE t where t.SERVICEAREAID='"+serviceAreaId+"' AND t.USERID='"+userIdNew+"' AND APPOINTMENTTIME=to_date('"+rollbackTime+"','YYYY-MM-DD') AND t.COMPLETESTATUS='N' AND t.APPOINTMENTTYPE=3 ORDER BY t.CREATETIME ";
                   }else  if("FC".equals(integrateType)){
                       appointMentSql="SELECT ID FROM APPOINTMENT_INFO_TABLE t where t.SERVICEAREAID='"+serviceAreaId+"' AND t.USERID='"+userIdNew+"' AND APPOINTMENTTIME=to_date('"+rollbackTime+"','YYYY-MM-DD') AND t.COMPLETESTATUS='N' AND t.APPOINTMENTTYPE=2 ORDER BY t.CREATETIME ";
                   }
                  if(!PubTools.isNull(appointMentSql)){
                      List appointList = this.mapperI.selectforlist(appointMentSql);
                      if(appointList.size()>0){
                          Map<String,Object> map=(Map<String,Object>)appointList.get(0);
                          int appointId=Integer.parseInt(map.get("ID").toString());
                          String updateAppointSql="UPDATE APPOINTMENT_INFO_TABLE SET COMPLETESTATUS='Y',INTEGRATIONLISTID="+(maxId + 1)+" WHERE ID="+appointId+"";
                          this.mapperI.update(updateAppointSql);
                          LogUtil.WriteLog_Info("积分核减=====修改预约记录为已核销", "QCodeInfoServiceImpl");
                      }
                  }*/
                   LogUtil.WriteLog_Info("积分核减=====消费记录已插入", "QCodeInfoServiceImpl");
                   //3、计算用户可用积分
                   String sql = "select " +
                           " ut.ID ,ut.OPENID ,COALESCE(ut.ENABLEINTEGRATION,0) AS ENABLEINTEGRATION,COALESCE(ut.CPENABLEINTEGRATION,0) AS CPENABLEINTEGRATION,COALESCE(ut.OGENABLEINTEGRATION,0) AS OGENABLEINTEGRATION" +
                           " from WEIXN_USER_TABLE ut " +
                           " where 1=1 AND ut.OPENID='" + openId + "'";
                   List selectforlist1 = this.mapperI.selectforlist(sql);
                   if (selectforlist1.size() > 0) {
                       Object objT = selectforlist1.get(0);
                       Map<String, Object> obj1T = (Map<String, Object>) objT;
                       Double enabledT = Double.parseDouble(obj1T.get("ENABLEINTEGRATION").toString());
                       BigDecimal bd = BigDecimal.valueOf(enabledT - rebateIntegrateSave * 100);
                       bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                       double enabledTI = bd.doubleValue();
                       Double enabledTCp = Double.parseDouble(obj1T.get("CPENABLEINTEGRATION").toString());
                       BigDecimal bdcp = BigDecimal.valueOf(enabledTCp - rebateIntegrateSave * 100);
                       bdcp = bdcp.setScale(1, BigDecimal.ROUND_HALF_UP);
                       double enabledTICp = bdcp.doubleValue();

                       Double enabledTPG = Double.parseDouble(obj1T.get("OGENABLEINTEGRATION").toString());
                       BigDecimal bdcpPG = BigDecimal.valueOf(enabledTPG - rebateIntegrateSave * 100);
                       BigDecimal bdcpPg = bdcpPG.setScale(1, BigDecimal.ROUND_HALF_UP);
                       double enabledTIPG = bdcpPg.doubleValue();
                       if("FP".equals(integrateType) || "FG".equals(integrateType)){
                           String sqlUpdate = "update WEIXN_USER_TABLE SET ENABLEINTEGRATION=" + enabledTI + " ,OGENABLEINTEGRATION=" + enabledTIPG + " " +
                                   " where 1=1 AND OPENID='" + openId + "'";
                           this.mapperI.update(sqlUpdate);
                           enabledIntegral=PubTools.doubleSave1(enabledTIPG / 100)+"";
                           retJo.put("ENABLEINTEGRATION",enabledIntegral);
                       }else if("FC".equals(integrateType) || "FS".equals(integrateType)) {
                           String sqlUpdate = "update WEIXN_USER_TABLE SET ENABLEINTEGRATION=" + enabledTI + " ,CPENABLEINTEGRATION=" + enabledTICp + " " +
                                   " where 1=1 AND OPENID='" + openId + "'";
                           this.mapperI.update(sqlUpdate);
                           enabledIntegral=PubTools.doubleSave1(enabledTICp / 100)+"";
                           retJo.put("ENABLEINTEGRATION", enabledIntegral);
                       }else{

                       }
                       LogUtil.WriteLog_Info("用户更新可用积分完成", "QCodeInfoServiceImpl");
                   }

                   Consistant.map.remove(content);

                   //发送消息
                   String integralTypePu="";
                   if("FP".equals(integrateType)){
                       integralTypePu="加油";
                   }else if("FG".equals(integrateType)){
                       integralTypePu="加气";
                   }else if("FC".equals(integrateType)){
                       integralTypePu="餐饮";
                   }else if("FS".equals(integrateType)){
                       integralTypePu="商超";
                   }
                   this.messagePushServiceImpl.pushMsg(openId,integralTypePu,"-"+consumeIntegral,enabledIntegral);
               }
               ret="1";
               //积分核减成功

           }else{
               //需要判断是否是餐饮预约
               String appointMentSql="select t.ID,t.SERVICEOPERATIONID,tt.JOBNUMBER,t.COMPLETESTATUS from APPOINTMENT_INFO_TABLE t,SERVICE_AREA_OPERATORS_TABLE tt where t.SERVICEOPERATIONID = tt.ID AND t.ORDERID='"+content+"'";
               List appointMentList = this.mapperI.selectforlist(appointMentSql);
               if(appointMentList != null && appointMentList.size()>0) {
                   Map<String, Object> appointment = (Map<String, Object>) appointMentList.get(0);
                   String appomintJob=appointment.get("JOBNUMBER").toString();
                   String completeStatus=appointment.get("COMPLETESTATUS").toString();
                   if("Y".equals(completeStatus)){
                       if(!appomintJob.equals(serverOperationId)){//数据已核销
                           ret = "12";
                           retJo.put("ret", ret);
                           return retJo;
                       }
                   }
                   if(!appomintJob.equals(serverOperationId)){//说明订单中商户与核销的商户不符
                       ret = "11";
                       retJo.put("ret", ret);
                       return retJo;
                   }
                   //先查询商户角色
                   String serivceOperatorRole = "SELECT saot.ID,saot.USERNAME,saot.ROLEID,saot.SERVICEAREAID,saoc.INPUTMENEY FROM SERVICE_AREA_OPERATORS_TABLE saot,SERVICE_AREA_OPERATORS_COMPANY_TEXT saoc  " +
                           " WHERE saoc.ID = saot.COMPANYID AND saot.JOBNUMBER='" + serverOperationId + "'";
                   List serviceOperatorList = this.mapperI.selectforlist(serivceOperatorRole);
                   if (serviceOperatorList.size() < 1) {//商户不存在
                       ret = "5";
                       retJo.put("ret", ret);
                       return retJo;
                   }
                   //如果是餐饮预约， 则直接改了状态即可
                       String updateAppointSql = "UPDATE APPOINTMENT_INFO_TABLE SET COMPLETESTATUS='Y' WHERE ORDERID='"+content+"'";
                       this.mapperI.update(updateAppointSql);
                       LogUtil.WriteLog_Info("积分核减=====修改预约记录为已核销", "QCodeInfoServiceImpl");
                       ret = "1";
                       retJo.put("ret", ret);
                       return retJo;
               }else{
                   ret="4";
                   retJo.put("ret",ret);
                   return  retJo;
               }

           }
       }catch (Exception e){
           e.printStackTrace();
           LogUtil.WriteLog_Error("积分核减操作失败====="+e.getMessage(),"QCodeInfoServiceImpl");
           ret="-1";
           retJo.put("ret",ret);
            //Consistant.map.remove(content);
            retJo.put("code",-1);
            retJo.put("msg","积分核减接口出错");
            retJo.put("data","");
            WebsocketUtil.sendMessage(openId,JSONObject.toJSONString(retJo));
           // WebsocketUtil.removeSession(openId);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           return retJo;
       }
        retJo.put("ret",ret);
        return retJo;
    }

    public int failBackMoney(String content, String serverOperationId,String orderId) throws Exception {
        return rollBackIntegral(content,serverOperationId,orderId);
    }
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})
    public int rollBackIntegral(String content, String serverOperationId,String orderId) throws Exception {
        int ret=1;// -1 代表接口处理失败 1 处理成功  2 商户不存在 3订单已经退回  4 用户信息未找到
        try{
            LogUtil.WriteLog_Info("调用红冲接口开始=====","QCodeInfoServiceImpl");
            String sqlTemp="select t.ID,COALESCE(to_char(t.INTEGRATIONLISTID),'') AS INTEGRATIONLISTID,COALESCE(to_char(t.INTEGRALROLLBACK),'') AS INTEGRALROLLBACK,t.USERID from CAFTER_TABLE t where t.ORDERID = '"+orderId+"' AND t.USERJOBNUMBER='"+serverOperationId+"'";
            if("4".equals(DBType)){
                sqlTemp="select t.ID,COALESCE(CONVERT(t.INTEGRATIONLISTID,CHAR),'') AS INTEGRATIONLISTID,COALESCE(CONVERT(t.INTEGRALROLLBACK,CHAR),'') AS INTEGRALROLLBACK,t.USERID from CAFTER_TABLE t where t.ORDERID = '"+orderId+"' AND t.USERJOBNUMBER='"+serverOperationId+"'";
            }
            List selectforlist = this.mapperI.selectforlist(sqlTemp);
            if(selectforlist.size()<1){
                ret=2;
                return ret;
            }else{
                //判断订单是否已经取消过
                Map<String,Object> o =(Map<String,Object>)   selectforlist.get(0);
                String integralIdRoll=PubTools.isEmpty(o.get("INTEGRALROLLBACK"))?"":o.get("INTEGRALROLLBACK").toString();
                String userId=PubTools.isEmpty(o.get("USERID"))?"":o.get("USERID").toString();

                //判断用户是否被锁定
                String sqlUserTemp="SELECT ut.CERTIFICATION FROM WEIXN_USER_TABLE ut WHERE ID="+userId+"";
                List userByOpenIdTemp = this.mapperI.selectforlist(sqlUserTemp);
                if(userByOpenIdTemp.size()<1){
                    ret=4;
                    return  ret;
                }else {
                    Object obj = userByOpenIdTemp.get(0);
                    Map<String, Object> obj1 = (Map<String, Object>) obj;

                    String certification = obj1.get("CERTIFICATION").toString();//认证状态
                    if ("5".equals(certification)) {
                        ret=5;
                        return  ret;
                    }
                }

                if(!PubTools.isNull(integralIdRoll)){
                    ret=3;
                    return ret;
                }
                String openId="";
                //查询积分流水
                String integralId=o.get("INTEGRATIONLISTID").toString();
                String integralSql="select " +
                        "  ilt.ID,ilt.USERID ,ilt.ACARNO ,ilt.LASTINTEGRATION AS LASTINTEGRATION ,ilt.PAYTYPE,ilt.PAYINTEGRATION AS PAYINTEGRATION , " +
                        "  ilt.RESTINTEGRATION AS RESTINTEGRATION,ilt.OGENABLEINTEGRATION AS OGENABLEINTEGRATION,ilt.CPENABLEINTEGRATION AS CPENABLEINTEGRATION " +
                        "  from integration_list_table ilt where ilt.ID="+integralId+" ";

                List selectforlistInt = this.mapperI.selectforlist(integralSql);
                String rollbackTime=PubTools.getCurrentDate();
                if(selectforlistInt.size()>0){
                    Map<String,Object> oIntegral =(Map<String,Object>)   selectforlistInt.get(0);
                   String userid=PubTools.isEmpty(oIntegral.get("USERID"))?"": oIntegral.get("USERID").toString();
                   String payType=PubTools.isEmpty(oIntegral.get("PAYTYPE"))?"": oIntegral.get("PAYTYPE").toString();
                    String aCarNo=  PubTools.isEmpty(oIntegral.get("ACARNO"))?"":oIntegral.get("ACARNO").toString();
                    String payIntegral= PubTools.isEmpty(oIntegral.get("PAYINTEGRATION"))?"0":oIntegral.get("PAYINTEGRATION").toString();
                    String sqlMax="select COALESCE(max(t.ID),0) AS ID from integration_list_table t";
                    List selectforlistMax = this.mapperI.selectforlist(sqlMax);
                    int maxId=1;
                    if(selectforlistMax.size()>0){
                        Map<String,Object> os =(Map<String,Object>) selectforlistMax.get(0);
                        maxId=Integer.parseInt(os.get("ID").toString()) ;
                    }
                    String sqlUser="select " +
                            " ut.ID ,ut.OPENID ,COALESCE(ut.ENABLEINTEGRATION,0) AS ENABLEINTEGRATION," +
                            " COALESCE(ut.OGENABLEINTEGRATION,0) AS OGENABLEINTEGRATION," +
                            " COALESCE(ut.CPENABLEINTEGRATION,0) AS CPENABLEINTEGRATION" +
                            " from WEIXN_USER_TABLE ut " +
                            " where 1=1 AND ut.ID="+userid+"";
                    List userByOpenId = this.mapperI.selectforlist(sqlUser);
                    String ENABLEINTEGRATION="0";
                    double OGENABLEINTEGRATION=0.0;
                    double CPENABLEINTEGRATION=0.0;
                    if(userByOpenId.size()>0){
                        Object obj = userByOpenId.get(0);
                        Map<String, Object> obj1 = (Map<String, Object>) obj;
                         ENABLEINTEGRATION = obj1.get("ENABLEINTEGRATION").toString();//用户可用公共积分
                        OGENABLEINTEGRATION =Double.parseDouble(obj1.get("OGENABLEINTEGRATION").toString()) ;//用户可用加油、加气积分
                        CPENABLEINTEGRATION = Double.parseDouble(obj1.get("CPENABLEINTEGRATION").toString());//用户可用消费积分
                    }
                   /* String totalAddIntegralSql="SELECT COALESCE(MAX(ilt.TOTALADDINTEGRATION),0)  AS TOTALADDINTEGRATION FROM INTEGRATION_LIST_TABLE ilt,WEIXN_USER_TABLE ut WHERE ilt.USERID = ut.ID AND ut.ID="+userid+"";
                    List selectforlistTotalAdd = this.mapperI.selectforlist(totalAddIntegralSql);
                    double totalAddIntegral=0.0;
                    if(selectforlistTotalAdd.size()>0){
                        Map<String,Object> ot =(Map<String,Object>) selectforlistTotalAdd.get(0);
                        totalAddIntegral =Double.parseDouble(ot.get("TOTALADDINTEGRATION").toString()) ;
                    }*/

                    if("FG".equals(payType) || "FP".equals(payType)){//加油加气
                        OGENABLEINTEGRATION=  PubTools.doubleSave1(OGENABLEINTEGRATION+Double.parseDouble(payIntegral));
                    }else {//消费
                        CPENABLEINTEGRATION=  PubTools.doubleSave1(CPENABLEINTEGRATION+Double.parseDouble(payIntegral));
                    }
                    String cafterSql="INSERT INTO integration_list_table ( ID, USERID,ACARNO, LASTINTEGRATION, PAYINTEGRATION, RESTINTEGRATION, PAYTIME, PAYTYPE,CPENABLEINTEGRATION,OGENABLEINTEGRATION )\n" +
                            "VALUES\n" +
                            "\t(\n" +
                            "\t\t"+(maxId+1)+",\n" +
                            "\t\t'"+userid+"'," +
                            "\t\t'"+aCarNo+"'," +
                            "\t\t"+PubTools.doubleSave1(Double.parseDouble(ENABLEINTEGRATION))+",\n" +
                            "\t\t"+PubTools.doubleSave1(Double.parseDouble(payIntegral))+",\n" +
                            "\t\t"+PubTools.doubleSave1((Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(payIntegral)))+",\n" ;
                           if("2".equals(DBType)){
                               cafterSql+= "\t\tto_date('"+rollbackTime+"','yyyy-MM-dd HH24:mi:ss'),\n" ;
                           }else if("4".equals(DBType)){
                               cafterSql+= "\t\tstr_to_date('"+rollbackTime+"','%Y-%m-%d %H:%i:%s'),\n" ;
                           }
                              cafterSql+= "\t'TK',\n" +
                            "\t'"+PubTools.doubleSave1(CPENABLEINTEGRATION)+"', \n" +
                            "\t'"+PubTools.doubleSave1(OGENABLEINTEGRATION)+"' \n" +
                            "\t)";
                    this.mapperI.insert(cafterSql);
                    LogUtil.WriteLog_Info("积分恢复=====流水记录已插入","QCodeInfoServiceImpl");
                    String updateCafe="UPDATE CAFTER_TABLE set ROLLBACK='SUCCESS',INTEGRALROLLBACK='"+(maxId+1)+"',ROLLBACKTIME=to_date('"+rollbackTime+"','yyyy-MM-dd HH24:mi:ss') WHERE ORDERID = '"+orderId+"' AND USERJOBNUMBER='"+serverOperationId+"'";
                    if("4".equals(DBType)){
                        updateCafe="UPDATE CAFTER_TABLE set ROLLBACK='SUCCESS',INTEGRALROLLBACK='"+(maxId+1)+"',ROLLBACKTIME=str_to_date('"+rollbackTime+"','%Y-%m-%d %H:%i:%s') WHERE ORDERID = '"+orderId+"' AND USERJOBNUMBER='"+serverOperationId+"'";
                    }
                    this.mapperI.update(updateCafe);
                    LogUtil.WriteLog_Info("积分恢复=====消费记录已更新完成","QCodeInfoServiceImpl");
                    //3、计算用户可用积分
                    String sql="select " +
                            " ut.ID ,ut.OPENID ,COALESCE(ut.ENABLEINTEGRATION,0) AS ENABLEINTEGRATION,COALESCE(ut.CPENABLEINTEGRATION,0) AS CPENABLEINTEGRATION,COALESCE(ut.OGENABLEINTEGRATION,0) AS OGENABLEINTEGRATION" +
                            " from WEIXN_USER_TABLE ut " +
                            " where 1=1 AND ut.ID="+userid+"";
                    List selectforlist1 = this.mapperI.selectforlist(sql);
                    double enabledIntegral = 0.0;
                    if(selectforlist1.size()>0){
                        Object objT = selectforlist1.get(0);
                        Map<String, Object> obj1T = (Map<String, Object>) objT;
                        openId=obj1T.get("OPENID").toString();
                        Double enabledT=Double.parseDouble(obj1T.get("ENABLEINTEGRATION").toString());
                        BigDecimal bd = BigDecimal.valueOf(enabledT + Double.parseDouble(payIntegral));
                        bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                        double enabledTI = bd.doubleValue();

                        Double enabledTCp=Double.parseDouble(obj1T.get("CPENABLEINTEGRATION").toString());
                        BigDecimal bdcp = BigDecimal.valueOf(enabledTCp + Double.parseDouble(payIntegral));
                        bdcp = bdcp.setScale(1, BigDecimal.ROUND_HALF_UP);
                        double enabledTICp =0.0;
                        if("FC".equals(payType) || "FS".equals(payType)){
                            enabledTICp = bdcp.doubleValue();
                            enabledIntegral=enabledTICp;
                        }else{
                            enabledTICp=enabledTCp;
                        }

                        Double enabledTOG=Double.parseDouble(obj1T.get("OGENABLEINTEGRATION").toString());
                        BigDecimal bdco = BigDecimal.valueOf(enabledTOG +Double.parseDouble(payIntegral));
                        bdco = bdco.setScale(1, BigDecimal.ROUND_HALF_UP);
                        double enabledTIOG =0.0;
                        if("FG".equals(payType) || "FP".equals(payType)){
                            enabledTIOG = bdco.doubleValue();
                            enabledIntegral=enabledTIOG;
                        }else{
                            enabledTIOG=enabledTOG;
                        }
                        String sqlUpdate="update WEIXN_USER_TABLE SET ENABLEINTEGRATION="+enabledTI+",CPENABLEINTEGRATION="+enabledTICp+",OGENABLEINTEGRATION="+enabledTIOG+" " +
                                " where 1=1 AND ID="+userid+"";
                        this.mapperI.update(sqlUpdate);
                        LogUtil.WriteLog_Info("用户更新可用积分完成","QCodeInfoServiceImpl");
                    }


                    //发送消息
                    String integralTypePu="";
                    if("FP".equals(payType)){
                        integralTypePu="加油(恢复积分)";
                    }else if("FG".equals(payType)){
                        integralTypePu="加气(恢复积分)";
                    }else if("FC".equals(payType)){
                        integralTypePu="餐饮(恢复积分)";
                    }else if("FS".equals(payType)){
                        integralTypePu="商超(恢复积分)";
                    }
                    this.messagePushServiceImpl.pushMsg(openId,integralTypePu,"+"+PubTools.doubleSave1(Double.parseDouble(payIntegral)/100)+"",(enabledIntegral/100)+"");
                }
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("退款恢复积分操作失败===="+e.getMessage(),"QCodeInfoServiceImpl");
            ret=-1;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ret;
        }

        return ret;
    }
    public String getStatusByOrderId( String orderId,String checkType){
        String ret="1";// -1 代表接口处理失败 1 处理成功  2 根据订单id未找到积分消费记录
        try{
            String sqlTemp="select t.ID,t.ORDERID,COALESCE(t.INTEGRATIONLISTID,'') AS INTEGRATIONLISTID,COALESCE(t.INTEGRALROLLBACK,'') AS INTEGRALROLLBACK from CAFTER_TABLE t where t.ORDERID = '"+orderId+"' ";
            List selectforlist = this.mapperI.selectforlist(sqlTemp);
            if(selectforlist.size()<1){
                ret="2";
                return ret;
            }else{
                Map<String,Object> o =(Map<String,Object>)   selectforlist.get(0);
                String integralId=o.get("INTEGRATIONLISTID").toString();
                String integralrollbacklId=o.get("INTEGRALROLLBACK").toString();
                if ("TRIMINTEGRAL".equals(checkType)){//积分核减结果
                  if(PubTools.isNull(integralId)){
                      ret="0";
                  }
                }else if ("ROLLBACK".equals(checkType)){//退款结果
                    if(PubTools.isNull(integralrollbacklId)){
                        ret="0";
                    }
                }
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("查询积分核减（退款）结果操作失败","QCodeInfoServiceImpl");
            ret="-1";
           return ret;
        }
        return ret;
    }
    public List getIntegralListByServiceId( String serverOperationId,String checkType,String payBeginTime,String payEndTime){
        List ret=null;// -1 代表接口处理失败 1 处理成功
        try{
            String sqlTemp="SELECT\n" +
                    "\tct.ORDERID,\n" +
                    "\tct.USERJOBNUMBER,\n" +
                    "\tCOALESCE(TO_CHAR(ct.CAFTERTIME,'YYYY-MM-dd HH24:mi:ss'),'') AS CAFTERTIMEBAK,\n" +
                    "\t\tCOALESCE(TO_CHAR(ct.ROLLBACKTIME,'YYYY-MM-dd HH24:mi:ss'),'') AS ROLLBACKTIME,\n" +
                    "\t\tCOALESCE(TO_CHAR(ilt.PAYTIME,'YYYY-MM-dd HH24:mi:ss'),'') AS CAFTERTIME,\n" +
                    "\tROUND(ilt.PAYINTEGRATION/100,1) AS PAYINTEGRATION,\n" +
                    "\tilt.PAYTYPE,\n" +
                    "\tpt.TEXT AS PAYTYPENAME\n" +
                    "FROM\n" +
                    "\tCAFTER_TABLE ct,\n" +
                    "\tINTEGRATION_LIST_TABLE ilt,\n" +
                    "  PEYTYPE_TEXT pt\t\n" +
                    "WHERE\n" +
                    "\t( ct.INTEGRATIONLISTID = ilt.ID OR ct.INTEGRALROLLBACK = ilt.ID ) \n" +
                    "\tAND ilt.PAYTYPE = pt.VALUE\n" +
                    "\tAND ct.USERJOBNUMBER = '"+serverOperationId+"'\n";
            if("4".equals(DBType)){
                sqlTemp="SELECT\n" +
                        "\tct.ORDERID,\n" +
                        "\tct.USERJOBNUMBER,\n" +
                        "\tCOALESCE(date_format(ct.CAFTERTIME, '%Y-%m-%d %H:%i:%s'),'') AS CAFTERTIMEBAK,\n" +
                        "\t\tCOALESCE(date_format(ct.ROLLBACKTIME,'%Y-%m-%d %H:%i:%s'),'') AS ROLLBACKTIME,\n" +
                        "\t\tCOALESCE(date_format(ilt.PAYTIME,'%Y-%m-%d %H:%i:%s'),'') AS CAFTERTIME,\n" +
                        "\tROUND(ilt.PAYINTEGRATION/100,1) AS PAYINTEGRATION,\n" +
                        "\tilt.PAYTYPE,\n" +
                        "\tpt.TEXT AS PAYTYPENAME\n" +
                        "FROM\n" +
                        "\tCAFTER_TABLE ct,\n" +
                        "\tINTEGRATION_LIST_TABLE ilt,\n" +
                        "  PEYTYPE_TEXT pt\t\n" +
                        "WHERE\n" +
                        "\t( ct.INTEGRATIONLISTID = ilt.ID OR ct.INTEGRALROLLBACK = ilt.ID ) \n" +
                        "\tAND ilt.PAYTYPE = pt.VALUE\n" +
                        "\tAND ct.USERJOBNUMBER = '"+serverOperationId+"'\n";
            }
              if(!PubTools.isNull(payBeginTime) && !PubTools.isNull(payEndTime)){
                 if("2".equals(DBType)){
                     sqlTemp +=" \tAND (\n" +
                             "\t\t (TO_CHAR( ct.CAFTERTIME, 'YYYY-MM-dd HH24:mi:ss' )>= '"+payBeginTime+"' AND TO_CHAR( ct.CAFTERTIME, 'YYYY-MM-dd HH24:mi:ss' )<= '"+payEndTime+"')\n" +
                             "\t\tOR  (TO_CHAR( ct.ROLLBACKTIME, 'YYYY-MM-dd HH24:mi:ss' ) >= '"+payBeginTime+"' AND TO_CHAR( ct.ROLLBACKTIME, 'YYYY-MM-dd HH24:mi:ss' )<= '"+payEndTime+"')\n" +
                             "\t) ";
                 }else  if("4".equals(DBType)){
                     sqlTemp +=" \tAND (\n" +
                             "\t\t (date_format( ct.CAFTERTIME, '%Y-%m-%d %H:%i:%s' )>= '"+payBeginTime+"' AND date_format( ct.CAFTERTIME, '%Y-%m-%d %H:%i:%s' )<= '"+payEndTime+"')\n" +
                             "\t\tOR  (date_format( ct.ROLLBACKTIME, '%Y-%m-%d %H:%i:%s' ) >= '"+payBeginTime+"' AND date_format( ct.ROLLBACKTIME, '%Y-%m-%d %H:%i:%s' )<= '"+payEndTime+"')\n" +
                             "\t) ";
                 }else{}

              }else if(!PubTools.isNull(payBeginTime) && PubTools.isNull(payEndTime)){
                  if("2".equals(DBType)){
                      sqlTemp +="\tAND (\n" +
                              "\t\t TO_CHAR( ct.CAFTERTIME, 'YYYY-MM-dd HH24:mi:ss' )>= '"+payBeginTime+"' \n" +
                              "\t\tOR  TO_CHAR( ct.ROLLBACKTIME, 'YYYY-MM-dd HH24:mi:ss' ) >= '"+payBeginTime+"' \n" +
                              "\t)";
                  }else if("4".equals(DBType)){
                      sqlTemp +="\tAND (\n" +
                              "\t\t date_format( ct.CAFTERTIME, '%Y-%m-%d %H:%i:%s' )>= '"+payBeginTime+"' \n" +
                              "\t\tOR  date_format( ct.ROLLBACKTIME, '%Y-%m-%d %H:%i:%s' ) >= '"+payBeginTime+"' \n" +
                              "\t)";
                  }else{

                  }

              }else if(PubTools.isNull(payBeginTime) && !PubTools.isNull(payEndTime)){

                  if("2".equals(DBType)){
                      sqlTemp +="AND (\n" +
                              "\t\tTO_CHAR( ct.CAFTERTIME, 'YYYY-MM-dd HH24:mi:ss' )<= '"+payEndTime+"'\n" +
                              "\t\tOR  TO_CHAR( ct.ROLLBACKTIME, 'YYYY-MM-dd HH24:mi:ss' )<= '"+payEndTime+"'\n" +
                              "\t) ";
                  }else if("4".equals(DBType)){
                      sqlTemp +="AND (\n" +
                              "\t\tdate_format( ct.CAFTERTIME, '%Y-%m-%d %H:%i:%s' )<= '"+payEndTime+"'\n" +
                              "\t\tOR  date_format( ct.ROLLBACKTIME, '%Y-%m-%d %H:%i:%s' )<= '"+payEndTime+"'\n" +
                              "\t) ";
                  }else{

                  }
              }else{

              }

            if(!PubTools.isNull(checkType)){
                if("TK".equals(checkType)){
                    sqlTemp +=" AND ilt.PAYTYPE='TK' ";
                }else{
                    sqlTemp +=" AND substr(ilt.PAYTYPE,1,1)='F' ";
                }
            }
            sqlTemp +=" order by ct.CAFTERTIME,ct.ROLLBACKTIME";
            ret = this.mapperI.selectforlist(sqlTemp);
        }catch (Exception e){
            LogUtil.WriteLog_Error("根据商户查询积分明细失败","QCodeInfoServiceImpl");
            ret=null;
           return ret;
        }
        return ret;
    }

    public List getIntegralTotalByServiceId( String serverOperationId){
        List ret=null;// -1 代表接口处理失败 1 处理成功
        try{
            String sqlTemp="SELECT\n" +
                    "\tCOALESCE(ROUND(sum(ilt.PAYINTEGRATION)/100,1),0) AS PAYINTEGRATION\n" +
                    "FROM\n" +
                    "\tCAFTER_TABLE ct,\n" +
                    "\tINTEGRATION_LIST_TABLE ilt,\n" +
                    "\tSERVICE_AREA_OPERATORS_TABLE soat,\n" +
                    "  PEYTYPE_TEXT pt\t\n" +
                    "WHERE\n" +
                    "\t( ct.INTEGRATIONLISTID = ilt.ID OR ct.INTEGRALROLLBACK = ilt.ID ) \n" +
                    "\tAND ilt.PAYTYPE = pt.VALUE\n" +
                    "\tAND ct.USERJOBNUMBER = soat.JOBNUMBER\n" +
                    "\tAND ct.USERJOBNUMBER = '"+serverOperationId+"' AND (ct.INTEGRALROLLBACK is null or ct.INTEGRALROLLBACK ='') group by ct.USERJOBNUMBER";
            ret = this.mapperI.selectforlist(sqlTemp);
        }catch (Exception e){
            LogUtil.WriteLog_Error("根据商户查询总积分失败","QCodeInfoServiceImpl");
            ret=null;
           return ret;
        }
        return ret;
    }
    public String hexToString(String hexStr){
        String[] split = hexStr.replace("|", ",").split(",");
        Long dataStr = Long.valueOf(split[0], 16);
        BigInteger bigint=new BigInteger(split[1], 16);
        int series=bigint.intValue();
        BigInteger bigint2=new BigInteger(split[2], 16);
        int rebateInteger=bigint2.intValue();
        BigInteger bigint3=new BigInteger(split[3], 16);
        int checkStr=bigint3.intValue();
        return dataStr+"|"+series+"|"+rebateInteger+"|"+checkStr;
    }

    /**
     *
     * @param content 二维码流水号
     * @param serverOperationId 商超用户ID
     * @param payMoney 实际支付金额
     * @return
     */
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})
    public JSONObject solveQcodeRedis(String content, String serverOperationId,String orderId, Double payMoney,Double discountMoneyBefore,Double discountMoney) throws Exception {
        String ret="-2";// -1 代表接口处理失败 1 处理成功  2 用户不存在 3 兑换积分大于用户可用积分 4 二维码信息过期 5 商户不存在 6 积分类型与消费方式不匹配 7 商户角色未设置 8 用户已冻结 9 折扣金额与消费积分不一致 10 请重新生成二维码 11  订单中商户与核销中的商户不匹配  12 订单已核销
        JSONObject retJo=new JSONObject();
        String openId="";
        try{
            LogUtil.WriteLog_Info("积分核减操作开始====="+PubTools.getCurrentDate()+"=======params==={content:"+content+",serverOperationId:"+serverOperationId+",discountMoney:"+discountMoney+"}","QCodeInfoServiceImpl");
            //查询金额与积分的兑换比例，一元兑换积分
            String sqlTemp="select t.VALUE/100 AS VALUE ,t.EVERYMONEY/100 AS EVERYMONEY from PAY_INTEGRATION_NUMBER_TABLE t where t.TYPE='@TYPE@'";
            String rollbackTime=PubTools.getCurrentDate();
            Object content1 = Consistant.map.get(content);
            if(PubTools.isEmpty(content1)){
                content1 = redisConfigUtil.getIntegral(content);
            }
            if(content1 != null && !"-1".equals(content1.toString())){
                JSONObject joMap=null;
                if(content1 instanceof JSONObject){
                    joMap=(JSONObject)content1;
                } else if (content1 instanceof String) {
                    joMap = JSONObject.parseObject(content1.toString());
                }
                if(joMap== null){
                    ret="4";
                    retJo.put("ret",ret);
                    return  retJo;
                }
                openId= PubTools.isEmpty(joMap.get("openId"))?"":joMap.get("openId").toString();
                String integrateTypeParam= PubTools.isEmpty(joMap.get("integrateType"))?"":joMap.get("integrateType").toString();
                String rebateIntegrate= PubTools.isEmpty(joMap.get("rebateIntegrate"))?"":joMap.get("rebateIntegrate").toString();
                String createTime= PubTools.isEmpty(joMap.get("createTime"))?"":joMap.get("createTime").toString();
                Long s = PubTools.dateDiff(createTime, rollbackTime, "S");
                LogUtil.WriteLog_Info("二维码生成时间长度====="+s,"QCodeInfoServiceImpl");
                retJo.put("openId",openId);

                String integrateType="";
                String consumeIntegral="";
                String enabledIntegral="";
                int userIdNew=0;
                //校验用户状态
                List userByOpenId = userTableService.getUserByOpenId(openId);
                Object obj = userByOpenId.get(0);
                Map<String, Object> obj1 = (Map<String, Object>) obj;
                String certification = obj1.get("CERTIFICATION").toString();//认证状态
                if(userByOpenId.size()<1){
                    Object contentNew = Consistant.map.get(content);
                    if(!PubTools.isEmpty(contentNew)){
                        Consistant.map.remove(content);
                    }
                    Long l = redisConfigUtil.delIntegral(content);
                    ret="2";
                    retJo.put("ret",ret);
                    return  retJo;
                }
                if ("5".equals(certification)) {
                    ret = "8";
                    retJo.put("ret", ret);
                    Object contentNew = Consistant.map.get(content);
                    if(!PubTools.isEmpty(contentNew)){
                        Consistant.map.remove(content);
                    }
                    Long l = redisConfigUtil.delIntegral(content);
                    return retJo;
                }

                //先查询商户角色
                String serviceRole = "";
                String inputMoney = "";//是否需要商户端输入金额
                String serivceOperatorRole = "SELECT saot.ID,saot.USERNAME,saot.ROLEID,saot.SERVICEAREAID,saoc.INPUTMENEY FROM SERVICE_AREA_OPERATORS_TABLE saot,SERVICE_AREA_OPERATORS_COMPANY_TEXT saoc  " +
                        " WHERE saoc.ID = saot.COMPANYID AND saot.JOBNUMBER='" + serverOperationId + "'";
                List serviceOperatorList = this.mapperI.selectforlist(serivceOperatorRole);
                if (serviceOperatorList.size() < 1) {//商户不存在
                    Object contentNew = Consistant.map.get(content);
                    if(!PubTools.isEmpty(contentNew)){
                        Consistant.map.remove(content);
                    }
                    Long l = redisConfigUtil.delIntegral(content);
                    ret = "5";
                    retJo.put("ret", ret);
                    return retJo;
                }
                boolean isCheckDiscountMoney=false;
                if(userByOpenId.size()>0){
                    //String startLevel= obj1.get("STARLEVEL").toString();//星级
                    String ENABLEINTEGRATION = obj1.get("ENABLEINTEGRATION").toString();//用户可用公共积分
                    String OILENABLEINTEGRATION = obj1.get("OILENABLEINTEGRATION").toString();//加油可用积分
                    String GASENABLEINTEGRATION = obj1.get("GASENABLEINTEGRATION").toString();//加气可用积分
                    String SPENABLEINTEGRATION = obj1.get("SPENABLEINTEGRATION").toString();//消费可用积分
                    String CAFENABLEINTEGRATION = obj1.get("CAFENABLEINTEGRATION").toString();//餐饮可用积分
                    String OGENABLEINTEGRATION = obj1.get("OGENABLEINTEGRATION").toString();//加油、加气可用积分
                    String CPENABLEINTEGRATION = obj1.get("CPENABLEINTEGRATION").toString();//餐饮、消费可用积分
                    userIdNew = Integer.parseInt(obj1.get("ID").toString());//人员id
                    if (s > 30) {
                        Object contentNew = Consistant.map.get(content);
                        if(!PubTools.isEmpty(contentNew)){
                            Consistant.map.remove(content);
                        }
                        Long l = redisConfigUtil.delIntegral(content);
                        ret = "4";
                        retJo.put("ret", ret);
                        return retJo;
                    }
                    //核验商户角色与积分消费类型是否匹配

                    if (serviceOperatorList.size() >0 ) {
                        //校验用户与角色出示二维码积分消费类型是否匹配
                        Map<String, Object> mapServiceOperator = (Map<String, Object>) serviceOperatorList.get(0);
                        serviceRole = mapServiceOperator.get("ROLEID").toString();
                        /* serviceAreaId = mapServiceOperator.get("SERVICEAREAID").toString();*/
                        inputMoney = mapServiceOperator.get("INPUTMENEY").toString();
                    }
                    if("1".equals(inputMoney)){
                        isCheckDiscountMoney=true;
                    }
                    //根据商户角色判断消费类型
                    if (PubTools.isNull(serviceRole)) {
                        LogUtil.WriteLog_Info("商户角色未设置", "QCodeInfoServiceImpl");
                        Object contentNew = Consistant.map.get(content);
                        if(!PubTools.isEmpty(contentNew)){
                            Consistant.map.remove(content);
                        }
                        Long l = redisConfigUtil.delIntegral(content);
                        ret = "7";
                        retJo.put("ret", ret);
                        return retJo;
                    } else {
                        if ("3".equals(serviceRole) || "1".equals(serviceRole)) {
                            if (!"FPG".equals(integrateTypeParam)) {
                                ret = "6";
                                retJo.put("ret", ret);
                                Object contentNew = Consistant.map.get(content);
                                if(!PubTools.isEmpty(contentNew)){
                                    Consistant.map.remove(content);
                                }
                                Long l = redisConfigUtil.delIntegral(content);
                                return retJo;
                            }
                        }
                        if ("2".equals(serviceRole) || "4".equals(serviceRole)) {
                            if (!"FCS".equals(integrateTypeParam) && !"FCA".equals(integrateTypeParam)) {
                                ret = "6";
                                retJo.put("ret", ret);
                                Object contentNew = Consistant.map.get(content);
                                if(!PubTools.isEmpty(contentNew)){
                                    Consistant.map.remove(content);
                                }
                                Long l = redisConfigUtil.delIntegral(content);
                                return retJo;
                            }
                        }
             /*          //如果是餐饮预约， 则直接改了状态即可
                       if("FCA".equals(integrateTypeParam)){
                           String updateAppointSql="UPDATE APPOINTMENT_INFO_TABLE SET COMPLETESTATUS='Y' WHERE ID="+rebateIntegrate;
                           this.mapperI.update(updateAppointSql);
                           LogUtil.WriteLog_Info("积分核减=====修改预约记录为已核销", "QCodeInfoServiceImpl");
                           ret = "1";
                           retJo.put("ret", ret);
                           return retJo;
                       }*/

                        if ("1".equals(serviceRole)) {
                            integrateType = "FP";
                        } else if ("2".equals(serviceRole)) {
                            integrateType = "FC";
                        } else if ("3".equals(serviceRole)) {
                            integrateType = "FG";
                        } else if ("4".equals(serviceRole)) {
                            integrateType = "FS";
                        } else {

                        }
                    }
                    //查询用户累积获取的总积分
                    String totalAddIntegralSql = "SELECT COALESCE(MAX(ilt.TOTALADDINTEGRATION),0)  AS TOTALADDINTEGRATION FROM INTEGRATION_LIST_TABLE ilt,WEIXN_USER_TABLE ut WHERE ilt.USERID = ut.ID AND ut.OPENID='" + openId + "'";
                    double totalAddIntegral = 0.0;
                    double rebateIntegrateSave = 0.0;
                    switch (integrateType) {
                        case "FP"://加油
                            retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(OGENABLEINTEGRATION)));
                            String sqlFp = sqlTemp.replace("@TYPE@", integrateType);
                            List selectforlist = this.mapperI.selectforlist(sqlFp);
                            //判断兑换积分是否够本次折扣
                            int rebateIn = 1;
                            if (selectforlist.size() > 0) {
                                Map<String, Object> o = (Map<String, Object>) selectforlist.get(0);
                                BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(o.get("VALUE").toString()));
                                bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                                rebateIn=bd.intValue();
                            }
                            //根据折扣金额计算积分
                            Double rebateIntegrateI = Double.parseDouble(rebateIntegrate);
                            Double rebateIntegrateIZK=PubTools.doubleSave1(discountMoney*rebateIn);
                            //double enabledIntegFc=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(CAFENABLEINTEGRATION);
                            if(isCheckDiscountMoney){
                                if((rebateIntegrateIZK  -  rebateIntegrateI) != 0){
                                    ret = "9";
                                    retJo.put("PAYINTEGRAL", rebateIntegrateI);
                                    retJo.put("discountMoney", rebateIntegrateIZK);
                                    retJo.put("ret", ret);
                                    return retJo;
                                }
                            }
                            //double enabledInteg=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(OILENABLEINTEGRATION);
                            double enabledInteg = Double.parseDouble(OGENABLEINTEGRATION);
                            if (rebateIntegrateI > enabledInteg) {
                                ret = "3";
                                retJo.put("PAYINTEGRAL", rebateIntegrateI);
                                retJo.put("ret", ret);
                                return retJo;
                            } else {
                                rebateIntegrateSave=rebateIntegrateI;
                                retJo.put("PAYINTEGRAL", rebateIntegrateI);
                            }
                            break;
                        case "FG"://加气
                            retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(OGENABLEINTEGRATION)));
                            String sqlFg = sqlTemp.replace("@TYPE@", integrateType);
                            List selectforlistFg = this.mapperI.selectforlist(sqlFg);
                            //判断兑换积分是否够本次折扣
                            int rebateInFg = 1;
                            if (selectforlistFg.size() > 0) {
                                Map<String, Object> o = (Map<String, Object>) selectforlistFg.get(0);
                                BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(o.get("VALUE").toString()));
                                bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                                rebateInFg=bd.intValue();
                            }
                            //根据折扣金额计算积分
                            //  int rebateIntegrateI=Integer.parseInt(rebateIntegrate);
                            Double rebateIntegrateIFgZk=PubTools.doubleSave1(discountMoney*rebateInFg);
                            Double rebateIntegrateIFg = Double.parseDouble(rebateIntegrate);
                            // double enabledIntegFg=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(GASENABLEINTEGRATION);

                            //折扣金额与输入的积分是否一致
                            if(isCheckDiscountMoney) {
                                if ((rebateIntegrateIFgZk - rebateIntegrateIFg) != 0) {
                                    ret = "9";
                                    retJo.put("PAYINTEGRAL", rebateIntegrateIFg);
                                    retJo.put("discountMoney", rebateIntegrateIFgZk);
                                    retJo.put("ret", ret);
                                    return retJo;
                                }
                            }
                            double enabledIntegFg = Double.parseDouble(OGENABLEINTEGRATION);
                            if (rebateIntegrateIFg > enabledIntegFg) {
                                ret = "3";
                                retJo.put("PAYINTEGRAL", rebateIntegrateIFg);
                                retJo.put("ret", ret);
                                return retJo;
                            } else {
                                rebateIntegrateSave=rebateIntegrateIFg;
                                retJo.put("PAYINTEGRAL", rebateIntegrateIFg);
                            }
                            break;
                        case "FC"://餐饮
                            retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(CPENABLEINTEGRATION)));
                            String sqlFc = sqlTemp.replace("@TYPE@", integrateType);
                            List selectforlistFc = this.mapperI.selectforlist(sqlFc);
                            //判断兑换积分是否够本次折扣
                            int rebateInFc = 1;
                            if (selectforlistFc.size() > 0) {
                                Map<String, Object> o = (Map<String, Object>) selectforlistFc.get(0);
                                BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(o.get("VALUE").toString()));
                                bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                                rebateInFc=bd.intValue();
                            }
                            //根据折扣金额计算积分
                            Double rebateIntegrateIFcZK=discountMoney*rebateInFc;
                            Double rebateIntegrateIFc = Double.parseDouble(rebateIntegrate);
                            //double enabledIntegFc=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(CAFENABLEINTEGRATION);
                            if(isCheckDiscountMoney) {
                                if ((rebateIntegrateIFcZK - rebateIntegrateIFc) != 0) {
                                    ret = "9";
                                    retJo.put("PAYINTEGRAL", rebateIntegrateIFc);
                                    retJo.put("discountMoney", rebateIntegrateIFcZK);
                                    retJo.put("ret", ret);
                                    return retJo;
                                }
                            }
                            double enabledIntegFc = Double.parseDouble(CPENABLEINTEGRATION);
                            if (rebateIntegrateIFc > enabledIntegFc) {
                                ret = "3";
                                retJo.put("PAYINTEGRAL", rebateIntegrateIFc);
                                retJo.put("ret", ret);
                                return retJo;
                            } else {
                                //进行积分核减
                                rebateIntegrateSave=rebateIntegrateIFc;
                                retJo.put("PAYINTEGRAL", rebateIntegrateIFc);
                            }
                            break;
                        case "FS"://消费
                            retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(CPENABLEINTEGRATION)));
                            String sqlFs = sqlTemp.replace("@TYPE@", integrateType);
                            List selectforlistFs = this.mapperI.selectforlist(sqlFs);
                            //判断兑换积分是否够本次折扣
                            int rebateInFs = 1;
                            if (selectforlistFs.size() > 0) {
                                Map<String, Object> o = (Map<String, Object>) selectforlistFs.get(0);
                                BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(o.get("VALUE").toString()));
                                bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                                rebateInFs=bd.intValue();
                            }
                            //根据折扣金额计算积分

                            //  int rebateIntegrateI=Integer.parseInt(rebateIntegrate);
                            Double rebateIntegrateIFsZK=discountMoney*rebateInFs;
                            Double rebateIntegrateIFs = Double.parseDouble(rebateIntegrate);
                            //double enabledIntegFs=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(SPENABLEINTEGRATION);


                            //double enabledIntegFc=Double.parseDouble(ENABLEINTEGRATION)+Double.parseDouble(CAFENABLEINTEGRATION);
                            if(isCheckDiscountMoney) {
                                if ((rebateIntegrateIFsZK - rebateIntegrateIFs) != 0) {
                                    ret = "9";
                                    retJo.put("PAYINTEGRAL", rebateIntegrateIFs);
                                    retJo.put("discountMoney", rebateIntegrateIFsZK);
                                    retJo.put("ret", ret);
                                    return retJo;
                                }
                            }
                            double enabledIntegFs = Double.parseDouble(CPENABLEINTEGRATION);
                            if (rebateIntegrateIFs > enabledIntegFs) {
                                ret = "3";
                                retJo.put("PAYINTEGRAL", rebateIntegrateIFs);
                                retJo.put("ret", ret);
                                return retJo;
                            } else {
                                //进行积分核减
                                rebateIntegrateSave=rebateIntegrateIFs;
                                retJo.put("PAYINTEGRAL", rebateIntegrateIFs);
                            }
                            break;
                        default:
                            break;
                    }


                    //进行积分核减
                  /* List selectforlistTotalAdd = this.mapperI.selectforlist(totalAddIntegralSql);
                   if (selectforlistTotalAdd.size() > 0) {
                       Map<String, Object> o = (Map<String, Object>) selectforlistTotalAdd.get(0);
                       totalAddIntegral = Double.parseDouble(o.get("TOTALADDINTEGRATION").toString());
                   }*/
                    //1、积分流水记录新加
                    String sqlMax = "select COALESCE(max(ID),0) AS  ID from integration_list_table";
                    List selectforlistMax = this.mapperI.selectforlist(sqlMax);
                    //判断兑换积分是否够本次折扣
                    int maxId = 1;
                    if (selectforlistMax.size() > 0) {
                        Map<String, Object> o = (Map<String, Object>) selectforlistMax.get(0);
                        maxId = Integer.parseInt(o.get("ID").toString());
                    }
                    String cafterSql = "INSERT INTO integration_list_table ( ID, USERID, LASTINTEGRATION, PAYINTEGRATION, RESTINTEGRATION, PAYTIME, PAYTYPE,OGENABLEINTEGRATION,CPENABLEINTEGRATION )\n" +
                            "VALUES\n" +
                            "\t(\n" +
                            "\t\t" + (maxId + 1) + ",\n" +
                            "\t\t"+userIdNew+",\n" +
                            "\t\t" + PubTools.doubleSave1(Double.parseDouble(ENABLEINTEGRATION) * 100) + ",\n" +
                            "\t\t" + PubTools.doubleSave1(rebateIntegrateSave * 100) + ",\n" +
                            "\t\t" + PubTools.doubleSave1(((Double.parseDouble(ENABLEINTEGRATION) - rebateIntegrateSave) * 100)) + ",\n" +
                            "\t\tto_date('" + rollbackTime + "','yyyy-MM-dd HH24:mi:ss'),\n" +
                            "\t'" + integrateType + "', \n" ;
                    if("4".equals(DBType)){
                        cafterSql = "INSERT INTO integration_list_table ( ID, USERID, LASTINTEGRATION, PAYINTEGRATION, RESTINTEGRATION, PAYTIME, PAYTYPE,OGENABLEINTEGRATION,CPENABLEINTEGRATION )\n" +
                                "VALUES\n" +
                                "\t(\n" +
                                "\t\t" + (maxId + 1) + ",\n" +
                                "\t\t"+userIdNew+",\n" +
                                "\t\t" + PubTools.doubleSave1(Double.parseDouble(ENABLEINTEGRATION) * 100) + ",\n" +
                                "\t\t" + PubTools.doubleSave1(rebateIntegrateSave * 100) + ",\n" +
                                "\t\t" + PubTools.doubleSave1(((Double.parseDouble(ENABLEINTEGRATION) - rebateIntegrateSave) * 100)) + ",\n" +
                                "\t\tstr_to_date('" + rollbackTime + "','%Y-%m-%d %H:%i:%s'),\n" +
                                "\t'" + integrateType + "', \n" ;
                    }


                    if("FP".equals(integrateType) || "FG".equals(integrateType)){
                        cafterSql +=  "\t" + PubTools.doubleSave1(((Double.parseDouble(OGENABLEINTEGRATION) - rebateIntegrateSave) * 100)) + ", \n" +
                                "\t" + PubTools.doubleSave1(Double.parseDouble(CPENABLEINTEGRATION) * 100) + " \n" ;
                    }else if("FC".equals(integrateType) || "FS".equals(integrateType)) {
                        cafterSql +="\t" + PubTools.doubleSave1(((Double.parseDouble(OGENABLEINTEGRATION)) * 100)) + ", \n" +
                                "\t" + PubTools.doubleSave1((Double.parseDouble(CPENABLEINTEGRATION) - rebateIntegrateSave) * 100)+" " ;
                    }else{

                    }
                    cafterSql+=  "\t)";
                    this.mapperI.insert(cafterSql);
                    consumeIntegral=rebateIntegrateSave+"";
                    LogUtil.WriteLog_Info("积分核减=====积分流水已插入", "QCodeInfoServiceImpl");
                    //2、新加一条消费记录
                    String sqlIntegralList = "insert into CAFTER_TABLE(ID,\n" +
                            "ACARNO,\n" +
                            "USERID,\n" +
                            "CAFTERTIME,\n" +
                            "USERJOBNUMBER,\n" +
                            "TRIMINTEGRAL," +
                            "INTEGRATIONLISTID,\n" +
                            "ORDERID,CONTENT) values (\n" +
                            "  (select COALESCE(max(t.ID),0)+1 from CAFTER_TABLE t),''," +
                            ""+userIdNew+",to_date('" + rollbackTime + "','yyyy-MM-dd HH24:mi:ss'),'" + serverOperationId + "','SUCCESS'," + (maxId + 1) + ",'" + orderId + "','" + content + "'" +
                            ")";
                    if("4".equals(DBType)){
                        sqlIntegralList = "insert into CAFTER_TABLE(ID,\n" +
                                "ACARNO,\n" +
                                "USERID,\n" +
                                "CAFTERTIME,\n" +
                                "USERJOBNUMBER,\n" +
                                "TRIMINTEGRAL," +
                                "INTEGRATIONLISTID,\n" +
                                "ORDERID,CONTENT) values (\n" +
                                "  (select COALESCE(max(t.ID),0)+1 from CAFTER_TABLE t),''," +
                                ""+userIdNew+",str_to_date('" + rollbackTime + "','%Y-%m-%d %H:%i:%s'),'" + serverOperationId + "','SUCCESS'," + (maxId + 1) + ",'" + orderId + "','" + content + "'" +
                                ")";
                    }
                    this.mapperI.insert(sqlIntegralList);
                    //进行预约核销
                   /*String appointMentSql="";
                   if("FS".equals(integrateType)){
                        appointMentSql="SELECT ID FROM APPOINTMENT_INFO_TABLE t where t.SERVICEAREAID='"+serviceAreaId+"' AND t.USERID='"+userIdNew+"' AND APPOINTMENTTIME=to_date('"+rollbackTime+"','YYYY-MM-DD') AND t.COMPLETESTATUS='N' AND t.APPOINTMENTTYPE=3 ORDER BY t.CREATETIME ";
                   }else  if("FC".equals(integrateType)){
                       appointMentSql="SELECT ID FROM APPOINTMENT_INFO_TABLE t where t.SERVICEAREAID='"+serviceAreaId+"' AND t.USERID='"+userIdNew+"' AND APPOINTMENTTIME=to_date('"+rollbackTime+"','YYYY-MM-DD') AND t.COMPLETESTATUS='N' AND t.APPOINTMENTTYPE=2 ORDER BY t.CREATETIME ";
                   }
                  if(!PubTools.isNull(appointMentSql)){
                      List appointList = this.mapperI.selectforlist(appointMentSql);
                      if(appointList.size()>0){
                          Map<String,Object> map=(Map<String,Object>)appointList.get(0);
                          int appointId=Integer.parseInt(map.get("ID").toString());
                          String updateAppointSql="UPDATE APPOINTMENT_INFO_TABLE SET COMPLETESTATUS='Y',INTEGRATIONLISTID="+(maxId + 1)+" WHERE ID="+appointId+"";
                          this.mapperI.update(updateAppointSql);
                          LogUtil.WriteLog_Info("积分核减=====修改预约记录为已核销", "QCodeInfoServiceImpl");
                      }
                  }*/
                    LogUtil.WriteLog_Info("积分核减=====消费记录已插入", "QCodeInfoServiceImpl");
                    //3、计算用户可用积分
                    String sql = "select " +
                            " ut.ID ,ut.OPENID ,COALESCE(ut.ENABLEINTEGRATION,0) AS ENABLEINTEGRATION,COALESCE(ut.CPENABLEINTEGRATION,0) AS CPENABLEINTEGRATION,COALESCE(ut.OGENABLEINTEGRATION,0) AS OGENABLEINTEGRATION" +
                            " from WEIXN_USER_TABLE ut " +
                            " where 1=1 AND ut.OPENID='" + openId + "'";
                    List selectforlist1 = this.mapperI.selectforlist(sql);
                    if (selectforlist1.size() > 0) {
                        Object objT = selectforlist1.get(0);
                        Map<String, Object> obj1T = (Map<String, Object>) objT;
                        Double enabledT = Double.parseDouble(obj1T.get("ENABLEINTEGRATION").toString());
                        BigDecimal bd = BigDecimal.valueOf(enabledT - rebateIntegrateSave * 100);
                        bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                        double enabledTI = bd.doubleValue();
                        Double enabledTCp = Double.parseDouble(obj1T.get("CPENABLEINTEGRATION").toString());
                        BigDecimal bdcp = BigDecimal.valueOf(enabledTCp - rebateIntegrateSave * 100);
                        bdcp = bdcp.setScale(1, BigDecimal.ROUND_HALF_UP);
                        double enabledTICp = bdcp.doubleValue();

                        Double enabledTPG = Double.parseDouble(obj1T.get("OGENABLEINTEGRATION").toString());
                        BigDecimal bdcpPG = BigDecimal.valueOf(enabledTPG - rebateIntegrateSave * 100);
                        BigDecimal bdcpPg = bdcpPG.setScale(1, BigDecimal.ROUND_HALF_UP);
                        double enabledTIPG = bdcpPg.doubleValue();
                        if("FP".equals(integrateType) || "FG".equals(integrateType)){
                            String sqlUpdate = "update WEIXN_USER_TABLE SET ENABLEINTEGRATION=" + enabledTI + " ,OGENABLEINTEGRATION=" + enabledTIPG + " " +
                                    " where 1=1 AND OPENID='" + openId + "'";
                            this.mapperI.update(sqlUpdate);
                            enabledIntegral=PubTools.doubleSave1(enabledTIPG / 100)+"";
                            retJo.put("ENABLEINTEGRATION",enabledIntegral);
                        }else if("FC".equals(integrateType) || "FS".equals(integrateType)) {
                            String sqlUpdate = "update WEIXN_USER_TABLE SET ENABLEINTEGRATION=" + enabledTI + " ,CPENABLEINTEGRATION=" + enabledTICp + " " +
                                    " where 1=1 AND OPENID='" + openId + "'";
                            this.mapperI.update(sqlUpdate);
                            enabledIntegral=PubTools.doubleSave1(enabledTICp / 100)+"";
                            retJo.put("ENABLEINTEGRATION", enabledIntegral);
                        }else{

                        }
                        LogUtil.WriteLog_Info("用户更新可用积分完成", "QCodeInfoServiceImpl");
                    }

                    Object contentNew = Consistant.map.get(content);
                    if(!PubTools.isEmpty(contentNew)){
                        Consistant.map.remove(content);
                    }
                    Long l = redisConfigUtil.delIntegral(content);

                    //发送消息
                    String integralTypePu="";
                    if("FP".equals(integrateType)){
                        integralTypePu="加油";
                    }else if("FG".equals(integrateType)){
                        integralTypePu="加气";
                    }else if("FC".equals(integrateType)){
                        integralTypePu="餐饮";
                    }else if("FS".equals(integrateType)){
                        integralTypePu="商超";
                    }
                    this.messagePushServiceImpl.pushMsg(openId,integralTypePu,"-"+consumeIntegral,enabledIntegral);
                }
                ret="1";
                //积分核减成功

            }else{
                if (!content.contains("|")) {
                    //需要判断是否是餐饮预约
                    String appointMentSql = "select t.ID,t.SERVICEOPERATIONID,tt.JOBNUMBER,t.COMPLETESTATUS,wut.OPENID from APPOINTMENT_INFO_TABLE t,SERVICE_AREA_OPERATORS_TABLE tt,WEIXN_USER_TABLE wut where wut.ID=t.USERID  AND t.SERVICEOPERATIONID = tt.ID AND t.ORDERID='" + content + "'";
                    List appointMentList = this.mapperI.selectforlist(appointMentSql);
                    if (appointMentList != null && appointMentList.size() > 0) {
                        Map<String, Object> appointment = (Map<String, Object>) appointMentList.get(0);
                        String appomintJob = appointment.get("JOBNUMBER").toString();
                        String completeStatus = appointment.get("COMPLETESTATUS").toString();
                        openId = appointment.get("OPENID").toString();
                        if ("Y".equals(completeStatus)) {
                            if (!appomintJob.equals(serverOperationId)) {//数据已核销
                                ret = "12";
                                retJo.put("ret", ret);
                                return retJo;
                            }
                        }
                        if (!appomintJob.equals(serverOperationId)) {//说明订单中商户与核销的商户不符
                            ret = "11";
                            retJo.put("ret", ret);
                            return retJo;
                        }
                        //先查询商户角色
                        String serivceOperatorRole = "SELECT saot.ID,saot.USERNAME,saot.ROLEID,saot.SERVICEAREAID,saoc.INPUTMENEY FROM SERVICE_AREA_OPERATORS_TABLE saot,SERVICE_AREA_OPERATORS_COMPANY_TEXT saoc  " +
                                " WHERE saoc.ID = saot.COMPANYID AND saot.JOBNUMBER='" + serverOperationId + "'";
                        List serviceOperatorList = this.mapperI.selectforlist(serivceOperatorRole);
                        if (serviceOperatorList.size() < 1) {//商户不存在
                            ret = "5";
                            retJo.put("ret", ret);
                            return retJo;
                        }
                        //如果是餐饮预约， 则直接改了状态即可
                        String updateAppointSql = "UPDATE APPOINTMENT_INFO_TABLE SET COMPLETESTATUS='Y' WHERE ORDERID='" + content + "'";
                        this.mapperI.update(updateAppointSql);
                        LogUtil.WriteLog_Info("积分核减=====修改预约记录为已核销", "QCodeInfoServiceImpl");
                        ret = "1";
                        retJo.put("openId", openId);
                        retJo.put("ret", ret);
                        return retJo;
                    }
                }else{
                    ret="4";
                    retJo.put("ret",ret);
                    return  retJo;
                }

            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("积分核减操作失败====="+e.getMessage(),"QCodeInfoServiceImpl");
            ret="-1";
            retJo.put("ret",ret);
            //Consistant.map.remove(content);
            retJo.put("code",-1);
            retJo.put("msg","积分核减接口出错");
            retJo.put("data","");
            WebsocketUtil.sendMessage(openId,JSONObject.toJSONString(retJo));
            // WebsocketUtil.removeSession(openId);

            throw new Exception(e);
        }
        retJo.put("ret",ret);
        return retJo;
    }

}
