package com.engine.kq.cmd.reportfielddefine;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQReportFieldComInfo;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.LabelUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.util.*;


public class SaveFieldDefineCmd extends AbstractCommonCommand<Map<String, Object>> {

  private SimpleBizLogger logger;
  public SaveFieldDefineCmd(Map<String, Object> params, User user) {
    this.user = user;
    this.params = params;

    this.logger = new SimpleBizLogger();
    BizLogContext logContext = new BizLogContext();
    logContext.setDateObject(new Date());
    logContext.setLogType(BizLogType.HRM_ENGINE);
    logContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQREPORT_DEFINED);
    logContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQREPORT_DEFINED);
    logContext.setParams(params);
    logger.setUser(user);//当前操作人

    String id = Util.null2String(params.get("id"));
    if(id.length()==0)id="-1";
    String mainSql = " select * from kq_report_field where id= " + id;
    logger.setMainSql(mainSql);//主表sql
    logger.setMainPrimarykey("id");//主日志表唯一key
    logger.setMainTargetNameMethod("com.engine.kq.util.KQTransMethod.getLabelName");
    logger.setMethodOtherParams("column:fieldlabel+" + user.getLanguage());
    logger.before(logContext);
  }

  @Override
  public Map<String, Object> execute(CommandContext commandContext) {
    Map<String, Object> retmap = new HashMap<String, Object>();
    RecordSet rs = new RecordSet();
    String sql = "";
    try {
      if (!HrmUserVarify.checkUserRight("KQReportFieldDefine:Add", user)) {
        retmap.put("status", "-1");
        retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
        return retmap;
      }

      String id = Util.null2String(params.get("id"));
      String strFieldlabel = Util.null2String(params.get("fieldlabel"));//展示列名称
      if(this.isDuplicate(strFieldlabel,id)){
        retmap.put("status", "-1");
        retmap.put("message",  SystemEnv.getHtmlLabelName(10000834,weaver.general.Util.getIntValue(user.getLanguage())));
        return retmap;
      }
      String fieldname = Util.null2String(params.get("fieldname"));
      String fieldnameMins = fieldname+"Mins";
      String fielddbtype = Util.null2String(params.get("fielddbtype"));
      fielddbtype = "int";
      int fieldlabel = new LabelUtil().getLabelId(strFieldlabel);
      int fieldlabelMins = fieldlabel;//new LabelUtil().getLabelId(SystemEnv.getHtmlLabelName(fieldlabel, 7)+"时长");
      String fieldtype = Util.null2String(params.get("fieldtype"));//类型
      String fieldvalue = Util.null2String(params.get("fieldvalue"));//区间（分钟）
      String[] arrFieldvalue = Util.splitString(fieldvalue, "-");
      String formula = "";
      String groupid = Util.null2String(params.get("groupid"));
      if(groupid.equals("other")){
        groupid = null;
      }
      boolean validate = true;

      if(arrFieldvalue.length==2) {
        try {
          Integer.parseInt(arrFieldvalue[0].trim());
        } catch (Exception e) {
          validate = false;
        }

        if(validate) {
          try {
            Integer.parseInt(arrFieldvalue[1].trim());
          } catch (Exception e) {
            validate = false;
          }
        }
      }else{
        validate = false;
      }

      if(validate) {
        if (fieldtype.equals("1")) {
          formula = "${beLateMins}>" + arrFieldvalue[0].trim() + " && ${beLateMins}<=" + arrFieldvalue[1].trim() + "?1:0";
        } else if (fieldtype.equals("2")) {
          formula = "${leaveEarlyMins}>" + arrFieldvalue[0].trim() + " && ${leaveEarlyMins}<=" + arrFieldvalue[1].trim() + "?1:0";
        }
      }else{
        retmap.put("status", "-1");
        retmap.put("message", SystemEnv.getHtmlLabelName(517153, user.getLanguage()));
        return  retmap;
      }



      if(id.length()>0){
        sql = "update kq_report_field set fieldlabel=?,formula=? where id=?";
        rs.executeUpdate(sql, fieldlabel, formula, id);

        sql = "update kq_report_field set fieldlabel=? where fieldname=?";
        rs.executeUpdate(sql, fieldlabelMins, fieldnameMins);
      }else{
        boolean flag = false;
        sql = "alter table kq_format_detail add "+fieldname+" "+fielddbtype;
        flag = rs.executeUpdate(sql);

        sql = "alter table kq_format_detail add "+fieldnameMins+" "+fielddbtype;
        flag = rs.executeUpdate(sql);

        sql = "alter table kq_format_total add "+fieldname+" "+fielddbtype;
        flag = rs.executeUpdate(sql);

        sql = "alter table kq_format_total add "+fieldnameMins+" "+fielddbtype;
        flag = rs.executeUpdate(sql);

        if(flag) {
          sql = " insert into kq_report_field(" +
            " fieldname,fieldlabel,width,unittype,parentid,isDefinedColumn,defaultShow,isLeaveType,reportType,isdataColumn,showDetial,groupid,isenable,formula,cascadekey) " +
            " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
          rs.executeUpdate(sql, fieldname, fieldlabel, 65, 3, null, 1, 0, 0, "month", 1, 1, groupid, 1, formula,fieldnameMins);

          rs.executeQuery("select max(id) from kq_report_field") ;
          if(rs.next()){
            id = rs.getString(1);
          }

          String mainSql = " select * from kq_report_field where id= " + id;
          logger.setMainSql(mainSql);//主表sql

          rs.executeUpdate("update kq_report_field set showorder = ? where id= ?",id,id) ;

          sql = " insert into kq_report_field(" +
            " fieldname,fieldlabel,width,unittype,parentid,isDefinedColumn,defaultShow,isLeaveType,reportType,isdataColumn,showDetial,groupid,isenable,formula) " +
            " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
          rs.executeUpdate(sql, fieldnameMins, fieldlabelMins, 65, 2, null, 0, 0, 0, "month", 1, 1, groupid, 1, null);

          rs.executeQuery("select max(id) from kq_report_field") ;
          if(rs.next()){
            id = rs.getString(1);
          }

          rs.executeUpdate("update kq_report_field set showorder = ? where id= ?",id,id) ;
        }else{
          retmap.put("status", "-1");
          retmap.put("message", SystemEnv.getHtmlLabelName(83470, user.getLanguage()));
          return  retmap;
        }
      }


      new KQReportFieldComInfo().removeCache();
      retmap.put("status", "1");
    } catch (Exception e) {
      retmap.put("status", "-1");
      retmap.put("message", SystemEnv.getHtmlLabelName(517153, user.getLanguage()));
      writeLog(e);
    }

    return retmap;
  }


  private boolean isDuplicate(String fieldlabelname, String id){
    boolean isDuplicate = false;
    String sql = "";
    RecordSet rs = new RecordSet();
    List<String> lsFieldlabelName = new ArrayList<>();
    sql = " SELECT fieldlabel,issystem from kq_report_field where reporttype in('all','month') " +
          " and fieldname not in('workingDayOvertime_4leave','restDayOvertime_4leave','holidayOvertime_4leave') and fieldname not like '%Mins'";
    if(id.length()>0){
      sql +=" and id !=?";
      rs.executeQuery(sql,id);
    }else{
      rs.executeQuery(sql);
    }
    while(rs.next()){
      if(Util.null2String(rs.getString("issystem")).equals("1"))continue;
      lsFieldlabelName.add(SystemEnv.getHtmlLabelName(rs.getInt("fieldlabel"), user.getLanguage()));
    }
    if(lsFieldlabelName.contains(fieldlabelname)){
      isDuplicate = true;
    }
    return isDuplicate;
  }

  @Override
  public BizLogContext getLogContext() {
    return null;
  }

  @Override
  public List<BizLogContext> getLogContexts() {
    return logger.getBizLogContexts();
  }
}
