package com.engine.htxc.contract.util;

import weaver.conn.RecordSet;

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

public class RecordChangeFieldLog {

    /**
     * 插入变更日志表
     * @param tableName 变更的表名
     * @param conditionMap 插入变更日志所需参数
     * @param dataMap 变更字段及对应的值
     * @throws Exception
     */
    public static void recordChange(String tableName, Map<String, String> conditionMap, Map<String, Object> dataMap) throws Exception {
        String id = conditionMap.get("id");//数据id
        String selectParam = "";
        String columnName = "";
        String formId = conditionMap.get("formId");//表单id
        String modeId = conditionMap.get("modeId");//模块id
        String userId = conditionMap.get("userId");//操作人用户id
        String primaryName = conditionMap.get("primaryName");//表的主键名称
        String operateType = conditionMap.get("operateType");//操作类型 1：新建 2：修改 3：删除 4：查看 5:状态变更
        String viewtype = conditionMap.get("viewtype");//0：主表1：从表
        String operateName = "";
        switch (operateType){
            case "1":
                operateName="新建";
                break;
            case "2":
                operateName="修改";
                break;
            case "3":
                operateName="删除";
                break;
            case "5":
                operateName="状态变更";
                break;
        }
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            selectParam = selectParam + entry.getKey().toLowerCase() + ",";
            columnName = columnName + "'"+entry.getKey().toLowerCase() +"'"+ ",";
        }
        selectParam=selectParam.substring(0,selectParam.length()-1);
        columnName=columnName.substring(0,columnName.length()-1);
        RecordSet rs = new RecordSet();
        //查询老数据sql
        String oldValueSql = "select "+selectParam + " from "+tableName+" where "+primaryName+" in ("+id+")";
        String[] columns = selectParam.split(",");
        Map<String,String> oldMap = new HashMap<>(); //老数据map
        rs.executeQuery(oldValueSql);
        if (rs.next()){
            for (String column :columns){
                if ("1".equals(operateType)){//当为新建时
                    oldMap.put(column,"");
                }else {
                    oldMap.put(column,rs.getString(column));
                }
            }
        }

        //查询字段ID方法
        String fieldSql = "select id,fieldname from workflow_billfield where billid="+formId+" and fieldname in ("+columnName+")";
        if (viewtype != null){
            fieldSql = fieldSql + " and viewtype="+viewtype;
        }
        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,"-",operateType,operateName,userId,date[0],date[1],uuid};
        boolean bool = rs.executeUpdate(insertModeviewsql,params);
        //查询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()){
            if (fieldMap.get(oldEntry.getKey()) != null && !"".equals(fieldMap.get(oldEntry.getKey()))){
                Object[] modelogParams = {viewLogId,fieldMap.get(oldEntry.getKey()),dataMap.get(oldEntry.getKey().toUpperCase()),oldEntry.getValue(),modeId};
                boolean result = rs.executeUpdate(insertModelog,modelogParams);
            }
        }
    }
}
