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

import com.alibaba.fastjson.JSON;
import com.engine.kq.wfset.attendance.domain.HrmAttProcAction;
import com.engine.kq.wfset.attendance.framework.BaseConnection;
import com.engine.kq.wfset.attendance.framework.BaseDao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.hrm.common.database.dialect.DialectUtil;

/**
 * HrmAttProcActionDao
 * @author wcd
 * @version 1.0 2015-04-27
 */
public class HrmAttProcActionDao extends BaseConnection implements BaseDao<HrmAttProcAction> {

	public Comparable insert(HrmAttProcAction bean) {
    RecordSet rs = new RecordSet();
		if(bean == null) return -1;
		StringBuffer sql = new StringBuffer()
		.append(" insert into kq_ATT_PROC_ACTION (mfid,field001,field002,field003,field004,field005,")
		.append(" field006,field007,field008 )")
		.append(" values("+bean.getMfid()+","+bean.getField001()+",'"+bean.getField002()+"','"+bean.getField003()+"',")
		.append(" "+bean.getField004()+","+bean.getField005()+",'"+bean.getField006()+"',"+bean.getField007()+",")
		.append(" "+bean.getField008()+" )");
		rs.executeSql(sql.toString());
		return 0;
	}

	public void insert(List<HrmAttProcAction> list) {
    RecordSet rs = new RecordSet();
		if(list == null) return;
		StringBuffer sql = new StringBuffer(), tempSql = new StringBuffer()
		.append(" insert into kq_ATT_PROC_ACTION (mfid,field001,field002,field003,field004,field005,")
		.append(" field006,field007,field008 )");
		int count = 0, index = 0;
		for(HrmAttProcAction bean : list) {
			index ++;
			sql.append(count == 0 ? tempSql.toString() : " UNION ").append(bean.getSql()).append(isOracle() ? " from dual" : "");
			if((count++) == 100 || index >= list.size()) {
				rs.executeSql(sql.toString());
				sql.setLength(count = 0);
			}
		}
	}

	public void update(HrmAttProcAction bean) {
    RecordSet rs = new RecordSet();
		if(bean == null) return;
		StringBuffer sql = new StringBuffer()
		.append(" update kq_ATT_PROC_ACTION set")
		.append(" mfid = "+bean.getMfid()+",field001 = "+bean.getField001()+",field002 = '"+bean.getField002()+"',")
		.append(" field003 = '"+bean.getField003()+"',field004 = "+bean.getField004()+",field005 = "+bean.getField005()+",")
		.append(" field006 = '"+bean.getField006()+"',field007 = "+bean.getField007()+",field008 = "+bean.getField008()+"")
		.append(" where id = "+bean.getId()+"");
		rs.executeSql(sql.toString());
	}

	public List<HrmAttProcAction> find(Map<String, Comparable> map) {
    RecordSet rs = new RecordSet();
		List<HrmAttProcAction> list = new ArrayList<HrmAttProcAction>();
		StringBuffer sql = new StringBuffer()
		.append(" select t.id,t.mfid,t.field001,t.field002,t.field003,t.field004,t.field005,")
		.append(" t.field006,t.field007,t.field008, '' as field006Name")
		.append(" from kq_ATT_PROC_ACTION t")
		.append(" where  1 = 1");
		if(map != null) {
			if(map.containsKey("id")){
				sql.append(" and t.id = ").append(StringUtil.vString(map.get("id")));
			}
			if(map.containsKey("begin_id")){
				sql.append(" and t.id >= ").append(StringUtil.vString(map.get("begin_id")));
			}
			if(map.containsKey("end_id")){
				sql.append(" and t.id < ").append(StringUtil.vString(map.get("end_id")));
			}
			if(map.containsKey("sql_id")){
				sql.append(" " + StringUtil.vString(map.get("sql_id")));
			}
			if((rs.getDBType()).equalsIgnoreCase("postgresql")) {
				if (map.containsKey("mfid")) {
					sql.append(" and t.mfid = '").append(StringUtil.vString(map.get("mfid"))).append("'");
				}
				if (map.containsKey("begin_mfid")) {
					sql.append(" and t.mfid >= '").append(StringUtil.vString(map.get("begin_mfid"))).append("'");
				}
				if (map.containsKey("end_mfid")) {
					sql.append(" and t.mfid < '").append(StringUtil.vString(map.get("end_mfid"))).append("'");
				}
			} else {
				if(map.containsKey("mfid")){
					sql.append(" and t.mfid = ").append(StringUtil.vString(map.get("mfid")));
				}
				if(map.containsKey("begin_mfid")){
					sql.append(" and t.mfid >= ").append(StringUtil.vString(map.get("begin_mfid")));
				}
				if(map.containsKey("end_mfid")){
					sql.append(" and t.mfid < ").append(StringUtil.vString(map.get("end_mfid")));
				}
			}
			if(map.containsKey("sql_mfid")){
				sql.append(" " + StringUtil.vString(map.get("sql_mfid")));
			}
			if(map.containsKey("field001")){
				sql.append(" and t.field001 = ").append(StringUtil.vString(map.get("field001")));
			}
			if(map.containsKey("begin_field001")){
				sql.append(" and t.field001 >= ").append(StringUtil.vString(map.get("begin_field001")));
			}
			if(map.containsKey("end_field001")){
				sql.append(" and t.field001 < ").append(StringUtil.vString(map.get("end_field001")));
			}
			if(map.containsKey("sql_field001")){
				sql.append(" " + StringUtil.vString(map.get("sql_field001")));
			}
			if(map.containsKey("field004")){
				sql.append(" and t.field004 = ").append(StringUtil.vString(map.get("field004")));
			}
			if(map.containsKey("begin_field004")){
				sql.append(" and t.field004 >= ").append(StringUtil.vString(map.get("begin_field004")));
			}
			if(map.containsKey("end_field004")){
				sql.append(" and t.field004 < ").append(StringUtil.vString(map.get("end_field004")));
			}
			if(map.containsKey("sql_field004")){
				sql.append(" " + StringUtil.vString(map.get("sql_field004")));
			}
			if(map.containsKey("field005")){
				sql.append(" and t.field005 = ").append(StringUtil.vString(map.get("field005")));
			}
			if(map.containsKey("begin_field005")){
				sql.append(" and t.field005 >= ").append(StringUtil.vString(map.get("begin_field005")));
			}
			if(map.containsKey("end_field005")){
				sql.append(" and t.field005 < ").append(StringUtil.vString(map.get("end_field005")));
			}
			if(map.containsKey("sql_field005")){
				sql.append(" " + StringUtil.vString(map.get("sql_field005")));
			}
			if(map.containsKey("field007")){
				sql.append(" and t.field007 = ").append(StringUtil.vString(map.get("field007")));
			}
			if(map.containsKey("begin_field007")){
				sql.append(" and t.field007 >= ").append(StringUtil.vString(map.get("begin_field007")));
			}
			if(map.containsKey("end_field007")){
				sql.append(" and t.field007 < ").append(StringUtil.vString(map.get("end_field007")));
			}
			if(map.containsKey("sql_field007")){
				sql.append(" " + StringUtil.vString(map.get("sql_field007")));
			}
			if(map.containsKey("field008")){
				sql.append(" and t.field008 = ").append(StringUtil.vString(map.get("field008")));
			}
			if(map.containsKey("begin_field008")){
				sql.append(" and t.field008 >= ").append(StringUtil.vString(map.get("begin_field008")));
			}
			if(map.containsKey("end_field008")){
				sql.append(" and t.field008 < ").append(StringUtil.vString(map.get("end_field008")));
			}
			if(map.containsKey("sql_field008")){
				sql.append(" " + StringUtil.vString(map.get("sql_field008")));
			}
			if(map.containsKey("field002")){
				sql.append(" and t.field002 = '").append(StringUtil.vString(map.get("field002"))).append("'");
			}
			if(map.containsKey("like_field002")){
				sql.append(" and t.field002 like '%").append(StringUtil.vString(map.get("like_field002"))).append("%'");
			}
			if(map.containsKey("sql_field002")){
				sql.append(" " + StringUtil.vString(map.get("sql_field002")));
			}
			if(map.containsKey("field003")){
				sql.append(" and t.field003 = '").append(StringUtil.vString(map.get("field003"))).append("'");
			}
			if(map.containsKey("like_field003")){
				sql.append(" and t.field003 like '%").append(StringUtil.vString(map.get("like_field003"))).append("%'");
			}
			if(map.containsKey("sql_field003")){
				sql.append(" " + StringUtil.vString(map.get("sql_field003")));
			}
			if(map.containsKey("field006")){
				sql.append(" and t.field006 = '").append(StringUtil.vString(map.get("field006"))).append("'");
			}
			if(map.containsKey("like_field006")){
				sql.append(" and t.field006 like '%").append(StringUtil.vString(map.get("like_field006"))).append("%'");
			}
			if(map.containsKey("sql_field006")){
				sql.append(" " + StringUtil.vString(map.get("sql_field006")));
			}
			if(map.containsKey("mfsql")){
				sql.append(" " + StringUtil.vString(map.get("mfsql")));
			}
			if(map.containsKey("sqlorderby")){
				sql.append(" order by " + StringUtil.vString(map.get("sqlorderby")));
			}else{
				sql.append(" order by t.field008, t.id ").append(StringUtil.vString(map.get("sqlsortway")).length() > 0 ? StringUtil.vString(map.get("sqlsortway")) : "desc");
			}
		}
		writeLog("sql>>>>>>>>>>>>>>>>>>"+sql.toString());
		rs.executeQuery(sql.toString());
    boolean isMysql = false;
    if(DialectUtil.isMySql(rs.getDBType())){
      isMysql = true;
    }
		
		String wfId = map != null && map.containsKey("wfId") ? StringUtil.vString(map.get("wfId")) : "";
		boolean canExeQuery = StringUtil.isNotNull(wfId) && StringUtil.parseToInt(wfId) != -1;
		List<Map<String, Object>> nList = canExeQuery ? executeQuery("select a.nodeId,b.nodeName,a.nodeType from  workflow_flownode a,workflow_nodebase b where (b.IsFreeNode is null or b.IsFreeNode!='1') and a.nodeId=b.id and a.workflowId="+wfId+" order by a.nodeType asc,a.nodeId asc") : null;
		List<Map<String, Object>> oList = canExeQuery ? executeQuery("select id,isreject,linkname,conditioncn from workflow_nodelink where workflowId = "+wfId) : null;

    List<Map<String, Object>> nList_tmp = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> oList_tmp = new ArrayList<Map<String, Object>>();
		reBuidldList(nList,oList,nList_tmp,oList_tmp);

		HrmAttProcAction bean = null;
		while(rs.next()){
			bean = new HrmAttProcAction();
			bean.setId(StringUtil.parseToLong(rs.getString("id")));
			bean.setMfid(StringUtil.parseToLong(rs.getString("mfid")));
			bean.setField001(StringUtil.parseToLong(rs.getString("field001")));
			bean.setField002(StringUtil.vString(rs.getString("field002")));
			bean.setField003(StringUtil.vString(rs.getString("field003")));
			bean.setField004(StringUtil.parseToInt(rs.getString("field004")));
			bean.setField005(StringUtil.parseToInt(rs.getString("field005")));
			bean.setField006(StringUtil.vString(rs.getString("field006"), "-1"));
			String field006 = bean.getField006().startsWith(",") ? bean.getField006() : "," + bean.getField006();
			field006 = field006.endsWith(",") ? field006 : field006 + ",";
			StringBuffer field006Name = new StringBuffer();
			switch(bean.getField005().intValue()) {
				case 0:
				if(oList_tmp != null) {
					String key = "linkname".toUpperCase();
					String idKey = "id".toUpperCase();
					//mysql环境下id这个不是大写
					for(Map<String, Object> _map : oList_tmp) {
            if(field006.indexOf(","+StringUtil.vString(_map.get(idKey))+",") != -1) {
              field006Name.append(field006Name.length() == 0 ? "" : ",").append(StringUtil.vString(_map.get(key)));
            }
					}
				}
				break;
			case 1:
			case 2:
				if(nList_tmp != null) {
					String key = "nodeName".toUpperCase();
					String idKey = "nodeId".toUpperCase();
					for(Map<String, Object> _map : nList_tmp) {
            if(field006.indexOf(","+StringUtil.vString(_map.get(idKey))+",") != -1) {
              field006Name.append(field006Name.length() == 0 ? "" : ",").append(StringUtil.vString(_map.get(key)));
            }
					}
				}
				break;
			}
			bean.setField006Name(field006Name.toString());
			bean.setField007(StringUtil.parseToInt(rs.getString("field007")));
			bean.setField008(StringUtil.parseToInt(rs.getString("field008")));
			list.add(bean);
		}
		return list;
	}

  private void reBuidldList(List<Map<String, Object>> nList, List<Map<String, Object>> oList, List<Map<String, Object>> nList_tmp, List<Map<String, Object>> oList_tmp) {
    if(nList != null && !nList.isEmpty()){
      for(Map<String, Object> _map : nList) {
        Map<String, Object> nMap_tmp = new HashMap<>();
        for(Map.Entry<String,Object> me : _map.entrySet()){
          String map_key = me.getKey();
          Object map_val = me.getValue();
          nMap_tmp.put(map_key.toUpperCase(), map_val);
        }
        if(!nMap_tmp.isEmpty()){
          nList_tmp.add(nMap_tmp);
        }
      }
    }
    if(oList != null && !oList.isEmpty()){
      for(Map<String, Object> _map : oList) {
        Map<String, Object> oMap_tmp = new HashMap<>();
        for(Map.Entry<String,Object> me : _map.entrySet()){
          String map_key = me.getKey();
          Object map_val = me.getValue();
          oMap_tmp.put(map_key.toUpperCase(), map_val);
        }
        if(!oMap_tmp.isEmpty()){
          oList_tmp.add(oMap_tmp);
        }
      }
    }
  }

  public HrmAttProcAction get(Comparable id) {
		HrmAttProcAction bean = null;
		Map<String, Comparable> map = new HashMap<String, Comparable>();
		map.put("id", id);
		List<HrmAttProcAction> list = find(map);
		if(list != null && list.size() > 0){
			bean = list.get(0);
		}
		return bean;
	}

	public void delete(Comparable id) {
    RecordSet rs = new RecordSet();
    String deleteSql = "delete from kq_ATT_PROC_ACTION where id in ( "+id+" )";
	boolean flag = rs.executeUpdate(deleteSql);
		writeLog("deleteSql>>>>>>>>>>>>>>>>"+deleteSql+">>>>>isOk>>>>"+flag);
	}

	public void delete(Map<String, Comparable> map) {
    RecordSet rs = new RecordSet();
		if(map == null || map.isEmpty()) return;
		StringBuffer sql = new StringBuffer();
		if((rs.getDBType()).equalsIgnoreCase("postgresql")) {
			sql.append("delete from kq_ATT_PROC_ACTION where mfid not in ('0', '5') ");
		} else {
			sql.append("delete from kq_ATT_PROC_ACTION where mfid not in (0, 5) ");
		}
		if(map.containsKey("field001")) sql.append(" and field001 = ").append(StringUtil.vString(map.get("field001")));
		boolean flag = rs.executeUpdate(sql.toString());
		writeLog("deleteSql>>>>>>>>>>>>>>>>"+sql.toString()+">>>>>>isOk>>>>"+flag);
	}
	
	public void deleteAction(int wfid) {
    RecordSet rs = new RecordSet();
//	  String attAction = "'deduction','freeze','release','HrmScheduleShift','HrmPaidLeaveAction',"
//        + "'KqSplitLeaveAction','KqSplitEvectionAction','KqSplitOutAction','KqSplitOvertimeAction',"
//        + "'KqSplitOtherAction','KqSplitLeavebackAction','KqSplitCardAction','KqFreezeSplitLeaveAction',"
//        + "'KqFreezeSplitEvectionAction','KqFreezeSplitOutAction','KqFreezeSplitOvertimeAction','KqFreezeSplitOtherAction',"
//        + "'KqFreezeSplitLeavbackAction','KqFreezeVacationAction','KqDeductionVacationAction','KqReleaseVacationAction',"
//        + "'KqPaidLeaveAction','KqSplitShiftAction'";
	  String attAction = "'deduction','freeze','release','HrmScheduleShift','HrmPaidLeaveAction',"
        + "'KqSplitAction','KqFreezeVacationAction','KqDeductionVacationAction','KqReleaseVacationAction',"
        + "'KqPaidLeaveAction'";
		rs.executeSql(new StringBuffer("delete from workflowactionset where workflowid = ").append(wfid).append(" and interfaceid in ("+attAction+")").toString());
	}
	
	public void updateBackFlag(int field005, int flag, int wfid, int nodeid) {
		updateBackFlag(field005, flag, wfid, String.valueOf(nodeid));
	}
	
	public void updateBackFlag(int field005, int flag, int wfid, String nodeid) {
    RecordSet rs = new RecordSet();
		if(field005 <= 0 || nodeid.equals("0") || nodeid.startsWith("0,")) return;
		String nodeField = "drawbackflag";
		if(field005 == 1) {
			nodeField = "rejectbackflag";
			flag = flag == 1 ? 0 : 1;
		}
		rs.executeSql("update workflow_flownode set "+nodeField+"="+flag+" where workflowid="+wfid+" and nodeid in ("+nodeid+")");
	}

}
