package com.engine.kq.cmd.hrmAttProcSet;

import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQAttProcSetComInfo;
import com.engine.kq.enums.KqSplitFlowTypeEnum;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

/**
 * 新建编辑 校验规则
 * @author pzy
 *
 */
public class GetProcSetCheckRuleCmd extends AbstractCommonCommand<Map<String, Object>>{

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

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


	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
    Map<String,Object> retmap = new HashMap<String,Object>();

    List<Object> lsGroup = new ArrayList<Object>();
    Map<String,Object> groupitem = null;
    List<Object> itemlist = null;
    try {
      RecordSet rs = new RecordSet();
      RecordSet rs1 = new RecordSet();
      String id = Util.null2s(Util.null2String(params.get("id")),"");
      //校验规则的 校验类型 如果没有传过来，默认就是第一个
      String rule_type_uuid = Util.null2s(Util.null2String(params.get("rule_type_uuid")),"");
      //考勤流程设置的id 取值自kq_att_proc_set
      String attid = Util.null2s(Util.null2String(params.get("attid")),"");

      boolean isEdit = id.length() > 0;
      String ruleid = "";
      String edit_sql = "select *from kq_att_checkrule_set  where id = ? ";
      rs.executeQuery(edit_sql, id);
      if(rs.next()){
        attid = rs.getString("attid");
        ruleid = rs.getString("ruleid");
        rule_type_uuid = rs.getString("rule_type_uuid");
      }

      if(attid.length() == 0 ){
        retmap.put("status", "-1");
        retmap.put("message", SystemEnv.getHtmlLabelName(500682, user.getLanguage()));
        return retmap;
      }
      String kqtype = "";
      String att_sql = "select * from kq_att_proc_set where id = ? ";
      rs.executeQuery(att_sql,attid);
      if(rs.next()){
        kqtype = rs.getString("field006");
      }
      if(kqtype.length() == 0 ){
        retmap.put("status", "-1");
        retmap.put("message", SystemEnv.getHtmlLabelName(500682, user.getLanguage()));
        return retmap;
      }

      //如果新增的时候，下拉框需要有个默认值
      if(rule_type_uuid.length() == 0){
        String att_type_sql = "select * from kq_att_checkrule_type where att_type = ? order by rule_type_order ";
        rs.executeQuery(att_type_sql,kqtype);
        if(rs.next()){
          rule_type_uuid = rs.getString("uuid");
        }
      }
      //需要回显的动态提示内容
      Map<String,String> msg = Maps.newHashMap();
      //因为提示语句是要根据选择的内容动态回显的，针对这样的字段增加动态映射
      Map<String,String> field_map = Maps.newHashMap();
      get_field_map(field_map,rule_type_uuid);

      //得到下拉框校验类型的数据
      Map<String,String> labelidMap = Maps.newLinkedHashMap();
      get_labelidMap(labelidMap,kqtype);

      //根据下拉框的校验类型，获取到每种类型对应的校验字段
      List<Map<String,String>> fieldList = Lists.newArrayList();
      get_fieldList(fieldList,rule_type_uuid);

      //校验类型 校验规则 需校验流程路径 校验强度 提示语句
      String[] fields = new String[fieldList.size()];
      for(int i = 0 ; i < fieldList.size() ; i++){
        Map<String,String> fieldMap = fieldList.get(i);
        fields[i] = fieldMap.get("fieldname")+","+fieldMap.get("fieldlabel")+","+fieldMap.get("fieldhtmltype")+","+fieldMap.get("fieldtype");
      }

      String[] values = new String[fieldList.size()];
      if(isEdit){
        //编辑情况下，根据字段对应把每个字段对应的值返还
        get_edit_value(values,rule_type_uuid,fieldList,ruleid);
      }

      /**
       * 根据什么字段的什么条件来联动
       */
      Map<String,Object> to_related_map = Maps.newHashMap();
      //需要被联动的字段
      Map<String,Object> from_related_map = Maps.newHashMap();

      List<Map<String, Object>> replaceDatas = new ArrayList<Map<String,Object>>();
      HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
      SearchConditionItem searchConditionItem = null;
      HrmFieldBean hrmFieldBean = null;
      List<SearchConditionOption> options = Lists.newArrayList();
      itemlist = new ArrayList<Object>();
      groupitem = new HashMap<String,Object>();
      groupitem.put("title", SystemEnv.getHtmlLabelName(1361,weaver.general.Util.getIntValue(user.getLanguage())));
      groupitem.put("defaultshow", true);
      for(int i=0;i<fields.length;i++){
        String[] fieldinfo = fields[i].split(",");
        hrmFieldBean = new HrmFieldBean();
        hrmFieldBean.setFieldname(fieldinfo[0]);
        hrmFieldBean.setFieldlabel(fieldinfo[1]);
        hrmFieldBean.setFieldhtmltype(fieldinfo[2]);
        hrmFieldBean.setType(fieldinfo[3]);
        hrmFieldBean.setIsFormField(true);
        hrmFieldBean.setViewAttr(3);
        hrmFieldBean.setMultilang(true);
        hrmFieldBean.setRules("required|string");
        replaceDatas = new ArrayList<Map<String,Object>>();

        if("rule_type_uuid".equalsIgnoreCase(hrmFieldBean.getFieldname())){
          options = Lists.newArrayList();
          for(Iterator mapIterator = labelidMap.keySet().iterator();mapIterator.hasNext();){
            String key = Util.null2String(mapIterator.next());
            String val = labelidMap.get(key);
            SearchConditionOption searchConditionOption = new SearchConditionOption(key,SystemEnv.getHtmlLabelNames(val, user.getLanguage()));
            if(isEdit){
              if(values[i].equalsIgnoreCase(key)){
                searchConditionOption.setSelected(true);
              }
            }else{
              if(key.equalsIgnoreCase(rule_type_uuid)){
                searchConditionOption.setSelected(true);
                hrmFieldBean.setFieldvalue(key);
              }
            }
            options.add(searchConditionOption);
          }
          hrmFieldBean.setSelectOption(options);
        }
        if("duplicate_rule".equalsIgnoreCase(hrmFieldBean.getFieldname())){
          options = Lists.newArrayList();
          SearchConditionOption  SearchConditionOption1 = new SearchConditionOption("0",SystemEnv.getHtmlLabelName(516103,weaver.general.Util.getIntValue(user.getLanguage())));
          SearchConditionOption  SearchConditionOption2 = new SearchConditionOption("1",SystemEnv.getHtmlLabelName(516104,weaver.general.Util.getIntValue(user.getLanguage())));
          options.add(SearchConditionOption1);
          options.add(SearchConditionOption2);
          hrmFieldBean.setSelectOption(options);
          if(!isEdit){
            hrmFieldBean.setFieldvalue("0");
            SearchConditionOption1.setSelected(true);
          }else{
            if("0".equalsIgnoreCase(values[i])){
              SearchConditionOption1.setSelected(true);
            }else if("1".equalsIgnoreCase(values[i])){
              SearchConditionOption2.setSelected(true);
            }
          }
        }
        if("duplicate_level".equalsIgnoreCase(hrmFieldBean.getFieldname()) || "frequency_level".equalsIgnoreCase(hrmFieldBean.getFieldname())){
          options = Lists.newArrayList();
          SearchConditionOption  SearchConditionOption1 = new SearchConditionOption("0",SystemEnv.getHtmlLabelName(32137,weaver.general.Util.getIntValue(user.getLanguage())));
          SearchConditionOption  SearchConditionOption2 = new SearchConditionOption("1",SystemEnv.getHtmlLabelName(32138,weaver.general.Util.getIntValue(user.getLanguage())));
          SearchConditionOption  SearchConditionOption3 = new SearchConditionOption("2",SystemEnv.getHtmlLabelName(26009,weaver.general.Util.getIntValue(user.getLanguage())));
          options.add(SearchConditionOption1);
          options.add(SearchConditionOption2);
          options.add(SearchConditionOption3);
          hrmFieldBean.setSelectOption(options);
          if(!isEdit){
            hrmFieldBean.setFieldvalue("0");
            SearchConditionOption1.setSelected(true);
          }else{
            if("0".equalsIgnoreCase(values[i])){
              SearchConditionOption1.setSelected(true);
            }else if("1".equalsIgnoreCase(values[i])){
              SearchConditionOption2.setSelected(true);
            }else if("1".equalsIgnoreCase(values[i])){
              SearchConditionOption3.setSelected(true);
            }
          }
          if(field_map.containsValue(hrmFieldBean.getFieldname())){
            if("duplicate_level".equalsIgnoreCase(hrmFieldBean.getFieldname())){
              msg.put("check_level_0", SystemEnv.getHtmlLabelName(516560,weaver.general.Util.getIntValue(user.getLanguage())));
              msg.put("check_level_1", SystemEnv.getHtmlLabelName(516561,weaver.general.Util.getIntValue(user.getLanguage())));
            }else if("frequency_level".equalsIgnoreCase(hrmFieldBean.getFieldname())){
              msg.put("check_level_0", SystemEnv.getHtmlLabelName(516562,weaver.general.Util.getIntValue(user.getLanguage())));
              msg.put("check_level_1", SystemEnv.getHtmlLabelName(516563,weaver.general.Util.getIntValue(user.getLanguage())));
            }
          }
        }
        if("frequency_rule".equalsIgnoreCase(hrmFieldBean.getFieldname())){
          options = Lists.newArrayList();
          SearchConditionOption  SearchConditionOption1 = new SearchConditionOption("0",SystemEnv.getHtmlLabelName(539,weaver.general.Util.getIntValue(user.getLanguage())));
          SearchConditionOption  SearchConditionOption2 = new SearchConditionOption("1",SystemEnv.getHtmlLabelName(545,weaver.general.Util.getIntValue(user.getLanguage())));
          SearchConditionOption  SearchConditionOption3 = new SearchConditionOption("2",SystemEnv.getHtmlLabelName(541,weaver.general.Util.getIntValue(user.getLanguage())));
          SearchConditionOption  SearchConditionOption4 = new SearchConditionOption("3",SystemEnv.getHtmlLabelName(543,weaver.general.Util.getIntValue(user.getLanguage())));
          SearchConditionOption  SearchConditionOption5 = new SearchConditionOption("4",SystemEnv.getHtmlLabelName(546,weaver.general.Util.getIntValue(user.getLanguage())));
          options.add(SearchConditionOption1);
          options.add(SearchConditionOption2);
          options.add(SearchConditionOption3);
          options.add(SearchConditionOption4);
          options.add(SearchConditionOption5);
          hrmFieldBean.setSelectOption(options);
          if(!isEdit){
            hrmFieldBean.setFieldvalue("0");
            SearchConditionOption1.setSelected(true);
          }else{
            if("0".equalsIgnoreCase(values[i])){
              SearchConditionOption1.setSelected(true);
            }else if("1".equalsIgnoreCase(values[i])){
              SearchConditionOption2.setSelected(true);
            }else if("2".equalsIgnoreCase(values[i])){
              SearchConditionOption3.setSelected(true);
            }else if("3".equalsIgnoreCase(values[i])){
              SearchConditionOption4.setSelected(true);
            }else if("4".equalsIgnoreCase(values[i])){
              SearchConditionOption5.setSelected(true);
            }
          }
        }
        if("duplicate_message".equalsIgnoreCase(hrmFieldBean.getFieldname())){
          if(!isEdit){
            hrmFieldBean.setFieldvalue(SystemEnv.getHtmlLabelName(516560,weaver.general.Util.getIntValue(user.getLanguage())));
          }
        }
        if("frequency_message".equalsIgnoreCase(hrmFieldBean.getFieldname())){
          if(!isEdit){
            hrmFieldBean.setFieldvalue(SystemEnv.getHtmlLabelName(516562,weaver.general.Util.getIntValue(user.getLanguage())));
          }
        }
        if(isEdit){
          hrmFieldBean.setFieldvalue(values[i]);

          if("rule_type_uuid".equalsIgnoreCase(hrmFieldBean.getFieldname())){
            hrmFieldBean.setViewAttr(1);
          }
        }

        searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
        if("duplicate_level".equals(hrmFieldBean.getFieldname())){
          searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(516108,weaver.general.Util.getIntValue(user.getLanguage())));
        }
        if("duplicate_rule".equals(hrmFieldBean.getFieldname())){
          searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(516168,weaver.general.Util.getIntValue(user.getLanguage())));
        }
        if("duplicate_wfids".equalsIgnoreCase(hrmFieldBean.getFieldname())){
          if(isEdit){
            String tmpAttId = values[i];
            String workflowname = "";
            int version = 1;
            List<String> tmpAttIdList = Arrays.asList(tmpAttId.split(","));
            List<String> vals = Lists.newArrayList();
            String id_str = "";
            for(String tmp_id : tmpAttIdList){
              id_str += ",?";
              vals.add(tmp_id);
            }
            if(id_str.length() > 0){
              id_str = id_str.substring(1);
            }
            String tmp_att_sql = "select * from workflow_base where id in("+id_str+")";
            rs.executeQuery(tmp_att_sql, vals);
            while (rs.next()){
              Map<String, Object>  datas = new HashMap<String, Object>();
              String wfid = rs.getString("id");
              workflowname = Util.null2String(rs.getString("workflowname"));
              version = Util.getIntValue(rs.getString("version"),1);
              workflowname = workflowname+"("+SystemEnv.getHtmlLabelName(33569,user.getLanguage())
                  +SystemEnv.getHtmlLabelName(567,user.getLanguage())+":V"+version+")";
              datas.put("id",wfid);
              datas.put("name",workflowname);
              replaceDatas.add(datas);
            }
            searchConditionItem.getBrowserConditionParam().setReplaceDatas(replaceDatas);
          }
          if("5".equalsIgnoreCase(rule_type_uuid)) {
            //补卡流程 只能和补卡流程比较
            searchConditionItem.getBrowserConditionParam().getDataParams().put("kqtype", "7");
            searchConditionItem.getBrowserConditionParam().getCompleteParams().put("kqtype", "7");
          }else{
            //目前只有请假，出差，公出和加班流程可以比较
            searchConditionItem.getBrowserConditionParam().getDataParams().put("kqtype", "0,1,2,3,8");
            searchConditionItem.getBrowserConditionParam().getCompleteParams().put("kqtype", "0,1,2,3,8");
          }
        }
        searchConditionItem.setRules("required|string");
        searchConditionItem.setLabelcol(6);
        searchConditionItem.setFieldcol(18);

        if("frequency_rule_count".equals(hrmFieldBean.getFieldname())){
          searchConditionItem.setRules("required|integer");
          Map<String,Object> otherParams = new HashMap<String,Object>();
          otherParams.put("min",1);
          searchConditionItem.setOtherParams(otherParams);
        }

        itemlist.add(searchConditionItem);
      }
      List<Object> msglist = new ArrayList<>();
      Map<String,Object> item = new HashMap<String,Object>();
      item.put("label", SystemEnv.getHtmlLabelName(516109,user.getLanguage()));
      if("6".equalsIgnoreCase(rule_type_uuid)){
        //次数校验的补卡流程
        item.put("msg", SystemEnv.getHtmlLabelName(516638,user.getLanguage())
            +"<br/>"+SystemEnv.getHtmlLabelName(516639,user.getLanguage()));
      }else{
        item.put("msg", SystemEnv.getHtmlLabelName(516111,user.getLanguage())
            +"<br/>"+SystemEnv.getHtmlLabelName(516112,user.getLanguage()));
      }
      msglist.add(item);

      groupitem.put("items", itemlist);
      lsGroup.add(groupitem);
      retmap.put("condition", lsGroup);
      retmap.put("status", "1");
      retmap.put("msglist", msglist);
      retmap.put("kqtype", kqtype);
      retmap.put("msg", msg);
      retmap.put("field_map", field_map);

      //以下的效果就是duplicate_rule为1的时候才联动显示出来duplicate_wfids
      to_related_map.put("duplicate_rule", "1");
      from_related_map.put("duplicate_wfids", to_related_map);
      //以下的效果就是duplicate_rule为1的时候才联动显示出来duplicate_wfids
      to_related_map = Maps.newHashMap();
      to_related_map.put("duplicate_level", "0,1");
      from_related_map.put("duplicate_message", to_related_map);
      to_related_map = Maps.newHashMap();
      to_related_map.put("frequency_level", "0,1");
      from_related_map.put("frequency_message", to_related_map);
      retmap.put("related", from_related_map);
      retmap.put("id", id);
    } catch (Exception e) {
      retmap.put("status", "-1");
      retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
      writeLog(e);
    }

    return retmap;
  }

  /**
   * 编辑情况下，根据字段对应把每个字段对应的值返还
   * @param values
   * @param rule_type_uuid
   * @param fieldList
   * @param ruleid
   */
  private void get_edit_value(String[] values, String rule_type_uuid,
      List<Map<String, String>> fieldList, String ruleid) {
    RecordSet rs = new RecordSet();
    RecordSet rs1 = new RecordSet();
    String sql = "select * from kq_att_checkrule_type where uuid = ? ";
    rs.executeQuery(sql,rule_type_uuid);
    if(rs.next()){
      String rule_table = rs.getString("rule_table");
      String data_sql = "select * from "+rule_table+" where id = ? ";
      rs1.executeQuery(data_sql,ruleid);
      if(rs1.next()){
        for(int i = 0 ; i < fieldList.size() ; i++){
          Map<String,String> fieldMap = fieldList.get(i);
          String fieldname = fieldMap.get("fieldname");
          values[i] = rs1.getString(fieldname);
        }
      }
    }
  }

  /**
   * 根据下拉框的校验类型，获取到每种类型对应的校验字段
   * @param fieldList
   * @param rule_type_uuid
   */
  private void get_fieldList(List<Map<String, String>> fieldList, String rule_type_uuid) {
    RecordSet rs = new RecordSet();
    String fieldSql = "select * from kq_att_checkrule_fields where rule_type_uuid = ? order by fieldorder ";
    rs.executeQuery(fieldSql,rule_type_uuid);
    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);
    }
  }

  /**
   * 得到下拉框校验类型的数据
   * @param labelidMap
   * @param kqtype
   */
  private void get_labelidMap(Map<String, String> labelidMap, String kqtype) {
    RecordSet rs = new RecordSet();
    String rule_type_sql = "select * from kq_att_checkrule_type where att_type = ? order by rule_type_order ";
    rs.executeQuery(rule_type_sql,kqtype);
    while (rs.next()){
      String labelids = rs.getString("labelids");
      String uuid = rs.getString("uuid");
      labelidMap.put(uuid, labelids);
    }
  }

  /**
   * 因为提示语句是要根据选择的内容动态回显的，针对这样的字段增加动态映射
   * @param field_map
   * @param rule_type_uuid
   */
  private void get_field_map(Map<String, String> field_map, String rule_type_uuid) {
    RecordSet rs = new RecordSet();
    String field_map_sql = "select * from kq_att_checkrule_fields where rule_type_uuid=? ";
    rs.executeQuery(field_map_sql, rule_type_uuid);
    while (rs.next()){
      String key_fieldname = rs.getString("key_fieldname");
      String fieldname = rs.getString("fieldname");
      if(key_fieldname.length() > 0 && fieldname.length() > 0){
        field_map.put(key_fieldname, fieldname);
      }
    }
  }

}
