package nccloud.hrkq.hrkq.monthottimevo.action;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import nc.bs.logging.Logger;
import nc.itf.om.IPostQueryService;
import nc.vo.hi.psndoc.PsnJobVO;
import nc.vo.hrkq.monthottime.AggMonthOtTimeVO;
import nc.vo.hrkq.monthottime.MonthOtTimeBVO;
import nc.vo.hrkq.monthottime.MonthOtTimeVO;
import nc.vo.om.post.AggPostVO;
import nc.vo.om.post.PostVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.ui.pattern.billcard.BillCardOperator;
import nccloud.hrkq.hrkq.monthottimevo.hrkq.util.CommonUtil;
import nccloud.itf.hrkq.hrkq.IMonthottimevoMaintain;
import nccloud.vo.hrkq.hrkq.MonthOtTimeVOConst;
import nccloud.web.hr.pub.HRNccTemplateUtils;
import nccloud.web.hrkq.common.utils.AttendDataUtil;
import nccloud.web.uapbd.commons.web.ParamUtils;

public class MonthOtTimeVOCheckSaveAction implements ICommonAction {

	@Override
	public Object doAction(IRequest request) {
		ParamUtils param = new ParamUtils(request);
		Object obj = param.get("formData");
		IJson json = JsonFactory.create();
		MonthOtTimeBVO[] bvos = HRNccTemplateUtils.getVOFromGrid(MonthOtTimeBVO.class, json.toJson(obj));
		String appCode = param.getString("appCode",SessionContext.getInstance().getAppcode());
		String userid = SessionContext.getInstance().getClientInfo().getUserid();
		PsnJobVO psnJob = AttendDataUtil.queryPsnJob(null);
		MonthOtTimeVO vo = new MonthOtTimeVO();
		BillCardOperator billCardOperator = new BillCardOperator();
		String otapplytype = "";
		if("606570D0".equals(appCode)) {
			//按次
//			vo.setAttributeValue("otapplytype", "1");
			otapplytype = "1";
		}else if("606570C0".equals(appCode) || "606570E0".equals(appCode)) {
			//普通
//			vo.setAttributeValue("otapplytype", "2");
			otapplytype = "2";
		}
		AggMonthOtTimeVO aggVO = new AggMonthOtTimeVO();
		aggVO.setParentVO(vo);
		for(MonthOtTimeBVO bvo : bvos) {
			if(bvo.getAttributeValue("otdate") != null) {
				bvo.setAttributeValue("otdate",new UFDateTime(bvo.getAttributeValue("otdate").toString()).getDate());
			}
			if(bvo.getAttributeValue("overtimebegintime") != null) {
				bvo.setAttributeValue("otdate",new UFDateTime(bvo.getAttributeValue("overtimebegintime").toString()).getDate());
			}
		}
		
		String parentPk = vo.getPrimaryKey();
		PsnJobVO psnjobVO = AttendDataUtil.queryPsnJob(null);
		nc.vo.hrkq.monthottime.MonthOtTimeVO parent = aggVO.getParentVO();
	    parent.setAttributeValue(MonthOtTimeVO.PK_PSNDOC,psnjobVO.getPk_psndoc());
	    parent.setAttributeValue(MonthOtTimeVO.PK_DEPT,psnjobVO.getPk_dept());
	    parent.setAttributeValue(MonthOtTimeVO.PK_ORG,psnjobVO.getPk_org());
	    parent.setAttributeValue(MonthOtTimeVO.APPLYDATE,new UFDate());
	    parent.setAttributeValue(MonthOtTimeVO.BILLTYPE,MonthOtTimeVOConst.CONST_BILLTYPE_COST);
	    parent.setAttributeValue(MonthOtTimeVO.APPROVESTATUS, -1);
		String pk_psndoc = (String) parent.getAttributeValue(MonthOtTimeVO.PK_PSNDOC);
		String result = "";
		try {
		    if(bvos != null && bvos.length > 0) {
		    	//加班类型,1为按次ottimestype，2为普通otdatetype
		    	IMonthottimevoMaintain service = ServiceLocator.find(IMonthottimevoMaintain.class);
		    	List<Map<String, UFDate>> listMap = service.queryHoliday(pk_psndoc, psnjobVO.getPk_org());
		    	List<String> defdocList = service.queryDefdoc();//查询节假日类型主键
		    	String msg = "";
		    	String msg2 = "";
		    	for(MonthOtTimeBVO bvo : bvos) {
		    		if(bvo.getAttributeValue(MonthOtTimeBVO.OTDATE) == null) {
		    			continue;
		    		}
		    		UFDate otdate = new UFDate(bvo.getAttributeValue(MonthOtTimeBVO.OTDATE).toString());//加班日期是否为节假日
		    		String type = "";
		    		if("1".equals(otapplytype)) {//按次
		    			type = (String) bvo.getAttributeValue(MonthOtTimeBVO.OTTIMESTYPE);
		    		}else if("2".equals(otapplytype)) {//普通
		    			type = (String) bvo.getAttributeValue(MonthOtTimeBVO.OTDATETYPE);
		    		}
		    		if(this.checkDate(otdate, listMap)) {
		    			if(type.length() > 0 && !defdocList.contains(type)) {
		    				msg = "["+otdate.toString().substring(0,10)+"],";
		    			}
		    		} else {
		    			if(type.length() > 0 && defdocList.contains(type)) {
		    				msg2 = "["+otdate.toString().substring(0,10)+"],";
		    			}
		    		}
		    	}
		    	if(msg.length() > 0 && msg2.length() > 0) {
		    		result = "加班日期"+msg+"属于节假日加班,加班日期"+msg2+"不属于节假日加班，请选择正确的加班类型";
		    	}else if(msg.length() > 0) {
		    		result = "加班日期"+msg+"属于节假日加班，请选择正确的加班类型";
		    	}else if(msg2.length() > 0) {
		    		result = "加班日期"+msg2+"不属于节假日加班，请选择正确的加班类型";
		    	}
		    }
		    String pk_post = psnjobVO.getPk_post();
		    if(StringUtils.isNotBlank(pk_post)) {
		    	aggVO.setChildrenVO(bvos);
		    	AggPostVO aggPostVO = ServiceLocator.find(IPostQueryService.class).queryByPk(pk_post);
		    	if(aggPostVO != null) {
			    	PostVO postVO = (PostVO) aggPostVO.getParentVO();
			    	Object glbdef1 = postVO.getAttributeValue("glbdef1");
			    	if(glbdef1 == null || !UFBoolean.valueOf(glbdef1.toString()).booleanValue()) {
			    		doBeforeCheck(aggVO);
			    	}
		    	}
		    }
		    if("1".equals(otapplytype)) {//按次
		    	String dateCheckMsg = CommonUtil.checkSelfTimes(bvos);
			    if(dateCheckMsg != null) {
			    	throw new BusinessException("加班时间范围内存在冲突的加班单据，冲突时间："+dateCheckMsg);
			    }
			    List<MonthOtTimeBVO> oldBvos = CommonUtil.getMaintainService().queryBVOByPkPsndoc(pk_psndoc);
			    if(oldBvos != null && oldBvos.size() > 0) {
			    	String dateTwoCheckMsg = CommonUtil.checkTwoListTimes(bvos,oldBvos.toArray(new MonthOtTimeBVO[0]));
			    	if(dateTwoCheckMsg != null) {
			    		throw new BusinessException("加班时间范围内存在冲突的加班单据，冲突时间："+dateTwoCheckMsg);
			    	}
			    }
		    }else if("2".equals(otapplytype)) {//普通
			    String dateCheckMsg = CommonUtil.checkSelf(bvos);
			    if(dateCheckMsg != null) {
			    	throw new BusinessException("加班时间范围内存在冲突的加班单据，冲突时间："+dateCheckMsg);
			    }
			    List<MonthOtTimeBVO> oldBvos = CommonUtil.getMaintainService().queryBVOByPkPsndoc(pk_psndoc);
			    if(oldBvos != null && oldBvos.size() > 0) {
			    	String dateTwoCheckMsg = CommonUtil.checkTwoList(bvos,oldBvos.toArray(new MonthOtTimeBVO[0]));
			    	if(dateTwoCheckMsg != null) {
			    		throw new BusinessException("加班时间范围内存在冲突的加班单据，冲突时间："+dateCheckMsg);
			    	}
			    }
		    }
		    
		}catch (BusinessException ex) {
			Logger.error(ex.getMessage(), ex);
			ExceptionUtils.wrapException(ex);
			return ex.getMessage();
		}
		return result;
	}

	private void doBeforeCheck(AggMonthOtTimeVO aggvo) throws BusinessException {
		  String msg = "";
		  IMonthottimevoMaintain service = CommonUtil.getMaintainService();
		  Boolean checkFlag = Boolean.FALSE;
		  MonthOtTimeVO vo = aggvo.getParentVO();
		  String otapplytype = (String) vo.getAttributeValue(MonthOtTimeVO.OTAPPLYTYPE);
		  if("1".equals(otapplytype)) {
		  }else {
			  String pk_psndoc = (String) vo.getAttributeValue(MonthOtTimeVO.PK_PSNDOC);
			  Map<String, UFDouble> map = service.queryMonth(pk_psndoc);
			  UFDouble totalHours = UFDouble.ZERO_DBL;
			  MonthOtTimeBVO[] bvos = (MonthOtTimeBVO[]) aggvo.getChildrenVO();
			  if(map != null && bvos != null && bvos.length > 0) {
				  for(MonthOtTimeBVO bvo : bvos) {
					  UFDate otdate = bvo.getAttributeValue(MonthOtTimeBVO.OTDATE) == null ? ((UFDateTime)bvo.getAttributeValue(MonthOtTimeBVO.OVERTIMEBEGINTIME)).getDate() : (UFDate) bvo.getAttributeValue(MonthOtTimeBVO.OTDATE);
					  if(otdate != null) {
						  String monthday = dateToStr(otdate);
						  UFDouble hours = map.get(monthday) == null ? UFDouble.ZERO_DBL : map.get(monthday);
						  UFDouble othours = bvo.getAttributeValue(MonthOtTimeBVO.OTHOURS) == null ? UFDouble.ZERO_DBL : (UFDouble) bvo.getAttributeValue(MonthOtTimeBVO.OTHOURS);
						  totalHours = hours.add(othours);
						  if(totalHours.toDouble() > 36) {
							  checkFlag = Boolean.TRUE;
						  }
					  }
				  }
			  }
			  if(checkFlag) {
				  throw new BusinessException("本月加班时长超过36小时，不允许发起申请");
			  }
		  }
	  }
	
	public String DATE_FORMAT_Y_M_DHM = "yyyy-MM";
	public String dateToStr(UFDate date) {
	    String strDate = "";
	    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_Y_M_DHM);
	    strDate = sdf.format(date.toDate());
	    return strDate;
	}
	
	/**
     * 判断日期是否符合节假日时间
     * @param otdate
     * @param listMap
     * @return
     */
    private Boolean checkDate(UFDate otdate,List<Map<String, UFDate>> listMap) {
  	  Boolean check = Boolean.FALSE;
  	  if(listMap != null) {
  			for(Map<String, UFDate> map : listMap) {
  				UFDate begindate = map.get("begintime");
  				UFDate enddate = map.get("endtime");
  				if(otdate.compareTo(begindate) >= 0 && otdate.compareTo(enddate) <= 0) {
  					check = Boolean.TRUE;
  					break;
  				}
  			}
  		}
  	  
  	  return check;
    }
}
