package com.engine.htsc.common.service.impl;

import com.engine.core.impl.Service;
import com.engine.htsc.common.service.CommonService;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class CommonServiceImpl extends Service implements CommonService {

    private BaseBean bb = new BaseBean();

    @Override
    public Map<String, String> updateData(String tabelName, Map<String,String> conditionMap, Map<String,String>  dataMap){
        Map resultMap = new HashMap();
        RecordSet rs = new RecordSet();
        StringBuilder stringBuilder = new StringBuilder("update ");
        stringBuilder.append(tabelName);
        stringBuilder.append(" set ");
        for (Map.Entry<String, String> entry : dataMap.entrySet()) {
            stringBuilder.append(entry.getKey()+"="+entry.getValue());
            stringBuilder.append(",");
        }
        stringBuilder = new StringBuilder(stringBuilder.substring(0,stringBuilder.length()-1));
        stringBuilder.append(" where ");
        for (Map.Entry<String, String> entry : conditionMap.entrySet()) {
            if (entry.getValue().contains(",")){
                stringBuilder.append(entry.getKey()+" in ("+entry.getValue()+")");
            }else {
                stringBuilder.append(entry.getKey()+"="+entry.getValue());
            }
            stringBuilder.append(" and ");
        }
        String sql = stringBuilder.substring(0,stringBuilder.length()-5);
        boolean bool = rs.executeUpdate(sql);
        if (bool){
            resultMap.put("message","update success");
            resultMap.put("code",200);
        }else {
            resultMap.put("message","update error");
            resultMap.put("code",400);
        }
        return resultMap;
    }

    @Override
    public Map<String, String> recordChange(String tableName,Map<String, String> conditionMap, Map<String, String> dataMap, Map<String, String> changeRecordMap) throws Exception {
        Map resultMap = new HashMap();
        String id = conditionMap.get("id");//数据id
        String selectParam = "";
        String columnName = "";
        String formId = changeRecordMap.get("formId");//表单id
        String modeId = changeRecordMap.get("modeId");//模块id
        String userId = changeRecordMap.get("userId");//操作人用户id
        for (Map.Entry<String, String> entry : dataMap.entrySet()) {
            selectParam = selectParam + entry.getKey() + ",";
            columnName = columnName + "'"+entry.getKey() +"'"+ ",";
        }
        selectParam=selectParam.substring(0,selectParam.length()-1);
        columnName=columnName.substring(0,columnName.length()-1);
        RecordSet rs = new RecordSet();
        //查询老数据sql
        String oldValueSql = "select id,"+selectParam + " from "+tableName+" where id in ("+id+")";
        String[] columns = selectParam.split(",");
        Map<String,String> oldMap = new HashMap<>(); //老数据map
        rs.executeQuery(oldValueSql);
        if (rs.next()){
            for (String column :columns){
                oldMap.put(column,rs.getString(column));
            }
        }

        //查询字段ID方法
        String fieldSql = "select id,fieldname from workflow_billfield where billid="+formId+" and fieldname in ("+columnName+")";
        rs.executeQuery(fieldSql);
        Map<String,String> fieldMap = new HashMap<>();
        while (rs.next()){
            fieldMap.put(rs.getString("fieldname"),rs.getString("id"));
        }
        //插入Modeviewlog_82507语句
        String uuid = UUID.randomUUID().toString();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd&HH:mm:ss");
        String[] date = sdf2.format(new Date()).split("&");
        String insertModeviewsql = "insert into Modeviewlog_"+modeId+"(relatedid,relatedname,operatetype,operatedesc,operateuserid,operatedate,operatetime,clientaddress)values(?,?,?,?,?,?,?,?)";
        Object[] params = {id,"-",5,"状态变更",userId,date[0],date[1],uuid};
        boolean bool = rs.executeUpdate(insertModeviewsql,params);
        if (!bool){
            resultMap.put("message","update error");
            resultMap.put("code",400);
            return resultMap;
        }
        //查询viewlogId
        String viewLogIdsql = "select id from Modeviewlog_"+modeId +" where clientaddress='"+uuid+"'";
        String viewLogId = "";
        rs.executeQuery(viewLogIdsql);
        if (rs.next()){
            viewLogId = rs.getString("id");
        }
        String insertModelog = "insert into modelogfielddetail (viewlogid,fieldid,fieldvalue,prefieldvalue,modeid) values(?,?,?,?,?)";
        for (Map.Entry<String,String> oldEntry:oldMap.entrySet()){
            Object[] modelogParams = {viewLogId,fieldMap.get(oldEntry.getKey()),dataMap.get(oldEntry.getKey()),oldEntry.getValue(),modeId};
            boolean result = rs.executeUpdate(insertModelog,modelogParams);
            if (!result){
                resultMap.put("message","record ChangeData error");
                resultMap.put("code",400);
                return resultMap;
            }
        }
        boolean release = recordChangeVersion(id,dataMap);
        if (!release){
            resultMap.put("message","record ChangeData error");
            resultMap.put("code",400);
            return resultMap;
        }
        resultMap.put("message","record change success");
        resultMap.put("code",200);

        return resultMap;
    }

    /**
     * 插入变更记录版本
     * @param billid
     */
    public boolean recordChangeVersion(String billid,Map<String, String> map){
        try {
            String querySql = "select * from uf_dsfgl where id="+billid;
            Map<String,Object> dataMap = new HashMap<>();
            RecordSet rs = new RecordSet();
            rs.executeQuery(querySql);
            if (rs.next()){
                String[] columNames =  rs.getColumnName();
                for (String str : columNames){
                    dataMap.put(str,rs.getString(str));
                }
            }
            PropBean pb = new PropBean();
            String counterpartySnapshotmodeid = pb.getPropName("counterpartySnapshotmodeid");
            dataMap.put("FORMMODEID",counterpartySnapshotmodeid);
            dataMap.put("FID",billid);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                dataMap.put(entry.getKey().toUpperCase(),entry.getValue().replace("'",""));
            }

            String uuid = UUID.randomUUID().toString();
            dataMap.put("MODEUUID",uuid);
            int dqbb = Integer.valueOf(dataMap.get("DQBB").toString());
            dqbb = dqbb+1;
            String names="";
            String values="";
            for (Map.Entry entry :dataMap.entrySet()){
                names = names + entry.getKey() +",";
                values = values +"'"+entry.getValue()+"'" +",";
            };
            names = names.substring(0,names.length()-1);
            values = values.substring(0,values.length()-1);
            String insertSql = "insert into uf_dsfgl ("+names+") values ("+values+")";
            bb.writeLog("插入语句 insertSql:"+insertSql);
            rs.executeUpdate("update uf_dsfgl set DQBB = ? where id=?", dqbb,billid);
            rs.executeUpdate(insertSql);

            //查询快照版本billid
            rs.executeQuery("select id from uf_dsfgl where modeuuid=?",uuid);
            if (rs.next()){
                String id = rs.getString("id");
                //插入明细表1
                insertDetail("uf_dsfgl_dt1",id,billid);
                //插入明细表2
                insertDetail("uf_dsfgl_dt2",id,billid);
                //插入明细表3
                insertDetail("uf_dsfgl_dt3",id,billid);
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }


    /**
     * 插入明细表
     * @param tableName 明细表名
     * @param id 快照id
     * @param billid 主记录id
     */
    public void insertDetail(String tableName,String id,String billid){
        RecordSet rs = new RecordSet();
        //插入明细表
        String detail1Sql = "select * from "+tableName+" where mainid=?";
        //获取主记录明细表数据
        rs.executeQuery(detail1Sql,billid);
        while (rs.next()){
            Map<String,Object> detail1Map = new HashMap<>();
            String[] columNames =  rs.getColumnName();
            for (String str : columNames){
                detail1Map.put(str,rs.getString(str));
            }
            detail1Map.put("MAINID",id);
            String names="";
            String values="";
            for (Map.Entry entry :detail1Map.entrySet()){
                names = names + entry.getKey() +",";
                values = values +"'"+entry.getValue()+"'" +",";
            };
            names = names.substring(0,names.length()-1);
            values = values.substring(0,values.length()-1);
            //插入快照的明细表
            String insertSql = "insert into "+tableName+" ("+names+") values ("+values+")";
            bb.writeLog("插入明细表"+tableName+":"+insertSql);
            rs.executeUpdate(insertSql);
        }

    }
}
