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

import com.engine.kq.wfset.attendance.domain.HrmAttProcSet;
import com.engine.kq.wfset.util.KQAttFlowCheckUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import weaver.common.StringUtil;
import com.engine.kq.wfset.attendance.framework.BaseManager;
import com.engine.kq.wfset.attendance.dao.HrmAttProcRelationDao;
import com.engine.kq.wfset.attendance.domain.HrmAttProcFields;
import com.engine.kq.wfset.attendance.domain.HrmAttProcRelation;
import com.engine.kq.wfset.attendance.domain.WorkflowBillfield;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

/**
 * HrmAttProcRelationManager
 * @author wcd
 * @version 1.0 2015-04-24
 */
public class HrmAttProcRelationManager extends BaseManager<HrmAttProcRelation> {

	private HrmAttProcRelationDao dao = null;

	public HrmAttProcRelationManager() {
		dao = new HrmAttProcRelationDao();
		this.setDao(dao);
	}

	public Long save(HrmAttProcRelation 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 void save(HttpServletRequest request, HrmAttProcSet hrmAttProcSet,Map<String,Object> retmap,
      User user) {
		String field001 = StringUtil.vString(request.getParameter("field001"));

		RecordSet rs = new RecordSet();
		Enumeration enu = request.getParameterNames();
		String field002 = "";
		String[] value = null;
		//多明细处理
    Map<String,String> detailMap = new HashMap<>();
    Map<String,String> mainMap = new HashMap<>();
    getDetailInfoBy(hrmAttProcSet.getField002(),detailMap,detailMap);
    List<String> detailnames = new ArrayList<>();

    int usedetail = hrmAttProcSet.getUsedetail();

    boolean isUseDetail = usedetail==1;
    boolean isMainDetail = false;
    if(hrmAttProcSet.getField006() == 7 || hrmAttProcSet.getField006() == 6 || hrmAttProcSet.getField006() == 8){
      isMainDetail = true;
    }
    if(isMainDetail){
      isUseDetail = true;
    }
    List<HrmAttProcRelation> hrmAttProcRelations = Lists.newArrayList();

		while(enu.hasMoreElements()) {
			field002 = StringUtil.vString(enu.nextElement());  
			if(field002.equalsIgnoreCase("field001") 
					|| field002.equalsIgnoreCase("cmd") 
					|| !field002.startsWith("select")) continue;
			value = StringUtil.getURLDecode(request.getParameter(field002)).split("___");
			if(value.length != 2) continue;
			String fieldid = value[1];
			String fieldname = value[0];
      String detailname = Util.null2String(detailMap.get(fieldid));

      HrmAttProcRelation bean = new HrmAttProcRelation();
			bean.setField001(StringUtil.parseToInt(field001));
			bean.setField002(StringUtil.parseToInt(field002.substring("select".length())));
			bean.setField003(StringUtil.parseToInt(fieldid));
			bean.setField004(StringUtil.vString(fieldname));
      if(!isMainDetail){
        if(isUseDetail && (detailname == null || detailname.length() == 0)){
          retmap.put("status", "-1");
          retmap.put("message",  SystemEnv.getHtmlLabelName(500734,user.getLanguage()));
          return ;
        }
      }
      if(isUseDetail && detailname != null && detailname.length() > 0){
        if(detailnames.isEmpty()){
          detailnames.add(detailname);
        }else{
          //表明多明细下字段对应了两种
          if(!detailnames.contains(detailname)){
            retmap.put("status", "-1");
            retmap.put("message",  SystemEnv.getHtmlLabelName(500735,user.getLanguage()));
            return ;
          }
        }
      }
      int att_fieldid = bean.getField002();
//      0表示请假，1表示出差，2表示公出，3表示加班，4表示异常，5表示调班，6表示销假，7表示补卡
      int kqtype = hrmAttProcSet.getField006();
      int workflowid = hrmAttProcSet.getField001();
//      String sql = "select * from kq_att_proc_fields where id = ?  ";
//      rs.executeQuery(sql, att_fieldid);
//      if(rs.next()){
//        String fields_field002 = rs.getString("field002");
//        Map<String,String> map = Maps.newConcurrentMap();
//        if(0 == kqtype){
//          if("duration".equalsIgnoreCase(fields_field002) || "detail_duration".equalsIgnoreCase(fields_field002)){
//            KQAttFlowCheckUtil.duration_edit_check_new(fieldid, map,workflowid);
//          }
//        }else if(1 == kqtype){
//          if("duration".equalsIgnoreCase(fields_field002) || "detail_duration".equalsIgnoreCase(fields_field002)){
//            KQAttFlowCheckUtil.duration_edit_check_new(fieldid, map, workflowid);
//          }
//        }else if(2 == kqtype){
//          if("duration".equalsIgnoreCase(fields_field002) || "detail_duration".equalsIgnoreCase(fields_field002)){
//            KQAttFlowCheckUtil.duration_edit_check_new(fieldid, map, workflowid);
//          }
//        }else if(3 == kqtype){
//          if("duration".equalsIgnoreCase(fields_field002) || "detail_duration".equalsIgnoreCase(fields_field002)){
//            KQAttFlowCheckUtil.duration_edit_check_new(fieldid, map, workflowid);
//          }
//        }else if(6 == kqtype){
//          if("detail_duration".equalsIgnoreCase(fields_field002)){
//            KQAttFlowCheckUtil.duration_edit_check_new(fieldid, map, workflowid);
//          }
//        }else if(8 == kqtype){
//          if("detail_duration".equalsIgnoreCase(fields_field002)){
//            KQAttFlowCheckUtil.duration_edit_check_new(fieldid, map, workflowid);
//          }
//        }
//        if(!map.isEmpty()){
//          retmap.put("status", "-1");
//          retmap.put("message",  Util.null2String(map.get("msgAttError")));
//          return ;
//        }
//      }

      hrmAttProcSet.setDetailtablename(detailname);
      hrmAttProcRelations.add(bean);

		}
    delete(getMapParam("field001:"+field001));

		if(!hrmAttProcRelations.isEmpty()){
		  for(HrmAttProcRelation hrmAttProcRelation : hrmAttProcRelations){
        insert(hrmAttProcRelation);
      }
    }
	}

	public void getDetailInfoBy(Integer formid,Map<String,String> detailMap,Map<String,String> mainMap){
    RecordSet rs = new RecordSet();
	  String detailSql = "select * from workflow_billfield where billid = ? ";
    rs.executeQuery(detailSql, formid);
    while (rs.next()){
      String fieldid = rs.getString("id");
      String detailtable = rs.getString("detailtable");
      detailMap.put(fieldid, detailtable);
    }
  }


	public void save(List<HrmAttProcRelation> list) {
		dao.insert(list);
	}
	
	public void initRelation(Long id, List<HrmAttProcFields> list, List<WorkflowBillfield> fieldList) {
		if(list == null || fieldList == null || id == null) return;
		
		HrmAttProcRelation bean = null;
		for(HrmAttProcFields fBean : list){
			bean = new HrmAttProcRelation();
			bean.setField001(id.intValue());
			bean.setField002(fBean.getId().intValue());
			for(WorkflowBillfield wfBean : fieldList){
				if(!fBean.getField002().equalsIgnoreCase(wfBean.getFieldname())) continue;
				bean.setField003(wfBean.getId());
				bean.setField004(wfBean.getFieldname());
				break;
			}
			insert(bean);
		}
	}

}
