package com.kingdee.shr.customer.gtiit.handler;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.framework.CoreBaseCollection;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.ats.AtsOverTimeBillEntryCollection;
import com.kingdee.eas.hr.ats.AtsOverTimeBillEntryFactory;
import com.kingdee.eas.hr.ats.AtsOverTimeBillEntryInfo;
import com.kingdee.eas.hr.ats.AtsOverTimeBillInfo;
import com.kingdee.eas.hr.ats.FillSignCardEntryCollection;
import com.kingdee.eas.hr.ats.FillSignCardEntryFactory;
import com.kingdee.eas.hr.ats.FillSignCardEntryInfo;
import com.kingdee.eas.hr.ats.FillSignCardInfo;
import com.kingdee.eas.hr.ats.FillSignReasonFactory;
import com.kingdee.eas.hr.ats.FillSignReasonInfo;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.ats.web.handler.FillSignCardEditHandler;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.shr.customer.gtiit.util.BaseUtil;
import com.kingdee.util.LocaleUtils;

public class FillSignCardEditHandlerEx extends FillSignCardEditHandler{
	
	private static Logger logger =
	        Logger.getLogger("com.kingdee.shr.customer.gtiit.handler.FillSignCardEditHandlerEx");
	
	@Override
	protected void verifyModel(HttpServletRequest request, HttpServletResponse response, CoreBaseInfo model)
			throws SHRWebException {
		logger.error("进入补签卡校验");
		Context ctx = SHRContext.getInstance().getContext();
		FillSignCardInfo fillSignCardInfo = (FillSignCardInfo) model;
		FillSignCardEntryCollection entries = fillSignCardInfo.getEntries();
		Set<String> personIdSet = new HashSet<>(); 
		Map<String, Integer> personMap = new HashMap<>();
		for(int i=0;i<entries.size();i++) {
			String personId = entries.get(i).getPerson().getId().toString();
			Date attendDate = entries.get(i).getAttendDate();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(attendDate);
			String month = calendar.get(Calendar.MONTH)+1 >9?String.valueOf(calendar.get(Calendar.MONTH)+1):"0"+String.valueOf(calendar.get(Calendar.MONTH)+1);
			String mapKey = personId+calendar.get(Calendar.YEAR)+month;
			personIdSet.add(personId);
			FillSignReasonInfo fillSignReasonInfo = null;
			try {
				fillSignReasonInfo = FillSignReasonFactory.getLocalInstance(ctx).getFillSignReasonInfo(new ObjectUuidPK(entries.get(i).getReason().getId().toString()));
			} catch (EASBizException e) {
				e.printStackTrace();
			} catch (BOSException e) {
				e.printStackTrace();
			}
			if(fillSignReasonInfo!=null && "001".equals(fillSignReasonInfo.getNumber())) {
				if(personMap.containsKey(mapKey)) {
					personMap.put(mapKey, personMap.get(mapKey)+1);
				}else {
					personMap.put(mapKey, 1);
				}
			}
		}
		Map<String, String> personNameMap = BaseUtil.getPersonIdByName(ctx, personIdSet);
		logger.error("人员ID集合："+personIdSet);
		logger.error("补卡信息集合："+personMap);
		StringBuffer str = new StringBuffer();
		for(String personId:personIdSet) {
			str.append("'"+personId+"',");
		}
		if(str.length()>0) {
			String sql = "SELECT b.FPERSONID,count(1) count,year(b.FATTENDDATE) year ,month(b.FATTENDDATE) month FROM T_HR_ATS_FillSignCard a left join T_HR_ATS_FillSignCardEntry b on a.fid=b.fbillid left join T_HR_ATS_FillSignReason c on c.fid=b.freasonid "
					+ "where c.FNUMBER = '001' and a.FBILLSTATE in ('2','3') and b.FPERSONID in ("+str.substring(0, str.length()-1)+") group by b.FPERSONID,year(b.FATTENDDATE),month(b.FATTENDDATE) ";
			logger.error("查询补签信息SQL："+sql);
			try {
				IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
				while(rowSet.next()) {
					int count = rowSet.getInt("count");
					String personId = rowSet.getString("FPERSONID");
					String month = rowSet.getString("month").length()>1?rowSet.getString("month"):"0"+rowSet.getString("month");
					String mapKey = personId + rowSet.getString("year") + month;
					if(personMap.containsKey(mapKey)) {
						personMap.put(mapKey, personMap.get(mapKey)==null?0:personMap.get(mapKey)+count);
					}
				}
			} catch (BOSException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		logger.error("人员ID集合："+personIdSet);
		logger.error("人员编码映射："+personNameMap);
		logger.error("补卡信息集合："+personMap);
		for(String key:personMap.keySet()) {
			if(personMap.get(key) > 3) {
				String period = key.substring(key.length()-6);
				String personId = key.substring(0,key.length()-6);
				String personName = personNameMap.get(personId);
				throw new ShrWebBizException("Employee ("+personName+") forgot to clock in more than three times during the period ("+period+")");
			}
		}
		super.verifyModel(request, response, model);
	}

	public void getToremarksAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
			throws SHRWebException {
		Context ctx = SHRContext.getInstance().getContext();
		try {
			//单据ID
			String billId = request.getParameter("billId");
			if(StringUtils.isBlank(billId)) {
				return;
			}
			FillSignCardEntryCollection entryColl = FillSignCardEntryFactory.getLocalInstance(ctx).getFillSignCardEntryCollection("where bill = '"+billId+"'");
			for(int i = 0; i<entryColl.size();i++) {
				FillSignCardEntryInfo fillSignCardEntryInfo = entryColl.get(i);
				modelMap.put(fillSignCardEntryInfo.getId().toString(), fillSignCardEntryInfo.get("toremarks"));
			}
		} catch (BOSException e) {
			e.printStackTrace();
		}
		JSONUtils.writeJson(response, modelMap);
	}

}
