package com.nmgs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.nmgs.entity.Consistant;
import com.nmgs.entity.HttpParamDto;
import com.nmgs.mapper.Mapper;
import com.nmgs.service.AppointmentInfoService;
import com.nmgs.service.IntegralLevelMessageService;
import com.nmgs.service.UserTableService;
import com.nmgs.util.*;
import oracle.sql.CLOB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ApponintmentInfoServiceImpl implements AppointmentInfoService {
    @Autowired
    public Mapper mapperI;
    private static String  DBType= PropertiesUtil.getValue("DBType");

    public UserTableService userTableService;
    @Autowired
    public void setUserTableService(UserTableService userTableService) {
        this.userTableService = userTableService;
    }
    public MessagePushServiceImpl messagePushServiceImpl;
    @Autowired
    public void setMessagePushServiceImpl(MessagePushServiceImpl messagePushServiceImpl) {
        this.messagePushServiceImpl = messagePushServiceImpl;
    }
    private static String sql="SELECT\n" +
            "\tROWNUM AS num,\n" +
            "\tait.ID,\n" +
            "\tsat.AREANAME,\n" +
            "\tsaot.USERNAME,\n" +
            "\tsaot.STROEPIC,\n" +
            "\tTO_CHAR( ait.APPOINTMENTTIME, 'YYYY-MM-DD HH24:MI:SS' ) AS APPOINTMENTTIME,\n" +
            "\tTO_CHAR( ait.CREATETIME, 'YYYY-MM-DD HH24:MI:SS' ) AS CREATETIME,\n" +
            "\tait.TOTALINTEGRAL,\n" +
            "\tait.APPOINTMENTTYPE,\n" +
            "\tait.ORDERID,\n" +
            "\tait.MEALS AS MEALS,\n" +
            "\tait.MEALSCOUNT AS MEALSCOUNT,\n" +
            "\tait.APPOINTMENTLINEID,\n" +
            "\tait.INTEGRATIONLISTID,\n" +
            "\t    CASE WHEN ait.ACARNO IS NULL \n" +
            "            OR ait.ACARNO = '' \n" +
            "            OR ait.ACARNO = 'null' THEN\n" +
            "            '' ELSE to_char(\n" +
            "            substr( ait.ACARNO, 1, instr( ait.ACARNO, '_' ) - 1 ) || '_' || " +
            "            ( SELECT text FROM PLATECOLOR_TEXT WHERE value = substr( ait.ACARNO, instr( ait.ACARNO, '_' ) + 1 ) ) \n" +
            "            ) \n" +
            "            END AS ACARNONAME,\n" +
            "\t(\n" +
            "\tCASE\n" +
            "\t\t\t\n" +
            "\t\t\tWHEN ait.COMPLETESTATUS = 'N' \n" +
            "\t\t\tAND ait.APPOINTMENTTIME >= to_date( '"+PubTools.getCurrentDateYYD()+"', 'yyyy-MM-dd' ) THEN\n" +
            "\t\t\t\t1 \n" +
            "\t\t\t\tWHEN ait.COMPLETESTATUS = 'Y' THEN\n" +
            "\t\t\t\t2 ELSE 3 \n" +
            "\t\t\tEND \n" +
            "\t\t\t) AS COMPLETESTATUS \n" +
            "\t\tFROM\n" +
            "\t\t\tAPPOINTMENT_INFO_TABLE ait\n" +
            "\t\tLEFT JOIN\tSERVICE_AREA_OPERATORS_TABLE saot ON(ait.SERVICEOPERATIONID = saot.ID )\n" +
            "\t\tLEFT JOIN \tSERVICE_AREA_TABLE sat ON(ait.SERVICEAREAID = sat.ID),\n" +
            "\t\tWEIXN_USER_TABLE wut\n" +
            "\t\tWHERE\n" +
            "\t\t\tait.USERID = wut.id " ;
      static{
          if("4".equals(DBType)){
              sql="SELECT\n" +
                      "\tait.ID,\n" +
                      "\tsat.AREANAME,\n" +
                      "\tsaot.USERNAME,\n" +
                      "\tsaot.STROEPIC,\n" +
                      "\tdate_format(ait.APPOINTMENTTIME, '%Y-%m-%d %H:%i:%s') AS APPOINTMENTTIME,\n" +
                      "\tdate_format(ait.CREATETIME, '%Y-%m-%d %H:%i:%s') AS CREATETIME,\n" +
                      "\tait.TOTALINTEGRAL,\n" +
                      "\tait.APPOINTMENTTYPE,\n" +
                      "\tait.ORDERID,\n" +
                      "\tait.MEALS AS MEALS,\n" +
                      "\tait.MEALSCOUNT AS MEALSCOUNT,\n" +
                      "\tait.APPOINTMENTLINEID,\n" +
                      "\tait.INTEGRATIONLISTID,\n" +
                      "\t    CASE WHEN ait.ACARNO IS NULL \n" +
                      "            OR ait.ACARNO = '' \n" +
                      "            OR ait.ACARNO = 'null' THEN\n" +
                      "            '' ELSE  CONCAT(\n" +
                      "            substr( ait.ACARNO, 1, instr( ait.ACARNO, '_' ) - 1 ) , '_',\n" +
                      "            ( SELECT text FROM PLATECOLOR_TEXT WHERE value = substr( ait.ACARNO, instr( ait.ACARNO, '_' ) + 1 ) ) \n" +
                      "            ) \n" +
                      "            END AS ACARNONAME,\n" +
                      "\t(\n" +
                      "\tCASE\n" +
                      "\t\t\t\n" +
                      "\t\t\tWHEN ait.COMPLETESTATUS = 'N' \n" +
                      "\t\t\tAND ait.APPOINTMENTTIME >= str_to_date( '"+PubTools.getCurrentDateYYD()+"', '%Y-%m-%d' ) THEN\n" +
                      "\t\t\t\t1 \n" +
                      "\t\t\t\tWHEN ait.COMPLETESTATUS = 'Y' THEN\n" +
                      "\t\t\t\t2 ELSE 3 \n" +
                      "\t\t\tEND \n" +
                      "\t\t\t) AS COMPLETESTATUS \n" +
                      "\t\tFROM\n" +
                      "\t\t\tAPPOINTMENT_INFO_TABLE ait\n" +
                      "\t\tLEFT JOIN\tSERVICE_AREA_OPERATORS_TABLE saot ON(ait.SERVICEOPERATIONID = saot.ID )\n" +
                      "\t\tLEFT JOIN \tSERVICE_AREA_TABLE sat ON(ait.SERVICEAREAID = sat.ID),\n" +
                      "\t\tWEIXN_USER_TABLE wut\n" +
                      "\t\tWHERE\n" +
                      "\t\t\tait.USERID = wut.id ";
          }
      }

      public static String ordersqlEnd=" order by ait.APPOINTMENTTYPE ,ait.APPOINTMENTTIME DESC,ait.CREATETIME DESC";

    public static String returnSql = "SELECT ID,AREANAME,USERNAME,STROEPIC,APPOINTMENTTIME,CREATETIME,TOTALINTEGRAL,APPOINTMENTTYPE,(SELECT IPS.BAK1 FROM INTEGRAL_PUBLIC_SET ips WHERE IPS.PARAMCODE='PICURL') AS PICURL," +
              "MEALS,MEALSCOUNT,APPOINTMENTLINEID,INTEGRATIONLISTID,ACARNONAME,ORDERID,COMPLETESTATUS,(CASE COMPLETESTATUS WHEN 1 THEN '待使用' WHEN 2 THEN '已使用' ELSE '已过期' END ) AS COMPLETESTATUSNAME ";
    @Override
    public List getList(String id, String orderId, String userId, String appointmentType, String orderSope, int start, int end) {
        List list=null;
        List listRet=new ArrayList();
        String sqlTemp=sql;
        try{
            if(!PubTools.isNull(id)){
                sqlTemp += " and ait.ID = "+id+"";
            }
            if (!PubTools.isNull(orderId)) {
                sqlTemp += " and ait.ORDERID='" + orderId + "'";
            }
            if(!PubTools.isNull(userId)){
                sqlTemp += " AND wut.OPENID='"+userId+"'";
            }
            if(!PubTools.isNull(appointmentType)){
                sqlTemp += " and ait.APPOINTMENTTYPE ="+appointmentType+"";
            }
            if(!PubTools.isNull(orderSope)){
                if("ALL".equals(orderSope)){//全部订单
                    sqlTemp += " AND 1=1";
                }else  if("Y".equals(orderSope)){//已使用
                    sqlTemp += " AND ait.COMPLETESTATUS = 'Y'";
                }else  if("W".equals(orderSope)){//待使用
                    if("2".equals(DBType)){
                        sqlTemp += " AND ait.COMPLETESTATUS = 'N' AND ait.APPOINTMENTTIME >= to_date( '"+PubTools.getCurrentDateYYD()+"', 'yyyy-MM-dd' )";
                    }else   if("4".equals(DBType)){
                        sqlTemp += " AND ait.COMPLETESTATUS = 'N' AND   ait.APPOINTMENTTIME >= str_to_date( '"+PubTools.getCurrentDateYYD()+"', '%Y-%m-%d' )";
                    }

                }else  if("O".equals(orderSope)){//已过期
                    if("2".equals(DBType)){
                        sqlTemp += " AND ait.COMPLETESTATUS = 'N' AND ait.APPOINTMENTTIME < to_date( '"+PubTools.getCurrentDateYYD()+"', 'yyyy-MM-dd' )";
                    }else   if("4".equals(DBType)){
                        sqlTemp += " AND ait.COMPLETESTATUS = 'N' AND   ait.APPOINTMENTTIME < str_to_date( '"+PubTools.getCurrentDateYYD()+"', '%Y-%m-%d' )";
                    }
                }
            }
            if("2".equals(DBType)){
                if(start==0 && end==0){
                    list= this.mapperI.selectforlist(sqlTemp);
                }else{
                    String startSql= returnSql+" FROM("+sqlTemp+" AND ROWNUM >= "+start+""+ordersqlEnd+")tt where tt.num <= "+end;
                    list= this.mapperI.selectforlist(startSql);
                }
            }else if("4".equals(DBType)){//mysql数据库
                if(start>0){
                    sqlTemp +=ordersqlEnd+" Limit "+(start-1)+","+(end-start+1);
                }
                if(start==0 && end==0){
                    list= this.mapperI.selectforlist(sqlTemp);
                }else{
                    String startSql=returnSql+" FROM("+sqlTemp+")tt";
                    list= this.mapperI.selectforlist(startSql);
                }
            }else{}
            if(list != null && list.size()>0){
                if(start==0 && end==0){
                    listRet=list;
                }else{
                    if("2".equals(appointmentType)){//餐饮预约查询需要解析数据
                        for(Object obj:list){
                            Map<String,Object> map=(Map<String,Object>)(obj);
                            String meals=PubTools.isEmpty(map.get("MEALS"))?"":map.get("MEALS").toString();
                            String mealsCount=PubTools.isEmpty(map.get("MEALSCOUNT"))?"":map.get("MEALSCOUNT").toString();
                            JSONArray ja=new JSONArray();
                            if(!PubTools.isNull(meals)){
                                String[] splitMeals = meals.split(",");
                                String[] splitMealCount = mealsCount.split(",");
                                for(int k=0;k<splitMeals.length;k++){
                                    String mealSql = "SELECT  t.ID,t.MEALNAME,t.MEALINFO,t.MEALPIC,t.MEALPRICE,  (SELECT IPS.BAK1 FROM INTEGRAL_PUBLIC_SET ips WHERE IPS.PARAMCODE='PICURL') AS PICURL  FROM SERVICE_AREA_OPERATION_MEAL_TABLE t where t.ID=" + splitMeals[k];
                                    Map<String, Object> select = this.mapperI.select(mealSql);
                                    JSONObject jo=new JSONObject();
                                    jo.put("MEALNAME",select.get("MEALNAME"));
                                    jo.put("MEALCOUNT",splitMealCount[k]);
                                    jo.put("MEALINFO",select.get("MEALINFO"));
                                    jo.put("MEALPIC",PubTools.isEmpty(select.get("MEALPIC"))?"":PubTools.ClobToString(select.get("MEALPIC")));
                                    jo.put("MEALPRICE",select.get("MEALPRICE"));
                                    jo.put("PICURL", select.get("PICURL"));
                                    ja.add(jo);
                                }
                            }
                            String storePic = PubTools.isEmpty(map.get("STROEPIC")) ? "" : PubTools.ClobToString(map.get("STROEPIC"));
                            if (!PubTools.isEmpty(map.get("STROEPIC"))) {
                                map.remove("STROEPIC");
                            }
                            map.put("STROEPIC", storePic);
                            map.put("MEALINFO",ja);
                            listRet.add(map);
                        }
                    }else{
                        listRet=list;
                    }
                }
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("查询预约记录失败===>"+e.getMessage(),"ApponintmentInfoServiceImpl");
            return listRet=null;
        }
        return listRet;
    }

    @Override
    public List getStaList() {
        List ret=null;
        List retlist=new ArrayList();
        try{
            String sqlTemp="SELECT\n" +
                    "\taltt.ID,\n" +
                    "\taltt.LINENAME,\n" +
                    "\taltt.LINEINFO,\n" +
                    "\taltt.NUMBERPIC,\n" +
                    "\tCOALESCE( altt.ENSTATIONID, '' ) AS ENSTATIONID,\n" +
                    "\tCOALESCE( altt.EXSTATIONID, '' ) AS EXSTATIONID \n" +
                    "FROM\n" +
                    "\tAPPOINTMENT_LINE_TABLE altt";
            ret= this.mapperI.selectforlist(sqlTemp);
            if(ret.size()>0){
                for(Object obj:ret){
                    Map<String, Object> obj1 = (Map<String, Object>) obj;
                    Object o=obj1.get("NUMBERPIC");
                        String s = PubTools.ClobToString(o);
                        if(!PubTools.isNull(s)){
                            obj1.remove("NUMBERPIC");
                            obj1.put("NUMBERPIC",s);
                        }else{
                            obj1.remove("NUMBERPIC");
                            obj1.put("NUMBERPIC","");
                        }
                    retlist.add(obj1);
                }
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("查询线路信息失败===>"+e.getMessage(),"ApponintmentInfoServiceImpl");
            return retlist=null;
        }
        return retlist;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
    public JSONObject commit(String openId,String appointmentType,
                             String appointmentId,String aCarNo,
                             String serviceId,String operatorId,
                             String mealId,String mealIdCount,
                             String mealTotalMoney,String dateTime) {
        JSONObject retJo=new JSONObject();
        String ret="-2";// -1 代表接口处理失败 1 处理成功  2 用户不存在 3 兑换积分大于用户可用积分 4 二维码信息过期 5 商户不存在 6 积分类型与消费方式不匹配 7 商户角色未设置 8 用户已冻结
        String jobNumber = "";//商户工号
        try{
            String currentDate=PubTools.getCurrentDate();
            if("2".equals(appointmentType)) {//餐饮预约需要扣除积分
                Map<String, String> mapMealId = new HashMap<String, String>();
                LogUtil.WriteLog_Info("餐饮积分核减操作开始=====" + PubTools.getCurrentDate(), "ApponintmentInfoServiceImpl");
                List userByOpenId = userTableService.getUserByOpenId(openId);
                //查询金额与积分兑换比例
                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 obj = userByOpenId.get(0);
                Map<String, Object> obj1 = (Map<String, Object>) obj;
                String certification = obj1.get("CERTIFICATION").toString();//认证状态
                String ENABLEINTEGRATION = obj1.get("ENABLEINTEGRATION").toString();//用户可用公共积分
                String OGENABLEINTEGRATION = obj1.get("OGENABLEINTEGRATION").toString();//加油、加气可用积分
                String CPENABLEINTEGRATION = obj1.get("CPENABLEINTEGRATION").toString();//餐饮、消费可用积分
                int userIdNew = Integer.parseInt(obj1.get("ID").toString());//人员id
                if ("5".equals(certification)) {//判断用户是否被冻结
                    ret = "8";
                    retJo.put("ret", ret);
                    return retJo;
                }
                double discountMoney = PubTools.isNull(mealTotalMoney)?0.0:Double.parseDouble(mealTotalMoney);
                double rebateIntegrateSave = 0.0;

                //查询预约的套餐总金额，由于可以多选和数量，所以需要遍历
            /*    if (!PubTools.isNull(mealId)) {
                    String[] spliMeal = mealId.split(",");
                    String[] splitCount = mealIdCount.split(",");
                    for (int k = 0; k < spliMeal.length; k++) {
                        mapMealId.put(spliMeal[k], splitCount[k]);
                        String mealSql = "select tt.MEALPRICE AS TOTALMONEY from SERVICE_AREA_OPERATION_MEAL_TABLE tt where tt.ID =" + spliMeal[k];
                        Map<String, Object> select = this.mapperI.select(mealSql);
                        discountMoney += PubTools.isEmpty(select.get("TOTALMONEY")) ? 0.0 : Double.parseDouble(select.get("TOTALMONEY").toString()) * Integer.parseInt(splitCount[k]);
                    }
                }*/

                retJo.put("ENABLEINTEGRATIONBEFORE", PubTools.doubleSave1(Double.parseDouble(CPENABLEINTEGRATION)));
                String sqlFc = sqlTemp.replace("@TYPE@", "FC");//查询餐饮的兑换比例
                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 enabledIntegFc = Double.parseDouble(CPENABLEINTEGRATION);
                if (rebateIntegrateIFcZK > enabledIntegFc) {
                    ret = "3";
                    retJo.put("PAYINTEGRAL", rebateIntegrateIFcZK);
                    retJo.put("RESTINTEGRAL", enabledIntegFc);
                    retJo.put("ret", ret);
                    return retJo;
                } else {
                    //进行积分核减
                    rebateIntegrateSave = rebateIntegrateIFcZK;
                    retJo.put("PAYINTEGRAL", rebateIntegrateIFcZK);
                }

                String serivceOperatorRole = "SELECT saot.ID,saot.USERNAME,saot.ROLEID,saot.JOBNUMBER,saot.SERVICEAREAID FROM SERVICE_AREA_OPERATORS_TABLE saot" +
                        " WHERE  saot.ID=" + operatorId + "";
                List serviceOperatorList = this.mapperI.selectforlist(serivceOperatorRole);
                if (serviceOperatorList != null && serviceOperatorList.size() > 0) {//商户不存在
                    Map<String, Object> oTemp = (Map<String, Object>) serviceOperatorList.get(0);
                    jobNumber = oTemp.get("JOBNUMBER").toString();
                }
                String integralListId = "";//积分流水的ID
                String enabledIntegral = "";//本次消费之后，剩余的餐饮积分
               // if (serviceforlist != null && serviceforlist.size() > 0) {
                    double restEnabled = Double.parseDouble(ENABLEINTEGRATION);
                    double lastEnabled = Double.parseDouble(ENABLEINTEGRATION);
                    double cpEnabled = Double.parseDouble(CPENABLEINTEGRATION);
                   // for (int k = 0; k < serviceforlist.size(); k++) {
                       // Map<String, Object> oTemp = (Map<String, Object>) serviceforlist.get(k);
                        //String serverOperationId = oTemp.get("JOBNUMBER").toString();
                        /*String serverOperationId = operatorId;
                        String mealIds = oTemp.get("MEALIDS").toString();//按照服务区分组的套餐ID
                        String mealPrices = oTemp.get("MEALPRICES").toString();//按照服务区分组的套餐ID

                        String[] splitMeal = mealIds.split(",");
                        String[] splitMealPrice = mealPrices.split(",");
                        double totalConsumeMoney = 0.0;
                        for (int H = 0; H < splitMeal.length; H++) {
                            System.out.println("splitMeal[H]===="+splitMeal[H]);
                            String sMealCount = mapMealId.get(splitMeal[H]);
                            double sMealPrice = Double.parseDouble(splitMealPrice[H]);
                            totalConsumeMoney += Integer.parseInt(sMealCount) * sMealPrice;
                        }*/
                        //double consumeInteger = totalConsumeMoney * rebateInFc;
                        double consumeInteger = rebateIntegrateIFcZK;
                        //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());
                        }
                        restEnabled = restEnabled - consumeInteger;
                        cpEnabled = cpEnabled - consumeInteger;
                        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(lastEnabled * 100) + ",\n" +
                                "\t\t" + PubTools.doubleSave1(consumeInteger * 100) + ",\n" +
                                "\t\t" + PubTools.doubleSave1((restEnabled * 100)) + ",\n" +
                                "\t\tto_date('" + rollbackTime + "','yyyy-MM-dd HH24:mi:ss'),\n" +
                                "\t'FCA', \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(lastEnabled * 100) + ",\n" +
                                    "\t\t" + PubTools.doubleSave1(consumeInteger * 100) + ",\n" +
                                    "\t\t" + PubTools.doubleSave1((restEnabled * 100)) + ",\n" +
                                    "\t\tstr_to_date('" + rollbackTime + "','%Y-%m-%d %H:%i:%s'),\n" +
                                    "\t'FCA', \n";
                        }

                        cafterSql += "\t" + PubTools.doubleSave1(((Double.parseDouble(OGENABLEINTEGRATION)) * 100)) + ", \n" +
                                "\t" + PubTools.doubleSave1(cpEnabled * 100) + " ";
                        cafterSql += "\t)";
                        this.mapperI.insert(cafterSql);
                        lastEnabled = lastEnabled - consumeInteger;
                        if (PubTools.isNull(integralListId)) {
                            integralListId = (maxId + 1) + "";
                        } else {
                            integralListId += "," + (maxId + 1);
                        }
                LogUtil.WriteLog_Info("积分核减=====积分流水已插入", "ApponintmentInfoServiceImpl");
                        //2、新加一条消费记录
                        String sqlIntegralList = "insert into CAFTER_TABLE(ID,\n" +
                                "ACARNO,\n" +
                                "USERID,\n" +
                                "CAFTERTIME,\n" +
                                "USERJOBNUMBER,\n" +
                                "TRIMINTEGRAL," +
                                "INTEGRATIONLISTID,\n" +
                                "ORDERID) values (\n" +
                                "  (select COALESCE(max(t.ID),0)+1 from CAFTER_TABLE t),''," +
                                "" + userIdNew + ",to_date('" + rollbackTime + "','yyyy-MM-dd HH24:mi:ss'),'" + jobNumber + "','SUCCESS'," + (maxId + 1) + ",'" + operatorId + "'" +
                                ")";
                        if ("4".equals(DBType)) {
                            sqlIntegralList = "insert into CAFTER_TABLE(ID,\n" +
                                    "ACARNO,\n" +
                                    "USERID,\n" +
                                    "CAFTERTIME,\n" +
                                    "USERJOBNUMBER,\n" +
                                    "TRIMINTEGRAL," +
                                    "INTEGRATIONLISTID,\n" +
                                    "ORDERID) values (\n" +
                                    "  (select COALESCE(max(t.ID),0)+1 from CAFTER_TABLE t),''," +
                                    "" + userIdNew + ",str_to_date('" + rollbackTime + "','%Y-%m-%d %H:%i:%s'),'" + jobNumber + "','SUCCESS'," + (maxId + 1) + ",'" + jobNumber + "'" +
                                    ")";
                        }
                        this.mapperI.insert(sqlIntegralList);
                LogUtil.WriteLog_Info("积分核减=====消费记录已插入", "ApponintmentInfoServiceImpl");
                   // }
                String currentDate1 = PubTools.getCurrentDateNoStr().replace("-","").trim()+PubTools.getlinkNo();
                String sqlTemp2 = "insert into APPOINTMENT_INFO_TABLE(ID,USERID,ACARNO,APPOINTMENTTYPE,APPOINTMENTTIME,APPOINTMENTLINEID,CREATETIME,SERVICEAREAID,MEALS,MEALSCOUNT,COMPLETESTATUS,INTEGRATIONLISTID,SERVICEOPERATIONID,TOTALINTEGRAL,ORDERID) " +
                        " values((SELECT COALESCE(MAX(ID),0)+1 FROM APPOINTMENT_INFO_TABLE ),(SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='" + openId + "'),'" + aCarNo + "'," + Integer.parseInt(appointmentType) + ",to_date('" + dateTime + "','YYYY-MM-DD HH24:MI:SS')," + (PubTools.isNull(appointmentId) ? -1 : appointmentId) + ",to_date('" + currentDate + "','YYYY-MM-DD HH24:MI:SS')," + (PubTools.isNull(serviceId) ? -1 : serviceId) + ",'" + mealId + "','" + mealIdCount + "','N','" + integralListId + "',"+operatorId+",'"+mealTotalMoney+"','"+currentDate1+"') ";
                if ("4".equals(DBType)) {
                    sqlTemp2 = "insert into APPOINTMENT_INFO_TABLE(ID,USERID,ACARNO,APPOINTMENTTYPE,APPOINTMENTTIME,APPOINTMENTLINEID,CREATETIME,SERVICEAREAID,MEALS,MEALSCOUNT,COMPLETESTATUS,INTEGRATIONLISTID,SERVICEOPERATIONID,TOTALINTEGRAL,ORDERID) " +
                            " values((SELECT COALESCE(MAX(t.ID),0)+1 FROM APPOINTMENT_INFO_TABLE t),(SELECT ID FROM WEIXN_USER_TABLE tt WHERE tt.OPENID='" + openId + "'),'" + aCarNo + "'," + Integer.parseInt(appointmentType) + ",str_to_date('" + dateTime + "','%Y-%m-%d %H:%i:%s')," + (PubTools.isNull(appointmentId) ? -1 : appointmentId) + ",str_to_date('" + currentDate + "','%Y-%m-%d %H:%i:%s')," + (PubTools.isNull(serviceId) ? -1 : serviceId) + ",'" + mealId + "','" + mealIdCount + "','N','" + integralListId + "',"+operatorId+",'"+mealTotalMoney+"','"+currentDate1+"') ";
                }
                this.mapperI.insert(sqlTemp2);
                //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();
                    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);
                    retJo.put("ORDERID", currentDate1);
                    LogUtil.WriteLog_Info("用户更新可用积分完成", "ApponintmentInfoServiceImpl");
                }

                //发送消息
                String consumeIntegral = rebateIntegrateSave + "";
                LogUtil.WriteLog_Info("餐饮预约积分核减已完成=====" + PubTools.getCurrentDate(), "ApponintmentInfoServiceImpl");
                String integralTypePu = "餐饮预约";
                this.messagePushServiceImpl.pushMsg(openId, integralTypePu, "-" + consumeIntegral, enabledIntegral);
            //}
            }else{
                String currentDate1 = PubTools.getCurrentDate().replace("-","").trim()+PubTools.getlinkNo();
                String sqlTemp2="insert into APPOINTMENT_INFO_TABLE(ID,USERID,ACARNO,APPOINTMENTTYPE,APPOINTMENTTIME,APPOINTMENTLINEID,CREATETIME,SERVICEAREAID,MEALS,MEALSCOUNT,COMPLETESTATUS,ORDERID) " +
                        " values((SELECT COALESCE(MAX(ID),0)+1 FROM APPOINTMENT_INFO_TABLE ),(SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+openId+"'),'"+aCarNo+"',"+Integer.parseInt(appointmentType)+",to_date('"+dateTime+"','YYYY-MM-DD HH24:MI:SS'),"+(PubTools.isNull(appointmentId)?-1:appointmentId)+",to_date('"+currentDate+"','YYYY-MM-DD HH24:MI:SS'),"+(PubTools.isNull(serviceId)?-1:serviceId)+",'"+mealId+"','"+mealIdCount+"','N','"+currentDate1+"') ";
                if("4".equals(DBType)){
                    sqlTemp2="insert into APPOINTMENT_INFO_TABLE(ID,USERID,ACARNO,APPOINTMENTTYPE,APPOINTMENTTIME,APPOINTMENTLINEID,CREATETIME,SERVICEAREAID,MEALS,MEALSCOUNT,COMPLETESTATUS,ORDERID) " +
                            " values((SELECT COALESCE(MAX(t.ID),0)+1 FROM APPOINTMENT_INFO_TABLE t),(SELECT ID FROM WEIXN_USER_TABLE tt WHERE tt.OPENID='"+openId+"'),'"+aCarNo+"',"+Integer.parseInt(appointmentType)+",str_to_date('"+dateTime+"','%Y-%m-%d %H:%i:%s'),"+(PubTools.isNull(appointmentId)?-1:appointmentId)+",str_to_date('"+currentDate+"','%Y-%m-%d %H:%i:%s'),"+(PubTools.isNull(serviceId)?-1:serviceId)+",'"+mealId+"','"+mealIdCount+"','N','"+currentDate1+"') ";
                }
                this.mapperI.insert(sqlTemp2);
                retJo.put("ORDERID", currentDate1);
            }
            ret="1";

            retJo.put("ret",ret);
        }catch (Exception e){
            e.printStackTrace();
            LogUtil.WriteLog_Error("预约记录提交失败===>"+e.getMessage(),"ApponintmentInfoServiceImpl");
            ret="-1";
            retJo.put("ret",ret);
            //Consistant.map.remove(content);
            retJo.put("code",-1);
            retJo.put("msg","提交预约记录接口出错");
            retJo.put("data","");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           return  retJo;
        }
        return retJo;
    }

    @Override
    public List getAppointListByServiceId(String serviceAreaId, String operatorId, String beginTime, String endTime, String appointmentType, String isCurrentDateAfter, String refreshDate, String completeStatus) {
        List ret=null;
        List listRet=new ArrayList();
        String sqlTemp=sql;
        try{
            if(!PubTools.isNull(serviceAreaId)){
                sqlTemp += " and ait.SERVICEAREAID = "+serviceAreaId+"";
            }
            if(!PubTools.isNull(operatorId)){
                sqlTemp += " and (saot.ID = '"+operatorId+"' OR saot.JOBNUMBER = '"+operatorId+"') ";
            }
            if(!PubTools.isNull(beginTime)){
                if("2".equals(DBType)){
                    sqlTemp += " and ait.APPOINTMENTTIME >=to_date('"+beginTime+"','YYYY-MM-DD')";
                }
                if("4".equals(DBType)){
                    sqlTemp += " and ait.APPOINTMENTTIME >=str_to_date('"+beginTime+"','%Y-%m-%d')";

                }
            }
            if(!PubTools.isNull(endTime)){
                if("2".equals(DBType)){
                    sqlTemp += " and ait.APPOINTMENTTIME <=to_date('"+endTime+"','YYYY-MM-DD')";
                }
                if("4".equals(DBType)){
                    sqlTemp += " and ait.APPOINTMENTTIME <=str_to_date('"+endTime+"','%Y-%m-%d')";

                }
            }
            if(!PubTools.isNull(appointmentType)){//由于传递的是商户角色，这边需要做匹配
                if(!"ALL".equals(appointmentType)){
                    sqlTemp += " and ait.APPOINTMENTTYPE ="+appointmentType+"  ";
                }else{
                    sqlTemp += " and ait.APPOINTMENTTYPE in(2,3) ";
                }
            }
            if("Y".equals(isCurrentDateAfter)){
                if("2".equals(DBType)) {
                    sqlTemp += " and ait.APPOINTMENTTIME >=to_date('" + PubTools.getCurrentDateYYD() + "','yyyy-MM-dd')";
                }
                if("4".equals(DBType)){
                    sqlTemp += " and ait.APPOINTMENTTIME >=str_to_date('"+PubTools.getCurrentDateYYD()+"','%Y-%m-%d')";
                }
            }
            if(!PubTools.isNull(refreshDate)){
                if("2".equals(DBType)) {
                    sqlTemp += " and ait.CREATETIME >=to_date('" + refreshDate + "','YYYY-MM-DD HH24:MI:SS')";
                }
                if("4".equals(DBType)){
                    sqlTemp += " and ait.CREATETIME >=str_to_date('"+refreshDate+"','%Y-%m-%d %H:%i:%s')";
                }
            }
            if (!PubTools.isNull(completeStatus)) {
                sqlTemp += " and ait.COMPLETESTATUS ='" + completeStatus + "'";
            }
            sqlTemp +=" order by ait.APPOINTMENTTYPE ,ait.APPOINTMENTTIME DESC,ait.CREATETIME DESC";
            ret= this.mapperI.selectforlist(sqlTemp);
            if(ret != null && ret.size()>0){
                    if("2".equals(appointmentType)){//餐饮预约查询需要解析数据
                        JSONArray ja=new JSONArray();
                        for(Object obj:ret){
                            Map<String,Object> map=(Map<String,Object>)(obj);
                            String meals=PubTools.isEmpty(map.get("MEALS"))?"":map.get("MEALS").toString();
                            String mealsCount=PubTools.isEmpty(map.get("MEALSCOUNT"))?"":map.get("MEALSCOUNT").toString();
                            if(!PubTools.isNull(meals)){
                                String[] splitMeals = meals.split(",");
                                String[] splitMealCount = mealsCount.split(",");
                                for(int k=0;k<splitMeals.length;k++){
                                    String mealSql="SELECT  t.ID,t.MEALNAME,t.MEALINFO,t.MEALPIC,t.MEALPRICE FROM SERVICE_AREA_OPERATION_MEAL_TABLE t where t.ID="+splitMeals[k];
                                    Map<String, Object> select = this.mapperI.select(mealSql);
                                    JSONObject jo=new JSONObject();
                                    jo.put("MEALNAME",select.get("MEALNAME"));
                                    jo.put("APPOINTMENTTIME",map.get("APPOINTMENTTIME"));
                                    jo.put("CREATETIME",map.get("CREATETIME"));
                                    jo.put("COMPLETESTATUS", map.get("COMPLETESTATUS"));
                                    jo.put("MEALCOUNT",splitMealCount[k]);
                                    jo.put("MEALINFO",select.get("MEALINFO"));
                                    jo.put("MEALPIC",PubTools.isEmpty(select.get("MEALPIC"))?"":(PubTools.isNull(PubTools.ClobToString(select.get("MEALPIC")))?"":PubTools.ClobToString(select.get("MEALPIC"))));
                                    jo.put("MEALPRICE",select.get("MEALPRICE"));
                                    listRet.add(jo);
                                    // ja.add(jo);
                                }
                            }
                            //map.put("MEALINFO",ja);
                        }
                        //listRet.add(ja);
                    }else{
                        listRet=ret;
                    }
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("给服务区查询预约信息失败===>"+e.getMessage(),"ApponintmentInfoServiceImpl");
            return listRet=null;
        }
        return listRet;
    }

    /**
     *
     * @param openId 用户微信iD
     * @param integrateType 积分类型
     * @param appointMentId 预约ID
     * @return
     */
    @Override
    public String getQcodeInfoById(String openId,  String integrateType, String appointMentId){
        SimpleDateFormat df=new SimpleDateFormat("yyyyMMdd");
        JSONObject jo=new JSONObject();
        jo.put("openId",openId);
        jo.put("integrateType",integrateType);
        jo.put("rebateIntegrate",appointMentId);
        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 serialsT="";
        Random random = new Random();
        int res = 1000+random.nextInt(9000);
        Long seconds = (new Date()).getTime()/1000;
        String dataStr=Long.toHexString(seconds);
        String rebateIntegrateTStr=Integer.toHexString(Integer.parseInt(appointMentId));
        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+"|"+ rebateIntegrateTStr +"|"+resStr;
        //  content=  dateTimes+"|" +serialsT +"|"+rebateIntegrateT+"|"+res;
        LogUtil.WriteLog_Info("用户：" + openId + "---->核销积分类型" + integrateType + "生成的流水号======" + content, "ApponintmentInfoServiceImpl");
        Consistant.map.put(content,jo);
        return content;
    }

    /**
     * 修改已经过期的数据状态为 O
     */

    public void updateCompleteStastus() {
        String selStr = "select t.id  FROM APPOINTMENT_INFO_TABLE t  WHERE t.COMPLETESTATUS='N'";
        String sql = "update APPOINTMENT_INFO_TABLE set COMPLETESTATUS='O' WHERE COMPLETESTATUS='N'";
        if ("2".equals(DBType)) {
            selStr += " and t.APPOINTMENTTIME <to_date('" + PubTools.getCurrentDateYYD() + "','yyyy-MM-dd')";
            sql += " and APPOINTMENTTIME <to_date('" + PubTools.getCurrentDateYYD() + "','yyyy-MM-dd')";
        }
        if ("4".equals(DBType)) {
            selStr += " and t.APPOINTMENTTIME <str_to_date('" + PubTools.getCurrentDateYYD() + "','%Y-%m-%d')";
            sql += " and APPOINTMENTTIME <str_to_date('" + PubTools.getCurrentDateYYD() + "','%Y-%m-%d')";
        }
        List selectforlist = this.mapperI.selectforlist(selStr);
        if (selectforlist != null && selectforlist.size() > 0 && !PubTools.isEmpty(selectforlist.get(0))) {
            this.mapperI.update(sql);
        }
    }

}
