package com.nmgs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nmgs.mapper.Mapper;
import com.nmgs.service.IntegralLevelMessageService;
import com.nmgs.service.IntegralSignService;
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 org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class IntegralSignServiceImpl implements IntegralSignService {
    @Autowired
    public Mapper mapperI;
    private static String  DBType= PropertiesUtil.getValue("DBType");
    private String sql="SELECT ist.USERID,\n" +
            "ist.MONTH,\n" +
            "COALESCE(ist.DAY01,'N') AS DAY01,\n" +
            "COALESCE(ist.DAY02,'N') AS DAY02,\n" +
            "COALESCE(ist.DAY03,'N') AS DAY03,\n" +
            "COALESCE(ist.DAY04,'N') AS DAY04,\n" +
            "COALESCE(ist.DAY05,'N') AS DAY05,\n" +
            "COALESCE(ist.DAY06,'N') AS DAY06,\n" +
            "COALESCE(ist.DAY07,'N') AS DAY07,\n" +
            "COALESCE(ist.DAY08,'N') AS DAY08,\n" +
            "COALESCE(ist.DAY09,'N') AS DAY09,\n" +
            "COALESCE(ist.DAY10,'N') AS DAY10,\n" +
            "COALESCE(ist.DAY11,'N') AS DAY11,\n" +
            "COALESCE(ist.DAY12,'N') AS DAY12,\n" +
            "COALESCE(ist.DAY13,'N') AS DAY13,\n" +
            "COALESCE(ist.DAY14,'N') AS DAY14,\n" +
            "COALESCE(ist.DAY15,'N') AS DAY15,\n" +
            "COALESCE(ist.DAY16,'N') AS DAY16,\n" +
            "COALESCE(ist.DAY17,'N') AS DAY17,\n" +
            "COALESCE(ist.DAY18,'N') AS DAY18,\n" +
            "COALESCE(ist.DAY19,'N') AS DAY19,\n" +
            "COALESCE(ist.DAY20,'N') AS DAY20,\n" +
            "COALESCE(ist.DAY21,'N') AS DAY21,\n" +
            "COALESCE(ist.DAY22,'N') AS DAY22,\n" +
            "COALESCE(ist.DAY23,'N') AS DAY23,\n" +
            "COALESCE(ist.DAY24,'N') AS DAY24,\n" +
            "COALESCE(ist.DAY25,'N') AS DAY25,\n" +
            "COALESCE(ist.DAY26,'N') AS DAY26,\n" +
            "COALESCE(ist.DAY27,'N') AS DAY27,\n" +
            "COALESCE(ist.DAY28,'N') AS DAY28,\n" +
            "COALESCE(ist.DAY29,'N') AS DAY29,\n" +
            "COALESCE(ist.DAY30,'N') AS DAY30,\n" +
            "COALESCE(ist.DAY31,'N') AS DAY31\n" +

            " FROM INTEGRAL_SIGN_TABLE  ist where 1=1 ";

    @Override
    public JSONArray getList(String userId, String signDate,int countDay) {
        List list=null;
        String sqlTemp=sql;
        JSONArray ja=new JSONArray();
        try{
            if(!PubTools.isNull(userId)){
                sqlTemp += " and ist.USERID=(SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+userId+"')  ";
            }
            if(!PubTools.isNull(signDate)){
                sqlTemp += " and ist.MONTH ='"+signDate+"'";
            }
            list= this.mapperI.selectforlist(sqlTemp);

            for(int k=1;k<=countDay;k++){
                JSONObject jo=new JSONObject();
                String signStatus="N";
                if(list.size()>0){
                  Map<String,Object> map= (Map<String,Object>) list.get(0);
                  if(k<10){
                       signStatus = map.get("DAY0" + k).toString();
                  }else{
                      signStatus = map.get("DAY" + k).toString();
                  }

                }
                jo.put("name",k);
                jo.put("value",signStatus);
                ja.add(jo);
            }

        }catch (Exception e){
            LogUtil.WriteLog_Error("查询签到记录失败===>"+e.getMessage(),"IntegralSignServiceImpl");
            return ja=null;
        }
        return ja;
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED )
    public int commit(String userId, String signDate) {
        int ret=-1;
        String currentDate = PubTools.getCurrentDate().substring(0,10);

        //判断是否是当前日
        if(!signDate.equals(currentDate)){
           return ret =2;
        }
        try{
            //先查询人员本月是否有签到记录
            String yM=signDate.substring(0,7);
            String date=signDate.substring(8);
            String sqlExists=sql+" AND ist.USERID=(SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+userId+"') AND ist.MONTH ='"+yM+"' ";
            List list= this.mapperI.selectforlist(sqlExists);
            if(list.size()>0){//说明已经有签到记录
                String sqlTemp="UPDATE  INTEGRAL_SIGN_TABLE SET DAY"+date+" ='Y'" +
                        " where USERID=(SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+userId+"') AND MONTH ='"+yM+"'";
                this.mapperI.insert(sqlTemp);
            }else{
                String sqlTemp="insert into INTEGRAL_SIGN_TABLE(USERID,MONTH) " +
                        " values((SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+userId+"'),'"+yM+"') ";
                this.mapperI.insert(sqlTemp);
                String sqlTempUpdate="UPDATE  INTEGRAL_SIGN_TABLE SET DAY"+date+" ='Y'" +
                        " where USERID=(SELECT ID FROM WEIXN_USER_TABLE WHERE OPENID='"+userId+"') AND MONTH ='"+yM+"'";
                this.mapperI.insert(sqlTempUpdate);
            }
            //查询签到一次加多少积分

            String signIntegral="SELECT COALESCE(VALUE,0) AS PAYINTEGRAL FROM PAY_INTEGRATION_NUMBER_TABLE WHERE TYPE='AS'";
            Map<String, Object> select = this.mapperI.select(signIntegral);
            double payIntegral=Double.parseDouble(select.get("PAYINTEGRAL").toString()) ;
            if(payIntegral>0.0){
                String payType="AS";
                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> os =(Map<String,Object>) selectforlistMax.get(0);
                    maxId=Integer.parseInt(os.get("ID").toString()) ;
                }
                String sqlUser="select " +
                        " ut.ID ,ut.OPENID ,COALESCE(ut.ENABLEINTEGRATION,0) AS ENABLEINTEGRATION," +
                        " COALESCE(ut.OGENABLEINTEGRATION,0) AS OGENABLEINTEGRATION," +
                        " COALESCE(ut.CPENABLEINTEGRATION,0) AS CPENABLEINTEGRATION" +
                        " from WEIXN_USER_TABLE ut " +
                        " where 1=1 AND ut.OPENID='"+userId+"'";
                List userByOpenId = this.mapperI.selectforlist(sqlUser);
                int userMainId=0;
                String ENABLEINTEGRATION="0";
                double OGENABLEINTEGRATION=0.0;
                double CPENABLEINTEGRATION=0.0;
                if(userByOpenId.size()>0){
                    Object obj = userByOpenId.get(0);
                    Map<String, Object> obj1 = (Map<String, Object>) obj;
                    userMainId = Integer.parseInt(obj1.get("ID").toString());//用户主键
                    ENABLEINTEGRATION = obj1.get("ENABLEINTEGRATION").toString();//用户可用公共积分
                    OGENABLEINTEGRATION =Double.parseDouble(obj1.get("OGENABLEINTEGRATION").toString()) ;//用户可用加油、加气积分
                    CPENABLEINTEGRATION = Double.parseDouble(obj1.get("CPENABLEINTEGRATION").toString());//用户可用消费积分
                }
                String totalAddIntegralSql="SELECT COALESCE(MAX(ilt.TOTALADDINTEGRATION),0)  AS TOTALADDINTEGRATION FROM INTEGRATION_LIST_TABLE ilt,WEIXN_USER_TABLE ut WHERE ilt.USERID = ut.ID AND ut.ID="+userMainId+"";
                List selectforlistTotalAdd = this.mapperI.selectforlist(totalAddIntegralSql);
                double totalAddIntegral=0.0;
                if(selectforlistTotalAdd.size()>0){
                    Map<String,Object> ot =(Map<String,Object>) selectforlistTotalAdd.get(0);
                    totalAddIntegral =Double.parseDouble(ot.get("TOTALADDINTEGRATION").toString()) ;
                }

                OGENABLEINTEGRATION=  PubTools.doubleSave1(OGENABLEINTEGRATION+payIntegral*0.6);
                CPENABLEINTEGRATION=  PubTools.doubleSave1(CPENABLEINTEGRATION+payIntegral*0.4);
                String cafterSql="INSERT INTO integration_list_table ( ID, USERID, LASTINTEGRATION,TOTALADDINTEGRATION, PAYINTEGRATION, RESTINTEGRATION, PAYTIME, PAYTYPE,CPENABLEINTEGRATION,OGENABLEINTEGRATION )\n" +
                        "VALUES\n" +
                        "\t(\n" +
                        "\t\t"+(maxId+1)+",\n" +
                        "\t\t"+userMainId+"," +
                        "\t\t"+PubTools.doubleSave1(Double.parseDouble(ENABLEINTEGRATION))+",\n" +
                        "\t\t"+PubTools.doubleSave1(totalAddIntegral+payIntegral)+",\n" +
                        "\t\t"+PubTools.doubleSave1(payIntegral)+",\n" +
                        "\t\t"+PubTools.doubleSave1((Double.parseDouble(ENABLEINTEGRATION)+payIntegral))+",\n" +
                        "\t\tto_date('"+PubTools.getCurrentDate()+"','yyyy-MM-dd HH24:mi:ss'),\n" +
                        "\t'"+payType+"',\n" +
                        "\t'"+PubTools.doubleSave1(CPENABLEINTEGRATION)+"', \n" +
                        "\t'"+PubTools.doubleSave1(OGENABLEINTEGRATION)+"' \n" +
                        "\t)";
                this.mapperI.insert(cafterSql);
                LogUtil.WriteLog_Info("人员签到积分流水记录已插入","IntegralSignServiceImpl");
                //3、计算用户可用积分
                String sql="select " +
                        " ut.ID ,ut.OPENID ,COALESCE(ut.ENABLEINTEGRATION,0) AS ENABLEINTEGRATION,COALESCE(ut.CPENABLEINTEGRATION,0) AS CPENABLEINTEGRATION,COALESCE(ut.OGENABLEINTEGRATION,0) AS OGENABLEINTEGRATION" +
                        " from WEIXN_USER_TABLE ut " +
                        " where 1=1 AND ut.ID="+userMainId+"";
                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 + payIntegral);
                    bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                    double enabledTI = bd.doubleValue();

                    Double enabledTCp=Double.parseDouble(obj1T.get("CPENABLEINTEGRATION").toString());
                    BigDecimal bdcp = BigDecimal.valueOf(enabledTCp + payIntegral*0.4);
                    bdcp = bdcp.setScale(1, BigDecimal.ROUND_HALF_UP);
                    double enabledTICp = bdcp.doubleValue();

                    Double enabledTOG=Double.parseDouble(obj1T.get("OGENABLEINTEGRATION").toString());
                    BigDecimal bdco = BigDecimal.valueOf(enabledTOG+payIntegral*0.6);
                    bdco = bdco.setScale(1, BigDecimal.ROUND_HALF_UP);
                    double enabledTIOG =bdco.doubleValue();
                    String sqlUpdate="update WEIXN_USER_TABLE SET ENABLEINTEGRATION="+enabledTI+",CPENABLEINTEGRATION="+enabledTICp+",OGENABLEINTEGRATION="+enabledTIOG+" " +
                            " where 1=1 AND ID="+userMainId+"";
                    this.mapperI.update(sqlUpdate);
                    LogUtil.WriteLog_Info("用户更新可用积分完成","QCodeInfoServiceImpl");
                }
            }

            ret=1;
        }catch (Exception e){
            LogUtil.WriteLog_Error("插入反馈记录失败===>"+e.getMessage(),"IntegralLevelMessageServiceImpl");
            ret=-1;

        }
        return ret;
    }
}
