package com.engine.kq.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.engine.kq.log.KQLog;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.UUID;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.common.DbFunctionUtil;

/**
 * 打卡数据做一个日志记录表
 */
public class KQCardLogBiz {
  private static KQLog kqLog = new KQLog();

  /**
   * 记录一下打卡相关的信息
   * @param resourceid
   * @param logMap
   * @param workTimeEntityLogMap
   * @param cardtype
   * @return
   */
  public static String logCardInfo(String resourceid, Map<String, Object> logMap,Map<String,Object> workTimeEntityLogMap, String cardtype) {
    KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
    String cardlog_in_table = Util.null2String(kqSettingsComInfo.getMain_val("cardlog_in_table"),"0");
    if("0".equalsIgnoreCase(cardlog_in_table)){
      return "";
    }
    String uuid = UUID.randomUUID().toString();
    try{
      RecordSet rs = new RecordSet();

      String other_info = "";
      if(logMap != null){
        other_info = JSON.toJSONString(logMap,SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect);
      }
      String serial_info = "";
      if(workTimeEntityLogMap != null){
        serial_info = JSON.toJSONString(workTimeEntityLogMap,SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect);
      }
      boolean isok = false;
      if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){
        String sql = "insert into kq_card_log(resourceid,createdatetime,serial_info,other_info,uuid,cardtype) "
            + " values(?,"+DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",empty_clob(),empty_clob(),?,?) ";
        isok = rs.executeUpdate(sql,resourceid,uuid,cardtype);
      }else{
        String sql = "insert into kq_card_log(resourceid,createdatetime,serial_info,other_info,uuid,cardtype) "
            + " values(?,"+DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",?,?,?,?) ";
        boolean isRight = rs.executeUpdate(sql,resourceid,serial_info,other_info,uuid,cardtype);
        kqLog.info("logCardInfo sql:"+sql+":isRight:"+isRight);
      }
      if(isok && rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){
        ConnStatement stat=null;
        try {
          stat = new ConnStatement();
          // 需要使用for update方法来进行更新，
          // 但是，特别需要注意，如果原来CLOB字段有值，需要使用empty_clob()将其清空。
          // 如果原来是null，也不能更新，必须是empty_clob()返回的结果。
          stat.setStatementSql("select serial_info,other_info from kq_card_log where uuid=? for update", false);
          stat.setString(1,uuid);
          stat.executeQuery();
          if (stat.next()) {
            oracle.sql.CLOB serial_clob = (oracle.sql.CLOB) stat.getClob("serial_info");
            Writer serial_outStream = serial_clob.getCharacterOutputStream();
            char[] serial_c = serial_info.toCharArray();
            serial_outStream.write(serial_c, 0, serial_c.length);
            serial_outStream.flush();
            serial_outStream.close();

            oracle.sql.CLOB other_clob = (oracle.sql.CLOB) stat.getClob("other_info");
            Writer other_outStream = other_clob.getCharacterOutputStream();
            char[] other_c = other_info.toCharArray();
            other_outStream.write(other_c, 0, other_c.length);
            other_outStream.flush();
            other_outStream.close();
          }

        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (stat != null) {
            stat.close();
          }
        }
      }
    }catch (Exception e){
      kqLog.info("打卡日志报错:KQCardLogBiz:");
      StringWriter errorsWriter = new StringWriter();
      e.printStackTrace(new PrintWriter(errorsWriter));
      kqLog.info(errorsWriter.toString());
    }
    return uuid;
  }
}
