package com.engine.kq.cmd.hrmAttProcSet;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.log.KQLog;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

/**
 * 考勤流程 保存校验规则
 * @author pzy
 *
 */
public class SaveStateProcCheckRuleCmd extends AbstractCommonCommand<Map<String, Object>>{

  private SimpleBizLogger logger;
  private KQLog kqLog = new KQLog();

  public SaveStateProcCheckRuleCmd(Map<String, Object> params, User user) {
		this.user = user;
		this.params = params;
  }

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

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

	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
		Map<String,Object> retmap = new HashMap<String,Object>();
		 
		try {
			String id = Util.null2s(Util.null2String(params.get("id")),"");
      kqLog.info("SaveStateProcCheckRuleCmd:params:"+params);
      List<Map<String,String>> fieldList = Lists.newArrayList();
      buildFiledList(fieldList);
			if(id.length() > 0){
        checkCanSave(params,fieldList,retmap,id);
        if(!retmap.isEmpty()){
          return retmap;
        }
			  edit(params,id,fieldList);
      }else{
			  checkCanSave(params,fieldList,retmap,"");
			  if(!retmap.isEmpty()){
			    return retmap;
        }
			  add(params,fieldList);
      }
      kqLog.info("SaveStateProcCheckRuleCmd:retmap:"+retmap);
			retmap.put("status", "1");
		} catch (Exception e) {
			retmap.put("status", "-1");
			retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
			writeLog(e);
		}
			
		return retmap;
	}

  /**
   * 判断是否可以添加
   * 重复校验不允许添加多个
   * 次数校验，不允许添加同样类型的，比如同一天控制的不能添加多个
   * @param params
   * @param fieldList
   * @param retmap
   * @param id 如果是编辑的话，是有id的
   */
  private void checkCanSave(Map<String, Object> params, List<Map<String, String>> fieldList,
      Map<String, Object> retmap,String id) {
    RecordSet rs = new RecordSet();
    RecordSet rs1 = new RecordSet();
    RecordSet rs2 = new RecordSet();
    RecordSet rs3 = new RecordSet();
    String rule_type_uuid = Util.null2s(Util.null2String(params.get("rule_type_uuid")),"");
    String attid = Util.null2s(Util.null2String(params.get("attid")),"");
    String kqtype = Util.null2s(Util.null2String(params.get("kqtype")),"");
    String sql = "select * from kq_att_checkrule_type where uuid = ? and att_type=? ";
    rs.executeQuery(sql,rule_type_uuid,kqtype);
    if(rs.next()) {
      String rule_table = rs.getString("rule_table");
      if (rule_table.length() > 0) {
        if("kq_att_duplicate_rule".equalsIgnoreCase(rule_table)){
          //重复校验
          String check_sql = "select * from kq_att_checkrule_set where rule_type_uuid=? and attid=? ";
          rs1.executeQuery(check_sql, rule_type_uuid,attid);
          if(id.length() > 0){
            //如果是编辑的情况 ，需要判断是
            check_sql = "select * from kq_att_checkrule_set where rule_type_uuid=? and attid=? and id <>?  ";
            rs1.executeQuery(check_sql, rule_type_uuid,attid,id);
          }
          if(rs1.next()){
            retmap.put("status", "-1");
            retmap.put("message",  SystemEnv.getHtmlLabelName(516715,user.getLanguage()));
            return ;
          }
        }else if("kq_att_frequency_rule".equalsIgnoreCase(rule_table)){
          //次数校验
          String check_sql = "select * from kq_att_checkrule_set where rule_type_uuid=? and attid=? ";
          rs1.executeQuery(check_sql, rule_type_uuid,attid);
          if(id.length() > 0){
            //如果是编辑的情况 ，需要判断是
            check_sql = "select * from kq_att_checkrule_set where rule_type_uuid=? and attid=? and id <>?  ";
            rs1.executeQuery(check_sql, rule_type_uuid,attid,id);
          }
          while (rs1.next()){
            String ruleid = rs1.getString("ruleid");
            String frequency_rule = Util.null2s(Util.null2String(params.get("frequency_rule")),"");
            String check_type_sql = "select * from "+rule_table+" where id=? and frequency_rule=? ";
            rs2.executeQuery(check_type_sql,ruleid,frequency_rule);
            if(rs2.next()){
              retmap.put("status", "-1");
              retmap.put("message",  SystemEnv.getHtmlLabelName(516715,user.getLanguage()));
              return ;
            }
          }
        }
      }
    }
  }

  public void buildFiledList(List<Map<String,String>> fieldList) throws Exception{
    RecordSet rs = new RecordSet();
    //校验规则的 校验类型 如果没有传过来，默认就是第一个
    String rule_type_uuid = Util.null2s(Util.null2String(params.get("rule_type_uuid")),"");
    String kqtype = Util.null2s(Util.null2String(params.get("kqtype")),"");
    if(rule_type_uuid.length() == 0){
      String att_type_sql = "select * from kq_att_checkrule_type where att_type = "+kqtype+" order by rule_type_order ";
      rs.executeQuery(att_type_sql);
      if(rs.next()){
        rule_type_uuid = rs.getString("uuid");
      }
    }
    String fieldSql = "select * from kq_att_checkrule_fields where rule_type_uuid = '"+rule_type_uuid+"' order by fieldorder ";
    rs.executeQuery(fieldSql);
    while (rs.next()){
      String fieldname = rs.getString("fieldname");
      String fieldlabel = rs.getString("fieldlabel");
      String fieldhtmltype = rs.getString("fieldhtmltype");
      String fieldtype = rs.getString("fieldtype");
      Map<String,String> fieldMap = Maps.newHashMap();
      fieldMap.put("fieldname", fieldname);
      fieldMap.put("fieldlabel", fieldlabel);
      fieldMap.put("fieldhtmltype", fieldhtmltype);
      fieldMap.put("fieldtype", fieldtype);
      fieldList.add(fieldMap);
    }
  }

  public void add(Map<String, Object> params,
      List<Map<String, String>> fieldList) throws Exception{
    RecordSet rs = new RecordSet();
    RecordSet rs1 = new RecordSet();
    RecordSet rs2 = new RecordSet();
    RecordSet rs3 = new RecordSet();
    String rule_type_uuid = Util.null2s(Util.null2String(params.get("rule_type_uuid")),"");
    String attid = Util.null2s(Util.null2String(params.get("attid")),"");
    String kqtype = Util.null2s(Util.null2String(params.get("kqtype")),"");
    String sql = "select * from kq_att_checkrule_type where uuid = ? and att_type=? ";
    rs.executeQuery(sql,rule_type_uuid,kqtype);
    if(rs.next()){
      String rule_table = rs.getString("rule_table");
      if(rule_table.length() > 0){
        String uuid = UUID.randomUUID().toString();
        String fieldnames = "";
        String values_key = "";
        List values_value = Lists.newArrayList();

        for(int i = 0 ; i < fieldList.size() ; i++){
          Map<String,String> fieldMap = fieldList.get(i);
          String fieldname = fieldMap.get("fieldname");
          String fieldvalue = Util.null2s(Util.null2String(params.get(fieldname)),"");
          fieldnames += ","+fieldname;
          values_key += ",? ";
          values_value.add(fieldvalue);
        }
        if(fieldnames.length() > 0){
          fieldnames = fieldnames.substring(1);
        }
        if(values_key.length() > 0){
          values_key = values_key.substring(1);
        }
        String sql1 = "insert into "+rule_table+"("+fieldnames+",uuid)"
            + " values("+values_key+",?)";
        values_value.add(uuid);

        kqLog.info("SaveStateProcCheckRuleCmd:add:"+sql1+":values_value:"+values_value);
        boolean isok = rs1.executeUpdate(sql1,values_value);
        if(isok){
          String sql2 = "select * from "+rule_table+" where uuid = ? ";
          kqLog.info("SaveStateProcCheckRuleCmd:sql2:"+sql2+":uuid:"+uuid);
          rs2.executeQuery(sql2,uuid);
          if(rs2.next()){
            String ruleid = rs2.getString("id");
            String sql3 = "insert into kq_att_checkrule_set(attid,ruleid,rule_type_uuid,uuid) values(?,?,?,?)";
            isok = rs3.executeUpdate(sql3, attid,ruleid,rule_type_uuid,uuid);
            kqLog.info("SaveStateProcCheckRuleCmd:sql3:"+sql3+":attid:"+attid+":ruleid:"+ruleid
                +":rule_type_uuid:"+rule_type_uuid+":uuid:"+uuid+":isok:"+isok);
          }
        }else{
          throw new Exception("数据插入失败");
        }
      }
    }
  }

  public void edit(Map<String, Object> params, String id,
      List<Map<String, String>> fieldList) throws Exception{
    RecordSet rs = new RecordSet();
    RecordSet rs1 = new RecordSet();
    String rule_type_uuid = Util.null2s(Util.null2String(params.get("rule_type_uuid")),"");
    String kqtype = Util.null2s(Util.null2String(params.get("kqtype")),"");
    String sql = "select * from kq_att_checkrule_type where uuid = ? and att_type=?";
    rs.executeQuery(sql,rule_type_uuid,kqtype);
    if(rs.next()){
      String rule_table = rs.getString("rule_table");
      if(rule_table.length() > 0){
        String check_sql = "select * from kq_att_checkrule_set where id=? ";
        rs1.executeQuery(check_sql, id);
        if(rs1.next()){
          String ruleid = rs1.getString("ruleid");
          if(ruleid.length() > 0){
            String fieldvalues_key = "";
            List fieldvalues_value = Lists.newArrayList();
            for(int i = 0 ; i < fieldList.size() ; i++){
              Map<String,String> fieldMap = fieldList.get(i);
              String fieldname = fieldMap.get("fieldname");
              String fieldvalue = Util.null2s(Util.null2String(params.get(fieldname)),"");
              fieldvalues_key += ","+fieldname+"=? ";
              fieldvalues_value.add(fieldvalue);
            }
            if(fieldvalues_key.length() > 0){
              fieldvalues_key = fieldvalues_key.substring(1);
            }
            String sql1 = " update "+rule_table+" set "+fieldvalues_key+" where id=? ";
            fieldvalues_value.add(ruleid);
            boolean isok = rs1.executeUpdate(sql1,fieldvalues_value);

            if(isok){
            }else{
              throw new Exception("数据插入失败");
            }
          }
        }
      }
    }
  }
}
