package com.nmgs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nmgs.mapper.Mapper;
import com.nmgs.service.UserVehicleService;
import com.nmgs.util.ImageUtils;
import com.nmgs.util.LogUtil;
import com.nmgs.util.PropertiesUtil;
import com.nmgs.util.PubTools;
import oracle.sql.CLOB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Blob;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserVehicleServiceImpl implements UserVehicleService {

    @Autowired
    public Mapper mapperI;

    private static String  DBType= PropertiesUtil.getValue("DBType");
    private static String sql="select " +
            " uvt.USERID ,CONCAT(substr( uvt.ACARNO, 1,instr(uvt.ACARNO,'_')-1) || '_',(select text from PLATECOLOR_TEXT where value=substr( uvt.ACARNO, instr(uvt.ACARNO,'_')+1))) AS ACARNONAME ,uvt.CHECKUSERNAME ,uvt.CHECKUSERNUMBER ," +
            " uvt.ACARNO," +
            " uvt.UNPASSINFO," +
            " uvt.CERTIFICATION," +
            " to_char(uvt.CREATETIME,'YYYY-MM-DD HH24:MI:SS') AS CREATETIME,to_char(uvt.CANCELTIME,'YYYY-MM-DD HH24:MI:SS') AS CANCELTIME," +
            " uvt.BAK1,uvt.BAK2,uvt.BAK3,COALESCE(uvt.REFERRERCODE,'') AS REFERRERCODE," +
            " cst.VALUE as CERTIFICATIONNAME" +
            " from user_vehicle_table uvt " +
            " left join certification_status_text  cst on(uvt.CERTIFICATION = cst.ID)" +
            " left join WEIXN_USER_TABLE  ut on(uvt.USERID = ut.ID)" +
            " where 1=1 ";
    static{
        if("4".equals(DBType)){
            sql="select " +
                    " uvt.USERID ,CONCAT(substr( uvt.ACARNO, 1,instr(uvt.ACARNO,'_')-1) , '_',(select text from PLATECOLOR_TEXT where value=substr( uvt.ACARNO, instr(uvt.ACARNO,'_')+1))) AS ACARNONAME ,uvt.CHECKUSERNAME ,uvt.CHECKUSERNUMBER ," +
                    " uvt.ACARNO," +
                    " uvt.UNPASSINFO," +
                    " uvt.CERTIFICATION," +
                    " date_format(uvt.CREATETIME,'%Y-%m-%d %H:%i:%s') AS CREATETIME," +
                    " date_format(uvt.CANCELTIME,'%Y-%m-%d %H:%i:%s') AS CANCELTIME," +
                    " uvt.BAK1,uvt.BAK2,uvt.BAK3,COALESCE(uvt.REFERRERCODE,'') AS REFERRERCODE," +
                    " cst.VALUE as CERTIFICATIONNAME" +
                    " from user_vehicle_table uvt " +
                    " left join certification_status_text  cst on(uvt.CERTIFICATION = cst.ID)" +
                    " left join WEIXN_USER_TABLE  ut on(uvt.USERID = ut.ID)" +
                    " where 1=1 ";
        }

    }
    @Override
    public List getUserVehicleByUserId(String userId, String certification) {
        List list=null;
        List retlist=new ArrayList();
        String sqlTemp=sql;
        try{
            sqlTemp += " and ut.OPENID = '"+userId+"'";
            if(!PubTools.isNull(certification)){
                sqlTemp += " and uvt.CERTIFICATION in ("+certification+")";
            }
            retlist= this.mapperI.selectforlist(sqlTemp);
        }catch (Exception e){
            LogUtil.WriteLog_Error("根据用户id查询车牌失败===>"+e.getMessage(),"UserVehicleServiceImpl");
            return retlist=null;
        }
        return retlist;
    }

    @Override
   // @Transactional(rollbackFor = {Exception.class, RuntimeException.class},propagation = Propagation.REQUIRED)
    public int addUserVehicle(JSONArray jsonArray) {
        int ret=1;
        try{
           String currentDate=PubTools.getCurrentDate();
            if(jsonArray.size()>0){
                String CREATETIME=PubTools.getCurrentDate() ;
                JSONObject joTemp= (JSONObject)jsonArray.get(0);
                //校验用户已经绑定几辆车
                String userid = joTemp.get("USERID").toString();
                String sqlTempO=sql;

                sqlTempO += " and ut.OPENID = '"+userid+"' AND uvt.CERTIFICATION not in(4)";
                List list0= this.mapperI.selectforlist(sqlTempO);
                if(list0.size()>=3){
                    ret=4;//人员最多绑定三辆车
                    return ret;
                }
                for(Object obj:jsonArray){
                    JSONObject jo= (JSONObject)obj;
                    String userId=jo.get("USERID").toString();
                    String aCarNo=jo.get("ACARNO").toString() ;
                    //验证是否已经存在数据
                    String sqlTemp=sql;
                    sqlTemp=sql;//本月是否解绑过
                   // sqlTemp += " and ut.OPENID = '"+userId+"' AND ACARNO='"+aCarNo+"' AND uvt.CERTIFICATION in(4) AND to_char(uvt.CANCELTIME,'YYYY-MM') = substr('"+currentDate+"',1,7)";
                    if("2".equals(DBType)){
                        sqlTemp += " AND ACARNO='"+aCarNo+"' AND uvt.CERTIFICATION in(4) AND to_char(uvt.CANCELTIME,'YYYY-MM') = substr('"+currentDate+"',1,7)";
                    }
                    if("4".equals(DBType)){
                        sqlTemp += " AND ACARNO='"+aCarNo+"' AND uvt.CERTIFICATION in(4) AND date_format(uvt.CANCELTIME,'%Y-%m-%d') = substr('"+currentDate+"',1,7)";
                    }
                    List listNew= this.mapperI.selectforlist(sqlTemp);
                    if(listNew.size()>0){
                        ret=3;//车辆在本月进行解绑，下个月才可以继续绑定
                        break;
                    }
                     sqlTemp=sql;
                    //sqlTemp += " and ut.OPENID = '"+userId+"' AND ACARNO='"+aCarNo+"' AND uvt.CERTIFICATION not in(4)";
                    sqlTemp += " AND ACARNO='"+aCarNo+"' AND uvt.CERTIFICATION not in(4)";
                    List list= this.mapperI.selectforlist(sqlTemp);
                    if(list.size()>0){
                        ret=2;//车辆信息已经存在
                        break;
                    }
                    String sqlTemp2="insert into user_vehicle_table(USERID,ACARNO,CREATETIME,CERTIFICATION) " +
                            " values((SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+userId+"'),'"+aCarNo+"',to_date('"+CREATETIME+"','YYYY-MM-DD HH24:MI:SS'),0) ";
                   if("4".equals(DBType)){
                       sqlTemp2="insert into user_vehicle_table(USERID,ACARNO,CREATETIME,CERTIFICATION) " +
                               " values((SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+userId+"'),'"+aCarNo+"',str_to_date('"+CREATETIME+"','%Y-%m-%d %H:%i:%s'),0) ";
                   }
                    this.mapperI.insert(sqlTemp2);
                }

            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("批量插入车牌失败===>"+e.getMessage(),"UserVehicleServiceImpl");
            ret=-1;
            throw new RuntimeException();
        }
        return ret;
    }

    @Override
    public int cancelUserVehicle(String userId, String aCarNo) {
        int ret=1;
        try{
            String CREATETIME=PubTools.getCurrentDate() ;
            String sqlQuery = "SELECT uvt.USERID,uvt.ACARNO,uvt.CERTIFICATION,uvt.PERMITPICNAME ,uvt.VEHICLEPICNAME ,uvt.LICENSEPICNAME  from user_vehicle_table uvt where uvt.USERID=" + userId + " and uvt.ACARNO='" + aCarNo + "' AND uvt.CERTIFICATION not in(4)";
            List selectforlist = this.mapperI.selectforlist(sqlQuery);
            if(selectforlist.size()>0){
                Map<String, Object> obj1 = (Map<String, Object>)selectforlist.get(0);
                String certification = obj1.get("CERTIFICATION").toString();
                if (Integer.parseInt(certification) != 1) {
                    String sqlDel = "DELETE FROM user_vehicle_table where USERID=" + userId + " and ACARNO='" + aCarNo + "' AND CERTIFICATION not in(1,4)";
                    this.mapperI.update(sqlDel);
                    if (!PubTools.isEmpty(obj1.get("PERMITPICNAME"))) {
                        //需要删除附件
                        ImageUtils.delFile(obj1.get("PERMITPICNAME").toString(), true);
                    }
                    if (!PubTools.isEmpty(obj1.get("VEHICLEPICNAME"))) {
                        //需要删除附件
                        ImageUtils.delFile(obj1.get("VEHICLEPICNAME").toString(), true);
                    }
                    if (!PubTools.isEmpty(obj1.get("LICENSEPICNAME"))) {
                        //需要删除附件
                        ImageUtils.delFile(obj1.get("LICENSEPICNAME").toString(), true);
                    }
                }else{
                    String sqlTemp = "update user_vehicle_table set CERTIFICATION=4,CANCELTIME=to_date('" + CREATETIME + "','YYYY-MM-DD HH24:MI:SS') where USERID=" + userId + " and ACARNO='" + aCarNo + "' AND CERTIFICATION=1";
                    if ("4".equals(DBType)) {
                        sqlTemp = "update user_vehicle_table set CERTIFICATION=4,CANCELTIME=str_to_date('" + CREATETIME + "','%Y-%m-%d %H:%i:%s') where USERID=" + userId + " and ACARNO='" + aCarNo + "' AND CERTIFICATION=1";
                    }
                    this.mapperI.update(sqlTemp);
                }
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("根据用户id和车牌号取消绑定失败===>"+e.getMessage(),"UserVehicleServiceImpl");
            return ret=-1;
        }
        return ret;
    }
    @Override
    public List getUserVehicle(String userId, String aCarNo) {
        List ret=null;
        List retlist=new ArrayList();
        try{
            String sqlTemp="select " +
                    " uvt.USERID ,CONCAT(substr( uvt.ACARNO, 1,instr(uvt.ACARNO,'_')-1) || '_',(select text from PLATECOLOR_TEXT where value=substr( uvt.ACARNO, instr(uvt.ACARNO,'_')+1))) AS ACARNONAME ,uvt.CHECKUSERNAME ,uvt.CHECKUSERNUMBER ," +
                    " uvt.ACARNO,uvt.LICENSEPIC AS LICENSEPIC," +
                    " uvt.PERMITPIC AS PERMITPIC," +
                    " uvt.VEHICLEPIC AS VEHICLEPIC," +
                    " uvt.PERMITPICNAME AS PERMITPICNAME," +
                    " uvt.VEHICLEPICNAME AS VEHICLEPICNAME," +
                    " uvt.LICENSEPICNAME AS LICENSEPICNAME," +
                    " (SELECT IPS.BAK1 FROM INTEGRAL_PUBLIC_SET ips WHERE IPS.PARAMCODE='PICURL') AS PICURL," +
                    " uvt.CERTIFICATION," +
                    " uvt.UNPASSINFO," +
                    " COALESCE(uvt.REFERRERCODE,'') AS REFERRERCODE," +
                    " to_char(uvt.CREATETIME,'YYYY-MM-DD HH24:MI:SS') AS CREATETIME,to_char(uvt.CANCELTIME,'YYYY-MM-DD HH24:MI:SS') AS CANCELTIME," +
                    " uvt.BAK1,uvt.BAK2,uvt.BAK3," +
                    " cst.VALUE as CERTIFICATIONNAME" +
                    " from user_vehicle_table uvt " +
                    " left join certification_status_text  cst on(uvt.CERTIFICATION = cst.ID)" +
                    " left join WEIXN_USER_TABLE  ut on(uvt.USERID = ut.ID)" +
                    " where 1=1 AND uvt.USERID="+userId+" and uvt.ACARNO='"+aCarNo+"'";

            if("4".equals(DBType)){
                sqlTemp="select " +
                        " uvt.USERID ,CONCAT(substr( uvt.ACARNO, 1,instr(uvt.ACARNO,'_')-1) , '_',(select text from PLATECOLOR_TEXT where value=substr( uvt.ACARNO, instr(uvt.ACARNO,'_')+1))) AS ACARNONAME ,uvt.CHECKUSERNAME ,uvt.CHECKUSERNUMBER ," +
                        " uvt.ACARNO,uvt.LICENSEPIC AS LICENSEPIC," +
                        " uvt.PERMITPIC AS PERMITPIC," +
                        " uvt.VEHICLEPIC AS VEHICLEPIC," +
                        " uvt.PERMITPICNAME AS PERMITPICNAME," +
                        " uvt.VEHICLEPICNAME AS VEHICLEPICNAME," +
                        " uvt.LICENSEPICNAME AS LICENSEPICNAME," +
                        " (SELECT IPS.BAK1 FROM INTEGRAL_PUBLIC_SET ips WHERE IPS.PARAMCODE='PICURL') AS PICURL," +
                        " uvt.CERTIFICATION," +
                        " uvt.UNPASSINFO," +
                        " COALESCE(uvt.REFERRERCODE,'') AS REFERRERCODE," +
                        " date_format(uvt.CREATETIME,'%Y-%m-%d %H:%i:%s') AS CREATETIME," +
                        " date_format(uvt.CANCELTIME,'%Y-%m-%d %H:%i:%s') AS CANCELTIME," +
                        " uvt.BAK1,uvt.BAK2,uvt.BAK3," +
                        " cst.VALUE as CERTIFICATIONNAME" +
                        " from user_vehicle_table uvt " +
                        " left join certification_status_text  cst on(uvt.CERTIFICATION = cst.ID)" +
                        " left join WEIXN_USER_TABLE  ut on(uvt.USERID = ut.ID)" +
                        " where 1=1 AND uvt.USERID="+userId+" and uvt.ACARNO='"+aCarNo+"'";
            }
            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("LICENSEPIC");
                    Object oP=obj1.get("PERMITPIC");
                    Object oV=obj1.get("VEHICLEPIC");
                    String s = PubTools.ClobToString(o);
                        if(!PubTools.isNull(s)){
                            obj1.remove("LICENSEPIC");
                            obj1.put("LICENSEPIC", s);
                        }
                    String s2 = PubTools.ClobToString(oP);
                        if(!PubTools.isNull(s2)){
                            obj1.remove("PERMITPIC");
                            obj1.put("PERMITPIC",s2);
                        }
                    String s3 = PubTools.ClobToString(oV);
                        if(!PubTools.isNull(s3)){
                            obj1.remove("VEHICLEPIC");
                            obj1.put("VEHICLEPIC",s);
                        }
                    retlist.add(obj1);
                }
            }


        }catch (Exception e){
            LogUtil.WriteLog_Error("根据用户id和车牌号查询车辆信息失败===>"+e.getMessage(),"UserVehicleServiceImpl");
            return retlist=new ArrayList();
        }
        return retlist;
    }
    @Override
    //@Transactional(rollbackFor = {Exception.class, RuntimeException.class},propagation = Propagation.REQUIRED)
    public int updateUserVehicle(String userId,String aCarNo,String checkName,String checkUserNumber,String licensepic,
                           String permitpic,String  vehiclePic,String certification,String referrerCode) {
        int ret=1;
        try{
            String fileNamePre = userId + "-" + aCarNo + "-";
            String fileNameAfter = ".jpg";
            //图片加水印
            if (!PubTools.isNull(permitpic) && !permitpic.contains("PERPIC")) {
                        String permitpicPic = ImageUtils.addImageWaterMark(permitpic, "仅用于内蒙古交通货运车辆积分会员认证", fileNamePre + "PERPIC" + fileNameAfter);
                        if(!PubTools.isNull(permitpicPic)){
                            permitpic=permitpicPic;
                        }
                    }
            //图片加水印
            if (!PubTools.isNull(licensepic) && !licensepic.contains("LICPIC")) {
                        String permitpicPic = ImageUtils.addImageWaterMark(licensepic, "仅用于内蒙古交通货运车辆积分会员认证", fileNamePre + "LICPIC" + fileNameAfter);
                        if(!PubTools.isNull(permitpicPic)){
                            licensepic=permitpicPic;
                        }
                    }
                //图片加水印
            if (!PubTools.isNull(vehiclePic) && !vehiclePic.contains("VEHPIC")) {
                    String permitpicPic = ImageUtils.addImageWaterMark(vehiclePic, "仅用于内蒙古交通货运车辆积分会员认证", fileNamePre + "VEHPIC" + fileNameAfter);
                    if(!PubTools.isNull(permitpicPic)){
                        vehiclePic=permitpicPic;
                    }
                }
            String sql = "update user_vehicle_table " +
                    " set CERTIFICATION=" + certification + "";
            if ("2".equals(DBType)) {
                sql += ",CREATETIME=to_date('" + PubTools.getCurrentDate() + "','yyyy-MM-dd HH24:mi:ss')";
                if (!PubTools.isNull(licensepic)) {
                    // licensepic = PubTools.StringToClob(licensepic);
                    // sql += ",LICENSEPIC=" + licensepic;
                    sql += ",LICENSEPICNAME='" + PubTools.getCurrentDateYMD() + "/" + fileNamePre + "LICPIC" + fileNameAfter + "'";
                }
                if (!PubTools.isNull(permitpic)) {
                    //  permitpic = PubTools.StringToClob(permitpic);
                    //  sql += ",PERMITPIC=" + permitpic;
                    sql += ",PERMITPICNAME='" + PubTools.getCurrentDateYMD() + "/" + fileNamePre + "PERPIC" + fileNameAfter + "'";
                }
                if (!PubTools.isNull(vehiclePic)) {
                    // vehiclePic = PubTools.StringToClob(vehiclePic);
                    // sql += ",VEHICLEPIC=" + vehiclePic;
                    sql += ",VEHICLEPICNAME='" + PubTools.getCurrentDateYMD() + "/" + fileNamePre + "VEHPIC" + fileNameAfter + "'";
                }
            } else if ("4".equals(DBType)) {
                sql += ",CREATETIME=str_to_date('" + PubTools.getCurrentDate() + "','%Y-%m-%d %H:%i:%s')";
                if (!PubTools.isNull(licensepic)) {
                    // sql += ",LICENSEPIC='" + licensepic + "'";
                    sql += ",LICENSEPICNAME='" + PubTools.getCurrentDateYMD() + "/" + fileNamePre + "LICPIC" + fileNameAfter + "'";
                }
                if (!PubTools.isNull(permitpic)) {
                    // sql += ",PERMITPIC='" + permitpic + "'";
                    sql += ",PERMITPICNAME='" + PubTools.getCurrentDateYMD() + "/" + fileNamePre + "PERPIC" + fileNameAfter + "'";
                }
                if (!PubTools.isNull(vehiclePic)) {
                    //   sql += ",VEHICLEPIC='" + vehiclePic + "'";
                    sql += ",VEHICLEPICNAME='" + PubTools.getCurrentDateYMD() + "/" + fileNamePre + "VEHPIC" + fileNameAfter + "'";
                }
            }
            if (!PubTools.isNull(referrerCode)) {
                sql += ",REFERRERCODE='" + referrerCode + "'";
            }
            if (!PubTools.isNull(checkName)) {
                sql += ",CHECKUSERNAME='" + checkName + "'";
            }
            if (!PubTools.isNull(checkUserNumber) && !checkUserNumber.contains("*")) {
                sql += ",CHECKUSERNUMBER='" + checkUserNumber + "'";
            }
            if (!PubTools.isNull(referrerCode)) {
                sql += ",REFERRERCODE='" + referrerCode + "'";
            }
            sql += " where USERID=" + userId + " and ACARNO='" + aCarNo + "' AND CERTIFICATION not in(4)";

            this.mapperI.insert(sql);
        }catch (Exception e){
            LogUtil.WriteLog_Error("批量修改车牌失败===>"+e.getMessage(),"UserVehicleServiceImpl");
            return ret=-1;
        }
        return ret;
    }
}
