package com.engine.kq.cmd.shiftmanagement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.KQShiftManagementComInfo;
import com.engine.kq.biz.KQShiftPersonalizedRuleCominfo;
import com.engine.kq.biz.KQShiftPersonalizedRuleDetailComInfo;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

/**
 * 保存班次管理个性化表单
 * @author pzy
 *
 */
public class SaveShiftManagementPersonalizedFormCmd extends AbstractCommonCommand<Map<String, Object>>{

  private SimpleBizLogger logger;

  public SaveShiftManagementPersonalizedFormCmd() {
  }

  public SaveShiftManagementPersonalizedFormCmd(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_SHIFTMANAGER);
    logContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_SHIFTMANAGER);
    logContext.setParams(params);
    logger.setUser(user);//当前操作人
    String datas = Util.null2String(params.get("data"));
    JSONObject jsonObj = JSON.parseObject(datas);
    String serialid = Util.null2String(jsonObj.get("id"));

    if(serialid.length() > 0){
      String mainSql = " select * from kq_ShiftManagement where id= "+serialid +" ";
      logger.setMainSql(mainSql);//主表sql
      logger.setMainPrimarykey("id");//主日志表唯一key
      logger.setMainTargetNameMethod(this.getClass().getName() + ".getTargetName", "column:serial");

      SimpleBizLogger.SubLogInfo subLogInfo = logger.getNewSubLogInfo();
      String subSql = " select * from kq_ShiftPersonalizedRule where serialid= "+serialid +" ";
      subLogInfo.setSubSql(subSql);
      subLogInfo.setGroupId("0");  //所属分组， 按照groupid排序显示在详情中， 不设置默认按照add的顺序。
      subLogInfo.setSubGroupNameLabel(18166); //在详情中显示的分组名称，不设置默认显示明细x
      logger.addSubLogInfo(subLogInfo);

      int personalizedRuleid = 0;
      String idSql = "select id from kq_ShiftPersonalizedRule where serialid=? ";
      RecordSet rs = new RecordSet();
      rs.executeQuery(idSql,serialid);
      if(rs.next()) {
        personalizedRuleid = rs.getInt("id");
      }

      SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo();
      String subSql1 = "select * from kq_ShiftPersonalizedRuleDetail where personalizedruleid="+personalizedRuleid;
      subLogInfo1.setGroupId("1");  //所属分组， 按照groupid排序显示在详情中， 不设置默认按照add的顺序。
      subLogInfo1.setSubGroupNameLabel(388585); //在详情中显示的分组名称，不设置默认显示明细x
      subLogInfo1.setSubSql(subSql1);
      logger.addSubLogInfo(subLogInfo1);

    }
    logger.before(logContext);
	}

	@Override
	public BizLogContext getLogContext() {
		// TODO Auto-generated method stub
		return null;
	}

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

  /**
   * 获取日志对象的名称
   * @param id
   * @param para2
   * @return
   */
  public String getTargetName(String id,String para2){
    try {
      return para2;
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }
  }

	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
    Map<String,Object> retmap = new HashMap<String,Object>();
    RecordSet rs = new RecordSet();
    String datas = Util.null2String(params.get("data"));
    JSONObject jsonObj = JSON.parseObject(datas);
    String serialid = Util.null2String(jsonObj.get("id"));
    if(!HrmUserVarify.checkUserRight("KQClass:Management",user)) {
      retmap.put("status", "-1");
      retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
      return retmap;
    }
    int personalizedRuleid = 0;
    String idSql = "select id from kq_ShiftPersonalizedRule where serialid=? ";
    rs = new RecordSet();
    rs.executeQuery(idSql,serialid);
    if(rs.next()) personalizedRuleid = rs.getInt("id");

    try{
      if(personalizedRuleid > 0){
        edit(retmap,jsonObj,personalizedRuleid);
      }else{
        add(retmap,jsonObj);
      }
      KQShiftPersonalizedRuleCominfo kqShiftPersonalizedRuleCominfo = new KQShiftPersonalizedRuleCominfo();
      KQShiftPersonalizedRuleDetailComInfo ruleDetailComInfo = new KQShiftPersonalizedRuleDetailComInfo();

      kqShiftPersonalizedRuleCominfo.removeCache();
      ruleDetailComInfo.removePersonalizedRuleDetailCache();
    }catch (Exception e){
      retmap.put("status", "-1");
      retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
      writeLog(e);
    }

    return retmap;
	}

  /**
   * 编辑个性化信息
   * @param retmap
   * @param jsonObj
   * @param personalizedRuleid
   */
  private void edit(Map<String,Object> retmap,JSONObject jsonObj,int personalizedRuleid) throws Exception{
    RecordSetTrans rst = new RecordSetTrans();
    String dbType = rst.getDBType();
    rst.setAutoCommit(true);
    RecordSet rs = new RecordSet();
    String serialid = Util.null2String(jsonObj.get("id"));//本信息id
    String permitLateMinutes= Util.null2String(jsonObj.get("permitlateminutes"));//允许迟到分钟数
    String seriousLateMinutes = Util.null2String(jsonObj.get("seriouslateminutes"));//严重迟到分钟数
    String lateAbsentMinutes= Util.null2String(jsonObj.get("lateabsentminutes"));//迟到视作旷工分钟数
    String permitLeaveEarlyMinutes= Util.null2String(jsonObj.get("permitleaveearlyminutes"));//允许早退分钟数
    String seriousLeaveEarlyMinutes = Util.null2String(jsonObj.get("seriousleaveearlyminutes"));//严重早退分钟数
    String leaveEarlyAbsentMinutes= Util.null2String(jsonObj.get("leaveearlyabsentminutes"));//早退视作旷工分钟数
    String enableexcludelate = Util.null2String(jsonObj.get("enableexcludelate"));//是否排除迟到分钟数
    String enableexcludeleaveearly= Util.null2String(jsonObj.get("enableexcludeleaveearly"));//是否排除早退分钟数

    String permitlateminutesenable = Util.null2String(jsonObj.get("permitlateminutesenable"));//允许迟到是否开启
    String seriouslateminutesenable= Util.null2String(jsonObj.get("seriouslateminutesenable"));///严重迟到是否开启
    String lateabsentminutesenable = Util.null2String(jsonObj.get("lateabsentminutesenable"));//迟到视作旷工是否开启
    String permitleaveearlyminutesenable = Util.null2String(jsonObj.get("permitleaveearlyminutesenable"));///允许早退是否开启
    String seriousleaveearlyminutesenable= Util.null2String(jsonObj.get("seriousleaveearlyminutesenable"));//严重早退是否开启
    String leaveearlyabsentminutesenable = Util.null2String(jsonObj.get("leaveearlyabsentminutesenable"));//早退视作旷工是否开启

    String earlyinearlyout = Util.null2String(jsonObj.get("earlyinearlyout"));//允许早到早走是否开启
    String lateinlateout = Util.null2String(jsonObj.get("lateinlateout"));//允许晚到晚走是否开启
    String lateoutlatein = Util.null2String(jsonObj.get("lateoutlatein"));//允许晚走晚到是否开启

    JSONObject personalizedRuleDetails = (JSONObject)jsonObj.get("personalizedRuleDetails");
    checkRule(personalizedRuleDetails,retmap,jsonObj);
    if(!retmap.isEmpty()){
      return ;
    }

    String mainSql = "update kq_ShiftPersonalizedRule set permitlateminutes=?,seriouslateminutes=?,lateabsentminutes=?, "
        + "permitleaveearlyminutes=?,seriousleaveearlyminutes=?,leaveearlyabsentminutes=?,permitlatestatus=?, "
        + "seriouslatestatus=?,lateabsentstatus=?,permitleaveearlystatus=?,seriousleaveearlystatus=?,leaveearlyabsentstatus=?, "
        + "enableexcludelate=?,enableexcludeleaveearly=? "
        + " where serialid = ? ";

    boolean isUpdated = rs.executeUpdate(mainSql, permitLateMinutes,seriousLateMinutes,lateAbsentMinutes,permitLeaveEarlyMinutes,
        seriousLeaveEarlyMinutes,leaveEarlyAbsentMinutes,permitlateminutesenable,seriouslateminutesenable,lateabsentminutesenable,
        permitleaveearlyminutesenable,seriousleaveearlyminutesenable,leaveearlyabsentminutesenable,
        enableexcludelate,enableexcludeleaveearly,serialid);

    if(isUpdated){
      //对于个性化规则，直接删除重新创建
      String delRuleSql = "delete from kq_ShiftPersonalizedRuleDetail where personalizedruleid = ? ";
      rst.executeUpdate(delRuleSql, personalizedRuleid);

      String ruleSql = "insert into kq_ShiftPersonalizedRuleDetail(personalizedruleid,enable,enablesame,advancetime,postponetime,ruledetailtype,record) values(?,?,?,?,?,?,?)";
      String[] rules = new String[]{"earlyinearlyout","lateinlateout","lateoutlatein"};
      for(int j = 0 ; j < rules.length ; j++){
        String ruledetailtype=rules[j];
        if(!"lateoutlatein".equalsIgnoreCase(ruledetailtype)){
          JSONObject ruledetail = (JSONObject)personalizedRuleDetails.get(ruledetailtype);
          String enable=Util.null2String(jsonObj.get(ruledetailtype));
          String enablesame=Util.null2String(jsonObj.get(ruledetailtype+"same"));
          String advanceTime=Util.null2String(ruledetail.get("advancetime"));
          String postponeTime=Util.null2String(ruledetail.get("postponetime"));
          if(enablesame.equals("1")){
            postponeTime = advanceTime;
          }
          String record=Util.null2s(Util.null2String(ruledetail.get("record")),"0");
		  if("mysql".equals(dbType) && "".equals(enablesame)){
              enablesame = null;
          }
          rst.executeUpdate(ruleSql, personalizedRuleid,enable,enablesame,advanceTime,postponeTime,ruledetailtype,record);
        }else{
          JSONArray ruledetails = (JSONArray)personalizedRuleDetails.get(ruledetailtype);
          for(int k =0 ; k < ruledetails.size() ; k ++){
            JSONObject ruledetail = (JSONObject)ruledetails.get(k);
            String enable=Util.null2String(jsonObj.get(ruledetailtype));
            String enablesame=Util.null2String(jsonObj.get(ruledetailtype+"same"));
            String advanceTime=Util.null2String(ruledetail.get("advancetime"));
            String postponeTime=Util.null2String(ruledetail.get("postponetime"));
            if(enablesame.equals("1")){
              postponeTime = advanceTime;
            }
            String record=Util.null2s(Util.null2String(ruledetail.get("record")),"0");
            if("mysql".equals(dbType) && "".equals(enablesame)){
              enablesame = null;
            }
            rst.executeUpdate(ruleSql, personalizedRuleid,enable,enablesame,advanceTime,postponeTime,ruledetailtype,record);
          }
        }
      }
      retmap.put("status", "1");
      retmap.put("id", serialid);
      retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage()));
    }else{
      retmap.put("status", "-1");
      retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
    }
  }

  private void checkRule(JSONObject personalizedRuleDetails,
      Map<String, Object> retmap, JSONObject jsonObj) {
    Map<String,String> checkRule = new HashMap<>();
    JSONArray lateoutlatein_ruledetail = (JSONArray)personalizedRuleDetails.get("lateoutlatein");
    for(int k =0 ; k < lateoutlatein_ruledetail.size() ; k ++){
      JSONObject ruledetail = (JSONObject)lateoutlatein_ruledetail.get(k);
      String enable=Util.null2String(jsonObj.get("lateoutlatein"));
      if("1".equalsIgnoreCase(enable)){
        String advancetime=Util.null2String(ruledetail.get("advancetime"));
        if(checkRule.containsKey(advancetime)){
          retmap.put("status", "-1");
          retmap.put("message",  SystemEnv.getHtmlLabelName(514788,user.getLanguage()));
          break;
        }else{
          checkRule.put(advancetime, advancetime);
        }
      }
    }
  }

  /**
   * 新增个性化信息
   * @param retmap
   * @param jsonObj
   */
  private void add(Map<String,Object> retmap,JSONObject jsonObj) throws Exception{
    RecordSetTrans rst = new RecordSetTrans();
    String dbType = rst.getDBType();
    rst.setAutoCommit(true);
    RecordSet rs = new RecordSet();
    String serialid = Util.null2String(jsonObj.get("id"));//本信息id
    String permitLateMinutes= Util.null2String(jsonObj.get("permitlateminutes"));//允许迟到分钟数
    String seriousLateMinutes = Util.null2String(jsonObj.get("seriouslateminutes"));//严重迟到分钟数
    String lateAbsentMinutes= Util.null2String(jsonObj.get("lateabsentminutes"));//迟到视作旷工分钟数
    String permitLeaveEarlyMinutes= Util.null2String(jsonObj.get("permitleaveearlyminutes"));//允许早退分钟数
    String seriousLeaveEarlyMinutes = Util.null2String(jsonObj.get("seriousleaveearlyminutes"));//严重早退分钟数
    String leaveEarlyAbsentMinutes= Util.null2String(jsonObj.get("leaveearlyabsentminutes"));//早退视作旷工分钟数
    String enableexcludelate = Util.null2String(jsonObj.get("enableexcludelate"));//是否排除迟到分钟数
    String enableexcludeleaveearly= Util.null2String(jsonObj.get("enableexcludeleaveearly"));//是否排除早退分钟数

    String permitlateminutesenable = Util.null2String(jsonObj.get("permitlateminutesenable"));//允许迟到是否开启
    String seriouslateminutesenable= Util.null2String(jsonObj.get("seriouslateminutesenable"));///严重迟到是否开启
    String lateabsentminutesenable = Util.null2String(jsonObj.get("lateabsentminutesenable"));//迟到视作旷工是否开启
    String permitleaveearlyminutesenable = Util.null2String(jsonObj.get("permitleaveearlyminutesenable"));///允许早退是否开启
    String seriousleaveearlyminutesenable= Util.null2String(jsonObj.get("seriousleaveearlyminutesenable"));//严重早退是否开启
    String leaveearlyabsentminutesenable = Util.null2String(jsonObj.get("leaveearlyabsentminutesenable"));//早退视作旷工是否开启

    String earlyinearlyout = Util.null2String(jsonObj.get("earlyinearlyout"));//允许早到早走是否开启
    String lateinlateout = Util.null2String(jsonObj.get("lateinlateout"));//允许晚到晚走是否开启
    String lateoutlatein = Util.null2String(jsonObj.get("lateoutlatein"));//允许晚走晚到是否开启

    JSONObject personalizedRuleDetails = (JSONObject)jsonObj.get("personalizedRuleDetails");
    checkRule(personalizedRuleDetails,retmap,jsonObj);

    if(!retmap.isEmpty()){
      return ;
    }
    String uuid = UUID.randomUUID().toString();//uuid供查询使用

    String mainSql = "insert into kq_ShiftPersonalizedRule(serialid,permitlateminutes,seriouslateminutes,lateabsentminutes, "
        + "permitleaveearlyminutes,seriousleaveearlyminutes,leaveearlyabsentminutes,permitlatestatus, "
        + "seriouslatestatus,lateabsentstatus,permitleaveearlystatus,seriousleaveearlystatus,leaveearlyabsentstatus,uuid,enableexcludelate,enableexcludeleaveearly) "
        + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";

    boolean isUpdated = rst.executeUpdate(mainSql,serialid,permitLateMinutes,seriousLateMinutes,lateAbsentMinutes,permitLeaveEarlyMinutes,
        seriousLeaveEarlyMinutes,leaveEarlyAbsentMinutes,permitlateminutesenable,seriouslateminutesenable,lateabsentminutesenable,
        permitleaveearlyminutesenable,seriousleaveearlyminutesenable,leaveearlyabsentminutesenable,uuid,enableexcludelate,enableexcludeleaveearly);

    if(isUpdated){
      int personalizedRuleid = 0;
      String idSql = "select id from kq_ShiftPersonalizedRule where uuid=? ";
      rs = new RecordSet();
      rs.executeQuery(idSql,uuid);
      if(rs.next()) personalizedRuleid = rs.getInt("id");

      if(personalizedRuleid > 0){

        String ruleSql = "insert into kq_ShiftPersonalizedRuleDetail(personalizedruleid,enable,enablesame,advancetime,postponetime,ruledetailtype,record) values(?,?,?,?,?,?,?)";
        String[] rules = new String[]{"earlyinearlyout","lateinlateout","lateoutlatein"};
        for(int j = 0 ; j < rules.length ; j++){
          String ruledetailtype=rules[j];
          if(!"lateoutlatein".equalsIgnoreCase(ruledetailtype)){
            JSONObject ruledetail = (JSONObject)personalizedRuleDetails.get(ruledetailtype);
            String enable=Util.null2String(jsonObj.get(ruledetailtype));
            String enablesame=Util.null2String(jsonObj.get(ruledetailtype+"same"));
            String advanceTime=Util.null2String(ruledetail.get("advancetime"));
            String postponeTime=Util.null2String(ruledetail.get("postponetime"));
            if(enablesame.equals("1")){
              postponeTime = advanceTime;
            }
            String record=Util.null2s(Util.null2String(ruledetail.get("record")),"0");
			if("mysql".equals(dbType) && "".equals(enablesame)){
                enablesame = null;
            }
            rst.executeUpdate(ruleSql, personalizedRuleid,enable,enablesame,advanceTime,postponeTime,ruledetailtype,record);
          }else{
            JSONArray ruledetails = (JSONArray)personalizedRuleDetails.get(ruledetailtype);
            for(int k =0 ; k < ruledetails.size() ; k ++){
              JSONObject ruledetail = (JSONObject)ruledetails.get(k);
              String enable=Util.null2String(jsonObj.get(ruledetailtype));
              String enablesame=Util.null2String(jsonObj.get(ruledetailtype+"same"));
              String advanceTime=Util.null2String(ruledetail.get("advancetime"));
              String postponeTime=Util.null2String(ruledetail.get("postponetime"));
              if(enablesame.equals("1")){
                postponeTime = advanceTime;
              }
              String record=Util.null2s(Util.null2String(ruledetail.get("record")),"0");
              if("mysql".equals(dbType) && "".equals(enablesame)){
                enablesame = null;
              }
              rst.executeUpdate(ruleSql, personalizedRuleid,enable,enablesame,advanceTime,postponeTime,ruledetailtype,record);
            }
          }
        }
        retmap.put("status", "1");
        retmap.put("id", serialid);
        retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage()));
      }else{
        retmap.put("status", "-1");
        retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
      }
    }else{
      retmap.put("status", "-1");
      retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
    }
  }
}
