package com.engine.kq.wfset.attendance.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.cmd.hrmAttProcSet.KqSplitActionEnum;
import com.engine.kq.wfset.attendance.dao.HrmAttProcActionDao;
import com.engine.kq.wfset.attendance.domain.HrmAttProcAction;
import com.engine.kq.wfset.attendance.domain.HrmAttProcSet;
import com.engine.kq.wfset.attendance.framework.BaseManager;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.workflow.action.WorkflowActionManager;

/**
 * HrmAttProcActionManager
 * @author wcd
 * @version 1.0 2015-04-27
 */
public class HrmAttProcActionManagerE9 extends BaseManager<HrmAttProcAction> {

	private HrmAttProcActionDao dao = null;

	public HrmAttProcActionManagerE9() {
		dao = new HrmAttProcActionDao();
		this.setDao(dao);
	}

	public Long save(HrmAttProcAction bean) {
		String id = String.valueOf(bean.getId());
		if(id.equals("0") || id.equals("-1")) id = String.valueOf(this.insert(bean));
		else this.update(bean);
		return Long.valueOf(id);
	}
	
	public void delete(Map<String, Comparable> map){
		dao.delete(map);
	}
	
	public String save(HttpServletRequest request, HttpServletResponse response, String field001, String field002) {
	  String result = "";
		set(request, response);
		HrmAttProcSetManager setManager = new HrmAttProcSetManager();
		int workflowid = 0;
		HrmAttProcSet setBean = setManager.get(StringUtil.parseToInt(field001, 0));
    int flowtype = setBean.getField006();//考勤流程类型
    String splitAction = KqSplitActionEnum.ATT.getSplitAction();

    WorkflowActionManager workflowActionManager = new WorkflowActionManager();
    HrmAttProcAction bean = null;
    JSONArray jSONArray = JSON.parseArray(field002);

    for(int k = 0 ; k < jSONArray.size() ; k ++){

      JSONObject jObject = (JSONObject) jSONArray.get(k);
      String actionId = StringUtil.vString(jObject.get("rowKey"));
      String nodeid = StringUtil.vString(jObject.get("field006"));
      //0出口附加规则，1节点后附加操作，2节点前附加操作
      String nodeidType = StringUtil.vString(jObject.get("field005"));
      //两个校验，一个是保存的时候校验是否设置了拆分的action，第二个是校验拆分的action是否配置在归档节点前
      if(splitAction.equalsIgnoreCase(actionId)){
        if(nodeid.length() == 0){
          result = "1";
          break;
        }
        if(!checkAction(nodeid,nodeidType)){
          result = "1";
          break;
        }
      }
      //两个校验，一个是保存的时候校验是否设置了拆分的action，第二个是校验冻结拆分的action是否配置在创建节点后
      //TODO 未考虑做这个创建节点后拆分流程的功能，暂时屏蔽
//      if(splitFreezeAction.equalsIgnoreCase(actionId)){
//        if(!checkFreezeAction(nodeid,nodeidType)){
//          result = "2";
//          break;
//        }
//      }
    }
    if(result.length() > 0){
      return result;
    }
    if(setBean != null) {
      workflowid = setBean.getField001();
      setBean.setField009(DateUtil.getCurrentDate());
      setManager.update(setBean);
    }
    delete(getMapParam("field001:"+field001));

    //只有排班流程没有这块节点前action的控制
    if(flowtype != 5 && result.length() > 0) {
      return result;
    }
		dao.deleteAction(workflowid);
		
		for(int k = 0 ; k < jSONArray.size() ; k ++){
			JSONObject jObject = (JSONObject) jSONArray.get(k);
			String actionId = StringUtil.vString(jObject.get("rowKey"));
			
			bean = new HrmAttProcAction();
			bean.setField001(StringUtil.parseToLong(field001));
			bean.setField002(actionId);
			bean.setField003(StringUtil.vString(jObject.get("field003")));
			bean.setField005(StringUtil.parseToInt(StringUtil.vString(jObject.get("field005"))));
			bean.setField006(StringUtil.vString(jObject.get("field006")));
//			bean.setField007(StringUtil.parseToInt(StringUtil.vString(jObject.get("field007"),"0")));
			bean.setField008(StringUtil.parseToInt(StringUtil.vString(jObject.get("field008"))));
      insert(bean);
			
			if(bean.getField006().equals("-1")) continue;
			int size = bean.getField006().split(",").length;
			String defaultValue = "";
			for(int i=0; i<size; i++) defaultValue += "0"+(i!=size-1?",":"");
			
			int preoperator = 0;
			String nodeId = defaultValue, nodeLinkId = defaultValue;
			switch (bean.getField005()) {
			case 2:
				preoperator = 1;
				nodeId = bean.getField006();
				nodeLinkId = defaultValue;
				break;
			case 1:
				nodeId = bean.getField006();
				nodeLinkId = defaultValue;
				break;
			case 0:
				nodeId = defaultValue;
				nodeLinkId = bean.getField006();
				break;
			}
			
			String[] nodeIds = nodeId.split(",");
			String[] nodeLinkIds = nodeLinkId.split(",");
			if(nodeIds.length != nodeLinkIds.length) continue;
			
			String field003Name = getLabelName(bean.getField003());
			for(int index=0; index<nodeIds.length; index++) {
				workflowActionManager.setActionid(0);
				workflowActionManager.setActionname(field003Name);
				workflowActionManager.setWorkflowid(workflowid);
				workflowActionManager.setNodeid(StringUtil.parseToInt(nodeIds[index]));
				workflowActionManager.setNodelinkid(StringUtil.parseToInt(nodeLinkIds[index]));
				workflowActionManager.setIspreoperator(preoperator);
				workflowActionManager.setActionorder(1);
				workflowActionManager.setInterfaceid(bean.getField002());
				workflowActionManager.setInterfacetype(3);
				workflowActionManager.setIsused(1);
        if("KqReleaseVacationAction".equalsIgnoreCase(actionId)){
          workflowActionManager.setDrawbackflag(1);
        }
				workflowActionManager.doSaveWsAction();
			}
//			dao.updateBackFlag(bean.getField005(), bean.getField007(), workflowid, nodeId);
		}
		return result;
	}

	public void save(List<HrmAttProcAction> list) {
		dao.insert(list);
	}

  /**
   * 判断拆分action是否配置在流程的归档节点且节点前
   * @param nodeid
   * @param nodeidType
   * @return
   */
  public boolean checkAction(String nodeid,String nodeidType){
    RecordSet rs = new RecordSet();
    String checkSql = "select nodeType from workflow_flownode where nodeid in ("+nodeid+") ";
    rs.executeQuery(checkSql);

    boolean isNeededAction = true;
    while (rs.next()){
      //节点类型  0:创建 1:审批 2:实现 3:归档
      String nodetype = rs.getString("nodeType");
      boolean isCreateNode = "3".equalsIgnoreCase(nodetype) ? true : false;
      boolean isRightNodeType = "2".equalsIgnoreCase(nodeidType) ? true : false;
      if(!isCreateNode && isRightNodeType){
        isNeededAction = false;
        break;
      }
    }
    return isNeededAction;
  }

  /**
   * 判断冻结拆分action是否配置在流程的创建节点且节点后
   * @param nodeid
   * @param nodeidType
   * @return
   */
  public boolean checkFreezeAction(String nodeid,String nodeidType){
    RecordSet rs = new RecordSet();
    String checkSql = "select nodeType from workflow_flownode where nodeid = ? ";
    rs.executeQuery(checkSql, nodeid);
    //节点类型  0:创建 1:审批 2:实现 3:归档
    String nodetype = "";
    if(rs.next()){
      nodetype = rs.getString("nodeType");
    }
    boolean isCreateNode = "0".equalsIgnoreCase(nodetype) ? true : false;

    boolean isRightNodeType = "1".equalsIgnoreCase(nodeidType) ? true : false;
    return isCreateNode && isRightNodeType;
  }

}
