package com.nmgs.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nmgs.mapper.Mapper;
import com.nmgs.service.UserTableService;
import com.nmgs.util.LogUtil;
import com.nmgs.util.PropertiesUtil;
import com.nmgs.util.PubTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class IntegralSeriveImpl {
    @Autowired
    public Mapper mapperI;
    public UserTableService userTableService;
    @Autowired
    public void setUserTableService(UserTableService userTableService) {
        this.userTableService = userTableService;
    }
    private static String  DBType= PropertiesUtil.getValue("DBType");
    public JSONObject getCurrentIntegral(String openId){
        JSONObject json =null;
        try{
            List userByOpenId = this.userTableService.getUserByOpenId(openId);
            if(userByOpenId !=null && userByOpenId.size()>0){
                Map obj=(Map<String, Object>) userByOpenId.get(0);
                if(!PubTools.isEmpty(obj.get("ID"))){
                    json=new JSONObject();
                    json.put("ID",PubTools.isEmpty(obj.get("ID"))?"":obj.get("ID").toString());
                    json.put("OPENID",obj.get("OPENID"));
                    json.put("USERNAME",obj.get("USERNAME"));
                    json.put("PHONE",obj.get("PHONE"));
                    json.put("REALNAME",obj.get("REALNAME"));
                    json.put("IDNUMBER",obj.get("IDNUMBER"));
                    //json.put("NUMBERPIC",PubTools.isEmpty(obj.get("NUMBERPIC"))?"":obj.get("NUMBERPIC").toString());
                    json.put("CERTIFICATION",obj.get("CERTIFICATION"));
                    json.put("CREATETIME",obj.get("CREATETIME"));
                    json.put("ENABLEINTEGRATION",obj.get("ENABLEINTEGRATION"));
                    json.put("OGENABLEINTEGRATION",obj.get("OGENABLEINTEGRATION"));
                    json.put("CPENABLEINTEGRATION",obj.get("CPENABLEINTEGRATION"));
                    //json.put("REFERRER",obj.get("REFERRER"));
                    //json.put("BAK1",obj.get("BAK1"));
                    //json.put("BAK2",obj.get("BAK2"));
                   // json.put("BAK3",obj.get("BAK3"));
                    json.put("OILENABLEINTEGRATION",obj.get("OILENABLEINTEGRATION"));
                    json.put("GASENABLEINTEGRATION",obj.get("GASENABLEINTEGRATION"));
                    json.put("SPENABLEINTEGRATION",obj.get("SPENABLEINTEGRATION"));
                    json.put("CAFENABLEINTEGRATION",obj.get("CAFENABLEINTEGRATION"));
                    json.put("CERTIFICATIONNAME",obj.get("CERTIFICATIONNAME"));
                }
            }else{
                json =new JSONObject();
                json.put("ID",-1);
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("人员信息查询失败====>"+e.getMessage(),"IntegralSeriveImpl");
            return json=null;
        }
        return json;
    }
    public List getIntegraAndMileage(String userId,String aCarNo,String currentDate,String quarter,String queryType){
        List json =null;
        List retjson =new ArrayList();
        try{
         String sqlTemp="SELECT\n" +
                 "  vs.VEHICLEID,\n" +
                 "\tROUND(sum(vs.LENGTH/1000),1) AS MILEAGE,\n" +
                 "\tROUND(sum(vs.SCORE),1) AS INTEGRALTOTAL,\n" +
                 "\t'未上榜' AS CURRENTRANK\n" +
                 "FROM\n" +
                 "\t VEHICLE_SCORE_MONTH vs \n" +
                 "WHERE\n" +
                 "\t1 = 1\n" +
                 "\tand vs.VEHICLEID ='"+aCarNo+"'\n" ;
            if("MONTH".equals(queryType)){
                sqlTemp+="\t\tAND vs.MONTH = '"+currentDate+"' \n" ;
            }else if("YEAR".equals(queryType)){
                sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' \n" ;
            }else if("QUARTER".equals(queryType)){
                if("1".equals(quarter)){//第一季度
                    sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-01'  AND  vs.MONTH <='"+currentDate+"-03'\n" ;
                }else if("2".equals(quarter)){//第二季度
                    sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-04'  AND  vs.MONTH <='"+currentDate+"-06'\n" ;
                }else if("3".equals(quarter)){//第三季度
                    sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-07'  AND  vs.MONTH <='"+currentDate+"-09'\n" ;
                }else if("4".equals(quarter)){//第四季度
                    sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-10'  AND  vs.MONTH <='"+currentDate+"-12'\n" ;
                }else{
                    sqlTemp+=" 1=2 ";
                }
            }
              sqlTemp+=  "\tAND vs.USERID=(SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+userId+"')\n" +
                 "GROUP BY \tvs.VEHICLEID";
            json= this.mapperI.selectforlist(sqlTemp);
            if(json != null){
                List integraRank = this.getIntegraRank(currentDate, quarter, queryType);
                if(integraRank != null && integraRank.size()>0){
                    for(Object obj:json){
                        Map<String,Object> map=(Map<String,Object>)obj;
                        boolean isMatch=false;
                        String rank="未上榜";
                        for(Object objTemp:integraRank){
                            Map<String,Object> mapTemp=(Map<String,Object>)objTemp;
                            if(!PubTools.isEmpty(mapTemp.get("VEHICLEIDTEMP"))){
                                if(aCarNo.equals(mapTemp.get("VEHICLEIDTEMP").toString())){
                                    rank=mapTemp.get("ORDERNO").toString();
                                    break;
                                }
                            }
                        }
                        map.remove("CURRENTRANK");
                        map.put("CURRENTRANK",rank);
                        retjson.add(map) ;
                    }
                }else{
                    retjson=json;
                }

            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("车辆里程记录查询失败====>"+e.getMessage(),"IntegralSeriveImpl");
            return retjson=null;
        }
        return retjson;
    }
    public List getIntegraRank(String currentDate,String quarter,String queryType){
        List json =null;
        try{
            String sqlTemp="SELECT ROWNUM AS\n" +
                    "\tORDERNO,\n" +
                    "\tSUBSTR( VEHICLEID, 1, 3 ) || '***' || SUBSTR( VEHICLEID, 7 ) AS VEHICLEID,\n" +
                    "\tUSERNANE,\n" +
                    "\tVEHICLEIDTEMP AS VEHICLEIDTEMP,"+
                    "\tMILEAGE,\n" +
                    "\tINTEGRALSCORE \n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\tSELECT\n" +
                    "\t\t\tsubstr( vs.VEHICLEID, 1, instr( vs.VEHICLEID, '_' ) - 1 ) AS VEHICLEID,\n" +
                    "\t\t\tvs.VEHICLEID AS VEHICLEIDTEMP,\n" +
                    "\t\t\t(select DISTINCT CASE WHEN LENGTH(COALESCE(wuttemp.REALNAME,''))=2 THEN SUBSTR(wuttemp.REALNAME,1,1)||'*'  WHEN LENGTH(COALESCE(wuttemp.REALNAME,''))=3 THEN SUBSTR(wuttemp.REALNAME,1,1)||'*'||SUBSTR(wuttemp.REALNAME,3) WHEN LENGTH(COALESCE(wuttemp.REALNAME,''))>3 THEN SUBSTR(wuttemp.REALNAME,1,1)||'**'||SUBSTR(wuttemp.REALNAME,4) ELSE wuttemp.REALNAME END FROM USER_VEHICLE_TABLE uvttemp,WEIXN_USER_TABLE wuttemp  where uvttemp.USERID = wuttemp.ID AND uvttemp.CERTIFICATION in(1) AND uvttemp.ACARNO=vs.VEHICLEID) AS USERNANE,"+
                    "\t\tROUND(sum( vs.LENGTH / 1000 ),1) AS MILEAGE,\n" +
                    "\t\tROUND(sum( vs.SCORE ),1) AS INTEGRALSCORE \n" +
                    "\tFROM\n" +
                    "\t\tVEHICLE_SCORE_MONTH vs \n" +
                    "\tWHERE\n" +
                    "\t\t1 = 1 \n" ;
                    if("MONTH".equals(queryType)){
                        sqlTemp+="\t\tAND vs.MONTH = '"+currentDate+"' \n" ;
                    }else if("YEAR".equals(queryType)){
                        sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' \n" ;
                    }else if("QUARTER".equals(queryType)){
                        if("1".equals(quarter)){//第一季度
                            sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-01'  AND  vs.MONTH <='"+currentDate+"-03'\n" ;
                        }else if("2".equals(quarter)){//第二季度
                            sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-04'  AND  vs.MONTH <='"+currentDate+"-06'\n" ;
                        }else if("3".equals(quarter)){//第三季度
                            sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-07'  AND  vs.MONTH <='"+currentDate+"-09'\n" ;
                        }else if("4".equals(quarter)){//第四季度
                            sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-10'  AND  vs.MONTH <='"+currentDate+"-12'\n" ;
                        }else{
                            sqlTemp+=" 1=2 ";
                        }
                    }
            sqlTemp+= "\tGROUP BY\n" +
                    "\t\tvs.VEHICLEID \n" +
                    "\tORDER BY\n" +
                    "\t\tMILEAGE DESC,\n" +
                    "\t\tINTEGRALSCORE DESC \n" +
                    "\t) temp where ROWNUM <=10\n";
            if("4".equals(DBType)){
                sqlTemp="SELECT  ORDERNO AS\n" +
                        "\tORDERNO,\n" +
                        "\tSUBSTR( VEHICLEID, 1, 3 ) || '***' || SUBSTR( VEHICLEID, 7 ) AS VEHICLEID,\n" +
                        "\tUSERNAME AS USRENAME,"+
                        "\tVEHICLEIDTEMP AS VEHICLEIDTEMP,"+
                        "\tMILEAGE,\n" +
                        "\tINTEGRALSCORE \n" +
                        "FROM\n" +
                        "\t(\n" +
                        "\tSELECT\n" +
                        "\t (@row:=@row+1) AS ORDERNO,"+
                        "\t\t\tsubstr( vs.VEHICLEID, 1, instr( vs.VEHICLEID, '_' ) - 1 ) AS VEHICLEID,\n" +
                        "\t\t\tvs.VEHICLEID AS VEHICLEIDTEMP,\n" +
                        "\t\t\t(select DISTINCT CASE WHEN LENGTH(COALESCE(wuttemp.REALNAME,''))=2 THEN SUBSTR(wuttemp.REALNAME,1,1)||'*'  WHEN LENGTH(COALESCE(wuttemp.REALNAME,''))=3 THEN SUBSTR(wuttemp.REALNAME,1,1)||'*'||SUBSTR(wuttemp.REALNAME,3) WHEN LENGTH(COALESCE(wuttemp.REALNAME,''))>3 THEN SUBSTR(wuttemp.REALNAME,1,1)||'**'||SUBSTR(wuttemp.REALNAME,4) ELSE wuttemp.REALNAME END FROM USER_VEHICLE_TABLE uvttemp,WEIXN_USER_TABLE wuttemp  where uvttemp.USERID = wuttemp.ID AND uvttemp.CERTIFICATION in(1) AND uvttemp.ACARNO=vs.VEHICLEID) AS USERNANE,"+
                        "\tvs.VEHICLEID AS USERNAME,"+
                        "\t\tROUND(sum( vs.LENGTH / 1000 ),1) AS MILEAGE,\n" +
                        "\t\tROUND(sum( vs.SCORE ),1) AS INTEGRALSCORE \n" +
                        "\tFROM\n" +
                        "\t\tVEHICLE_SCORE_MONTH vs,(SELECT @row:=0)B \n" +
                        "\tWHERE\n" +
                        "\t\t1 = 1 \n" ;
                if("MONTH".equals(queryType)){
                    sqlTemp+="\t\tAND vs.MONTH = '"+currentDate+"' \n" ;
                }else if("YEAR".equals(queryType)){
                    sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' \n" ;
                }else if("QUARTER".equals(queryType)){
                    if("1".equals(quarter)){//第一季度
                        sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-01'   AND vs.MONTH <='"+currentDate+"-03'\n" ;
                    }else if("2".equals(quarter)){//第二季度
                        sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-04'   AND vs.MONTH <='"+currentDate+"-06'\n" ;
                    }else if("3".equals(quarter)){//第三季度
                        sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-07'   AND vs.MONTH <='"+currentDate+"-09'\n" ;
                    }else if("4".equals(quarter)){//第四季度
                        sqlTemp+="\t\tAND substr(vs.MONTH,1,4) = '"+currentDate+"' AND vs.MONTH >='"+currentDate+"-10'   AND vs.MONTH <='"+currentDate+"-12'\n" ;
                    }else{
                        sqlTemp+=" 1=2 ";
                    }
                }
                sqlTemp+=   "\tGROUP BY\n" +
                        "\t\tvs.VEHICLEID \n" +
                        "\tORDER BY\n" +
                        "\t\tMILEAGE DESC,\n" +
                        "\t\tINTEGRALSCORE DESC \n" +
                        "\t) temp where ORDERNO <=10\n";
            }
            json= this.mapperI.selectforlist(sqlTemp);
        }catch (Exception e){
            LogUtil.WriteLog_Error("车辆里程排名查询失败====>"+e.getMessage(),"IntegralSeriveImpl");
            return json=null;
        }
        return json;
    }

    public List getUserRank(String currentDate){
        List json =null;
        try{
            String sqlTemp="SELECT ROWNUM AS\n" +
                    "\tORDERNO,\n" +
                    "\tREALNAME AS VEHICLEID,\n" +
                    "\tMILEAGE,\n" +
                    "\tINTEGRALSCORE \n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\tSELECT\n" +
                    "\t CASE WHEN LENGTH(COALESCE(ut.REALNAME,''))=2 THEN SUBSTR(ut.REALNAME,1,1)||'*'  WHEN LENGTH(COALESCE(ut.REALNAME,''))=3 THEN SUBSTR(ut.REALNAME,1,1)||'*'||SUBSTR(ut.REALNAME,3) WHEN LENGTH(COALESCE(ut.REALNAME,''))>3 THEN SUBSTR(ut.REALNAME,1,1)||'**'||SUBSTR(ut.REALNAME,4) ELSE ut.REALNAME END REALNAME,\n" +
                    "\t\tROUND( sum( vs.LENGTH / 1000 ), 1 ) AS MILEAGE,\n" +
                    "\t\tROUND( sum( vs.SCORE ), 1 ) AS INTEGRALSCORE \n" +
                    "\tFROM\n" +
                    "\t\tVEHICLE_SCORE_MONTH vs ,WEIXN_USER_TABLE ut \n" +
                    "\tWHERE\n" +
                    "\t\t1 = 1 \n" +
                    "\t\tAND vs.USERID = ut.ID \n" +
                    "\t\tAND ut.CERTIFICATION=1\n" +
                    "\t\tAND vs.MONTH = '"+currentDate+"' \n" +
                    "\tGROUP BY\n" +
                    "\t\tvs.USERID ,\n" +
                    "\t\tut.REALNAME\n" +
                    "\tORDER BY\n" +
                    "\t\tMILEAGE DESC,\n" +
                    "\t\tINTEGRALSCORE DESC \n" +
                    "\t) temp \n" +
                    "WHERE\n" +
                    "\tROWNUM <= 10";


            if("4".equals(DBType)){
                sqlTemp="SELECT (@i:=@i+1) AS\n" +
                        "\tORDERNO,\n" +
                        "\tREALNAME AS VEHICLEID,\n" +
                        "\tMILEAGE,\n" +
                        "\tINTEGRALSCORE \n" +
                        "FROM\n" +
                        "\t(\n" +
                        "\tSELECT\n" +
                        "\t CASE WHEN LENGTH(COALESCE(ut.REALNAME,''))=2 THEN SUBSTR(ut.REALNAME,1,1)||'*'  WHEN LENGTH(COALESCE(ut.REALNAME,''))=3 THEN SUBSTR(ut.REALNAME,1,1)||'*'||SUBSTR(ut.REALNAME,3) WHEN LENGTH(COALESCE(ut.REALNAME,''))>3 THEN SUBSTR(ut.REALNAME,1,1)||'**'||SUBSTR(ut.REALNAME,4) ELSE ut.REALNAME END REALNAME,\n" +
                        "\t\tROUND( sum( vs.LENGTH / 1000 ), 1 ) AS MILEAGE,\n" +
                        "\t\tROUND( sum( vs.SCORE ), 1 ) AS INTEGRALSCORE \n" +
                        "\tFROM\n" +
                        "\t\tVEHICLE_SCORE_MONTH vs ,WEIXN_USER_TABLE ut \n" +
                        "\tWHERE\n" +
                        "\t\t1 = 1 \n" +
                        "\t\tAND vs.USERID = ut.ID \n" +
                        "\t\tAND ut.CERTIFICATION=1\n" +
                        "\t\tAND vs.MONTH = '"+currentDate+"' \n" +
                        "\tGROUP BY\n" +
                        "\t\tvs.USERID ,\n" +
                        "\t\tut.REALNAME\n" +
                        "\tORDER BY\n" +
                        "\t\tMILEAGE DESC,\n" +
                        "\t\tINTEGRALSCORE DESC \n" +
                        "\t) temp,(Select @i:=0) B \n" +
                        "WHERE\n" +
                        "\t(@i+1) <= 10";
            }
            json= this.mapperI.selectforlist(sqlTemp);
        }catch (Exception e){
            LogUtil.WriteLog_Error("用户里程排名查询失败====>"+e.getMessage(),"IntegralSeriveImpl");
            return json=null;
        }
        return json;
    }
    public Double getIntegraByMile(String mileAge,String vehicleType){
        Double ret=0.0;
        List json =null;
        try{
       /*     String sqlTemp="SELECT\n" +
                    "ID,\n" +
                    "VALUE,\n" +
                    "TYPE,\n" +
                    "EVERYMONEY,\n" +
                    "EVERYMILE,\n" +
                    "BEGINMILE,\n" +
                    "INTEGRATIONRULE,\n" +
                    "MILESCORE\n" +
                    "FROM PAY_INTEGRATION_NUMBER_TABLE WHERE TYPE='RAM' ";
            json= this.mapperI.selectforlist(sqlTemp);
            if(json.size()>0){
                Map<String,Object> o =(Map<String,Object>) json.get(0);
                Double BEGINMILE=Double.parseDouble(o.get("BEGINMILE").toString())/1000;//起始里程，大于这个才会有积分
                Double VALUE=Double.parseDouble(o.get("VALUE").toString());
                Double EVERYMILE=Double.parseDouble(o.get("EVERYMILE").toString());
                Double MILESCORE=Double.parseDouble(o.get("MILESCORE").toString())/100;
                if(Double.parseDouble(mileAge)>= BEGINMILE){
                    ret=VALUE/100;
                    ret  =ret+ (Math.floor((Double.parseDouble(mileAge) -BEGINMILE)/(EVERYMILE/1000)) * MILESCORE);
                }
            }*/
            String sqlTemp="SELECT\n" +
                    "SCORE\n" +
                    "FROM VEHICLE_SCORE_VALUE WHERE TYPE='"+vehicleType+"' AND  MINLENGTH <= "+(Double.parseDouble(mileAge)*1000)+" AND MAXLENGTH> "+(Double.parseDouble(mileAge)*1000)+"";
            json= this.mapperI.selectforlist(sqlTemp);
            if(json.size()>0) {
                Map<String, Object> o = (Map<String, Object>) json.get(0);
                ret = Double.parseDouble(o.get("SCORE").toString());
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("公里数查询积分查询失败====>"+e.getMessage(),"IntegralSeriveImpl");
            return -1.0;
        }
        return ret;
    }

    public String getIntegraRule(){
        String ret="";
        List json =null;
        try{
            String sqlTemp="SELECT\n" +
                    "ID,\n" +
                    "INTEGRATIONRULE\n" +
                    "FROM PAY_INTEGRATION_NUMBER_TABLE WHERE TYPE='RI' ";
            json= this.mapperI.selectforlist(sqlTemp);
            if(json.size()>0){
                Map<String,Object> o =(Map<String,Object>) json.get(0);
                ret=o.get("INTEGRATIONRULE").toString();
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("积分规则查询失败====>"+e.getMessage(),"IntegralSeriveImpl");
            return "-1";
        }
        return ret;
    }
}
