package com.nmgs.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nmgs.mapper.Mapper;
import com.nmgs.service.UserTableService;
import com.nmgs.util.*;
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 UserTableServiceImpl implements UserTableService {
    @Autowired
    public Mapper mapperI;
    private static String  DBType= PropertiesUtil.getValue("DBType");
    private static String sql="select " +
            " ut.ID ,ut.OPENID ,ut.USERNAME ,ut.PHONE ," +
            " ut.REALNAME,substr(ut.IDNUMBER,1,6)||'********'||substr(ut.IDNUMBER,15) AS IDNUMBER," +
            //" ut.NUMBERPIC AS NUMBERPIC," +
            " ut.CERTIFICATION,ut.CREATETIME," +
            " ut.UNPASSINFO," +
            " ROUND((ut.ENABLEINTEGRATION/100),1) AS ENABLEINTEGRATION,ut.REFERRER,ut.BAK1," +
            " ut.BAK2,ut.BAK3,ut.STARLEVEL,ROUND((ut.OILENABLEINTEGRATION/100),1) AS OILENABLEINTEGRATION," +
            " ROUND((ut.GASENABLEINTEGRATION/100),1) AS GASENABLEINTEGRATION," +
            " ROUND((ut.SPENABLEINTEGRATION / 100),1) AS SPENABLEINTEGRATION," +
            " ROUND((ut.CAFENABLEINTEGRATION/100),1) AS CAFENABLEINTEGRATION," +
            " ROUND((ut.OGENABLEINTEGRATION/100),1) AS OGENABLEINTEGRATION," +
            " ROUND((ut.CPENABLEINTEGRATION/100),1) AS CPENABLEINTEGRATION," +
            " ut.NUMBERPICNAME AS NUMBERPICNAME," +
            " ut.REFERRERCODE AS REFERRERCODE," +
            " cst.VALUE as CERTIFICATIONNAME" +
            " from WEIXN_USER_TABLE ut " +
            " left join certification_status_text  cst on(ut.CERTIFICATION = cst.ID)" +
            " where 1=1 ";
    static{
        if("4".equals(DBType)){
            sql="select " +
                    " ut.ID ,ut.OPENID ,ut.USERNAME ,ut.PHONE ," +
                    " ut.REALNAME,concat(substr(ut.IDNUMBER,1,6),'********',substr(ut.IDNUMBER,15)) AS IDNUMBER," +
                    " ut.UNPASSINFO," +
                    " ut.CERTIFICATION,ut.CREATETIME," +
                    " ROUND((ut.ENABLEINTEGRATION/100),1) AS ENABLEINTEGRATION,ut.REFERRER,ut.BAK1," +
                    " ut.BAK2,ut.BAK3,ut.STARLEVEL,ROUND((ut.OILENABLEINTEGRATION/100),1) AS OILENABLEINTEGRATION," +
                    " ROUND((ut.GASENABLEINTEGRATION/100),1) AS GASENABLEINTEGRATION," +
                    " ROUND((ut.SPENABLEINTEGRATION / 100),1) AS SPENABLEINTEGRATION," +
                    " ROUND((ut.CAFENABLEINTEGRATION/100),1) AS CAFENABLEINTEGRATION," +
                    " ROUND((ut.OGENABLEINTEGRATION/100),1) AS OGENABLEINTEGRATION," +
                    " ROUND((ut.CPENABLEINTEGRATION/100),1) AS CPENABLEINTEGRATION," +
                    " ut.REFERRERCODE AS REFERRERCODE," +
                    " ut.NUMBERPICNAME AS NUMBERPICNAME," +
                    " cst.VALUE as CERTIFICATIONNAME" +
                    " from WEIXN_USER_TABLE ut " +
                    " left join certification_status_text  cst on(ut.CERTIFICATION = cst.ID)" +
                    " where 1=1 ";
        }
    }
    @Override
    public List getUserByOpenId(String openId) {
        List retlist=new ArrayList();;
        String sqlTemp=sql;
        try{
            sqlTemp += " and ut.OPENID = '"+openId+"'";
            retlist= this.mapperI.selectforlist(sqlTemp);
        }catch (Exception e){
            LogUtil.WriteLog_Error("根据微信openid查询用户失败===>"+e.getMessage(),"UserTableServiceImpl");
            return null;
        }
        return retlist;
    }

    @Override
    //@Transactional(rollbackFor={RuntimeException.class, Exception.class},propagation= Propagation.REQUIRED)
    public synchronized int addUser(String openId, String userName) {
        int ret=-1;
        //查询全部人员，给list赋值推荐码
        List<String> retlist = new ArrayList();
        if(PubTools.list.size()==0){
            String sqlTempQuery = "select ut.REFERRERCODE AS REFERRERCODE from WEIXN_USER_TABLE ut";
            List list= this.mapperI.selectforlist(sqlTempQuery);
            if(list.size()>0) {
                for (Object obj : list) {
                    Map<String, Object> obj1 = (Map<String, Object>) obj;
                    Object o = PubTools.isEmpty(obj1.get("REFERRERCODE"))?"":obj1.get("REFERRERCODE");
                    retlist.add(o.toString());
                }
            }
        }else{
            retlist=PubTools.list;
        }
        String REFERRERCODE=PubTools.generateRandomCode(6);
        //从redis中获取用户的ID，防止重复
        Object obj = redisConfigUtil.get("USER_ID");
        int userId = 0;
        if (obj != null) {
            userId = Integer.parseInt(obj.toString());
            redisConfigUtil.set("USER_ID", (userId + 1) + "");
        } else {
            Map<String, Object> select = this.mapperI.select("select max(ID) AS MAXID from WEIXN_USER_TABLE");
            if (select != null && select.get("MAXID") != null) {
                userId = Integer.parseInt(select.get("MAXID").toString());
            }
            redisConfigUtil.set("USER_ID", userId + "");
        }
        String sqlTemp="insert into WEIXN_USER_TABLE(ID,OPENID,USERNAME,CREATETIME,ENABLEINTEGRATION,STARLEVEL,OILENABLEINTEGRATION,GASENABLEINTEGRATION," +
                " SPENABLEINTEGRATION,CAFENABLEINTEGRATION,CERTIFICATION,OGENABLEINTEGRATION,CPENABLEINTEGRATION,REFERRERCODE) values(" + (userId + 1) + ",'" + openId + "','" + userName + "',to_date('" + PubTools.getCurrentDate() + "','yyyy-MM-dd HH24:mi:ss'),0,0,0,0,0,0,0,0,0,'" + REFERRERCODE + "')";
        if("4".equals(DBType)){
            sqlTemp="insert into WEIXN_USER_TABLE(ID,OPENID,USERNAME,CREATETIME,ENABLEINTEGRATION,STARLEVEL,OILENABLEINTEGRATION,GASENABLEINTEGRATION," +
                    " SPENABLEINTEGRATION,CAFENABLEINTEGRATION,CERTIFICATION,OGENABLEINTEGRATION,CPENABLEINTEGRATION,REFERRERCODE) values(" + (userId + 1) + ",'" + openId + "','" + userName + "',str_to_date('" + PubTools.getCurrentDate() + "','%Y-%m-%d %H:%i:%s'),0,0,0,0,0,0,0,0,0,'" + REFERRERCODE + "')";
        }
        try{
            ret= this.mapperI.insert(sqlTemp);
            retlist.add(REFERRERCODE);
            PubTools.list=retlist;
        }catch (Exception e){
            LogUtil.WriteLog_Error("根据微信openid新增用户失败===>"+e.getMessage(),"UserTableServiceImpl");
            return ret=-1;
        }
        return ret;
    }

    @Override
   // @Transactional(rollbackFor = {Exception.class, RuntimeException.class},propagation = Propagation.REQUIRED)
    public int updateUser(String userId,String idNumber,String phone,String realName,String numberPic) {
        int ret=-1;
        try{
            //图片加水印
            String fileName = userId + "NUMPIC" + ".jpg";
            LogUtil.WriteLog_Info("用户实名认证修改附件水印=开始===" + PubTools.getCurrentDate() + "====", "UserController");
            if (!PubTools.isNull(numberPic) && !numberPic.contains("NUMPIC")) {
                LogUtil.WriteLog_Info("用户实名认证修改附件水印===IF里面=" + PubTools.getCurrentDate() + "====", "UserController");
                String permitpicPic = ImageUtils.addImageWaterMark(numberPic, "仅用于内蒙古交通货运车辆积分会员认证", fileName);
                LogUtil.WriteLog_Info("用户实名认证修改附件水印=完成===" + PubTools.getCurrentDate() + "====", "UserController");
                if(!PubTools.isNull(permitpicPic)){
                    numberPic=permitpicPic;
                }
            }
            if("2".equals(DBType)){
                numberPic=PubTools.StringToClob(numberPic);
            }
            fileName = PubTools.getCurrentDateYMD() + "/" + fileName;
            String sql="update WEIXN_USER_TABLE " +
                    " set CERTIFICATION=2,CREATETIME=to_date('" + PubTools.getCurrentDate() + "','yyyy-MM-dd HH24:mi:ss'),NUMBERPICNAME='" + fileName + "'";
            if (!PubTools.isNull(realName)) {
                sql += ",REALNAME='" + realName + "'";
            }
            if (!PubTools.isNull(idNumber) && !idNumber.contains("*")) {
                sql += ",IDNUMBER='" + idNumber + "'";
            }
            if (!PubTools.isNull(phone)) {
                sql += ",PHONE='" + phone + "'";
            }
            /*if (!PubTools.isNull(numberPic)) {
                sql += ",NUMBERPIC=" + numberPic + "";
            }*/
            sql += " where OPENID='" + userId + "'";
            if("4".equals(DBType)){
                sql="update WEIXN_USER_TABLE " +
                        " set CERTIFICATION=2,CREATETIME=str_to_date('" + PubTools.getCurrentDate() + "','%Y-%m-%d %H:%i:%s') ,NUMBERPICNAME='" + fileName + "'";
                if (!PubTools.isNull(realName)) {
                    sql += ",REALNAME='" + realName + "'";
                }
                if (!PubTools.isNull(idNumber) && !idNumber.contains("*")) {
                    sql += ",IDNUMBER='" + idNumber + "'";
                }
                if (!PubTools.isNull(phone)) {
                    sql += ",PHONE='" + phone + "'";
                }
               /* if (!PubTools.isNull(numberPic)) {
                    sql += ",NUMBERPIC='" + numberPic + "'";
                }*/

                sql += " where OPENID='" + userId + "'";
            }
            ret=this.mapperI.update(sql);

            //人员实名认证之后，需要积分表中加一条流水

           /* String sqlTemp="insert into integration_list_table(ID,USERID,LASTINTEGRATION,PAYINTEGRATION,RESTINTEGRATION,PAYTIME,PAYTYPE) " +
                    " values((select max(temp.id)+1 from integration_list_table temp),"+userId+",0,(select t.VALUE from pay_integration_number_table t where t.TYPE='AU'),0,to_date('"+PubTools.getCurrentDate()+"','YYYY-MM-DD HH24:MI:SS'),'AU')";
            ret=this.mapperI.insert(sqlTemp);*/

        }catch (Exception e){
            LogUtil.WriteLog_Error("人员实名认证失败===>"+e.getMessage(),"UserTableServiceImpl");
            return ret=-1;
            //throw new RuntimeException();
        }
        return ret;
    }

    @Override
    public List getUserStarByOepnId(String openId) {

        String sqlTemp="select t.ID,t2.OPENID,t2.USERID,t.STAR_LEVEL,COALESCE(t.EQUITY,'') AS EQUITY,t.BAK1,t.BAK2,t.BEGIN_VALUE AS BEGINVALUE,t.END_VALUE AS ENDVALUE from integral_star_setup t , (\n" +
                "\tSELECT\n" +
                "\t\tut.OPENID,\n" +
                "\t\tut.ID AS USERID,\n" +
                "\t\tCOALESCE(sum( t1.PAYINTEGRATION ),0) AS totalinte\n" +
                "\tFROM\n" +
                "\t\n" +
                "\t\tWEIXN_USER_TABLE ut left join \n" +
                "\t\tintegration_list_table t1 on(t1.USERID = ut.ID \n" +
                "\t\tAND substr( t1.PAYTYPE, 1, 1 )= 'A' )\n" +
                "\tWHERE\n" +
                "\t\t1=1\n" +
                "\tGROUP BY\n" +
                "\t\tut.OPENID,ut.ID \n" +
                "\t) t2 where  t2.totalinte >= t.begin_value and  t2.totalinte <t.end_value and t2.OPENID='"+openId+"'";
        List list=null;
        try{
            list= this.mapperI.selectforlist(sqlTemp);
        }catch (Exception e){
            LogUtil.WriteLog_Error("根据微信openid查询用户星级失败===>"+e.getMessage(),"UserTableServiceImpl");
            return list=null;
        }
        return list;
    }


    /**
     * clob转String
     *
     * @param clob
     * @return
     */
    public String ClobToString(Object  clob) throws Exception {
        String reString = "";
        try {
            if(clob instanceof CLOB){
                reString = ((CLOB)clob).getSubString((long) 1, (int) ((CLOB)clob).length());
            }else if(clob instanceof Blob){
                reString = clob.toString();
            }

        } catch (Exception e) {
            LogUtil.WriteLog_Error("Oracle数据由Clob类型转化String类型处理失败====>"+ e.getMessage(),"UserTableServiceImpl");
            throw new Exception("Oracle数据处理失败");
        }
        return reString;
    }


    @Override
    public List getUserDetailByOpenId(String openId) {

        String sqlTemp="select " +
                " ut.ID ,ut.OPENID ,ut.USERNAME ,ut.PHONE ,ut.UNPASSINFO," +
                " ut.REALNAME," ;
               if("2".equals(DBType)){
                   sqlTemp+="substr(ut.IDNUMBER,1,6)||'********'||substr(ut.IDNUMBER,15) AS IDNUMBER ,";
               }else if("4".equals(DBType)){
                   sqlTemp+="concat(substr(ut.IDNUMBER,1,6),'********',substr(ut.IDNUMBER,15)) AS IDNUMBER,";
               }
          sqlTemp+= " ut.NUMBERPIC AS NUMBERPIC," +
                " ut.CERTIFICATION,ut.CREATETIME," +
                " ROUND((ut.ENABLEINTEGRATION/100),1) AS ENABLEINTEGRATION,ut.REFERRER,ut.BAK1," +
                " ut.BAK2,ut.BAK3,ut.STARLEVEL,ROUND((ut.OILENABLEINTEGRATION/100),1) AS OILENABLEINTEGRATION," +
                " ROUND((ut.GASENABLEINTEGRATION/100),1) AS GASENABLEINTEGRATION," +
                " ROUND((ut.SPENABLEINTEGRATION / 100),1) AS SPENABLEINTEGRATION," +
                " ROUND((ut.CAFENABLEINTEGRATION/100),1) AS CAFENABLEINTEGRATION," +
                " ROUND((ut.OGENABLEINTEGRATION/100),1) AS OGENABLEINTEGRATION," +
                " ROUND((ut.CPENABLEINTEGRATION/100),1) AS CPENABLEINTEGRATION," +
                " ut.REFERRERCODE AS REFERRERCODE," +
                  " ut.NUMBERPICNAME AS NUMBERPICNAME," +
                  " (SELECT IPS.BAK1 FROM INTEGRAL_PUBLIC_SET ips WHERE IPS.PARAMCODE='PICURL') AS NUMBERPICURL," +
                " cst.VALUE as CERTIFICATIONNAME" +
                " from WEIXN_USER_TABLE ut " +
                " left join certification_status_text  cst on(ut.CERTIFICATION = cst.ID)" +
                " where 1=1 ";
        List list=null;
        List retlist=new ArrayList();;
        try{
            sqlTemp += " and ut.OPENID = '"+openId+"'";
            list= this.mapperI.selectforlist(sqlTemp);
            if(list.size()>0){
                for(Object obj:list){
                    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);
                        }
                    retlist.add(obj1);
                }
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("根据微信openid查询用户详情失败===>"+e.getMessage(),"UserTableServiceImpl");
            return retlist=null;
        }
        return retlist;
    }

    @Override
    public List checkUserInfo(String PHONE, String IDNUMBER, String REALNAME) {
        List retlist = new ArrayList();
        ;
        String sqlTemp = sql + " AND CERTIFICATION not in(0,2,3)";
        try {
            if (!PubTools.isNull(PHONE) || !PubTools.isNull(IDNUMBER) || !PubTools.isNull(REALNAME)) {
                if (!PubTools.isNull(PHONE)) {
                    sqlTemp += " and ut.PHONE = '" + PHONE + "'";
                }
                if (!PubTools.isNull(IDNUMBER)) {
                    sqlTemp += " and ut.IDNUMBER = '" + IDNUMBER + "'";
                }
                if (!PubTools.isNull(REALNAME)) {
                    sqlTemp += " and ut.REALNAME = '" + REALNAME + "'";
                }
                retlist = this.mapperI.selectforlist(sqlTemp);
            }

        } catch (Exception e) {
            LogUtil.WriteLog_Error("根据用户信息查询失败===>" + e.getMessage(), "UserTableServiceImpl");
            return null;
        }
        return retlist;
    }
}
