package com.kingdee.shr.compensation.web.handler.integrate;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.customer.util.handler.ConfigurationHandler;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.compensation.app.integrate.BatchSubmitShemeBillEntryCollection;
import com.kingdee.shr.compensation.app.integrate.BatchSubmitShemeBillEntryInfo;
import com.kingdee.shr.compensation.app.integrate.BatchSubmitShemeBillInfo;
import com.kingdee.shr.customer.gtiit.util.DateTimeUtils;

public class BatchSubmitSchemeUtils {

	private static Logger logger =
	        Logger.getLogger("com.kingdee.shr.compensation.web.handler.integrate.BatchSubmitSchemeUtils");
	
	/**
	 * 校验只能提交发生日期和提报日期在一个月内的单据
	 * @param info
	 * @throws ShrWebBizException
	 */
	public static void checkSubmitDate(BatchSubmitShemeBillInfo info) throws ShrWebBizException{
		Calendar calendar = Calendar.getInstance();
		//提报日期
		Date applyDate = info.getApplyDate();
		calendar.setTime(applyDate);
		int thisYear = calendar.get(Calendar.YEAR);
		int thisMonth = calendar.get(Calendar.MONTH);
		BatchSubmitShemeBillEntryCollection entryColl = info.getEntry();
		for(int i=0;i<entryColl.size();i++) {
			BatchSubmitShemeBillEntryInfo entryInfo = entryColl.get(i);
			Date effectDate = entryInfo.getEffectDate();
			calendar.setTime(effectDate);
			int effectYear = calendar.get(Calendar.YEAR);
			int effectMonth = calendar.get(Calendar.MONTH);
			if(thisYear != effectYear || thisMonth != effectMonth) {
				throw new ShrWebBizException("The occurrence date of the entry should be consistent with the reporting date");
			}
		}
	}
	
	/**
	 * 校验调整后的发生日期是否在所选的发薪任职日期范围内
	 * @param info
	 * @throws ShrWebBizException
	 */
	public static void checkSubmitAdjust(BatchSubmitShemeBillInfo info) throws ShrWebBizException{
		Context ctx = SHRContext.getInstance().getContext();
		String sql = "select top 1 * from T_HR_SHRRsvItem0 where fnumber = '1005' and FState = '1'";
		logger.error("获取调整月份SQL："+sql);
		//调整月份
		int adjustMonth = 0; 
		try {
			IRowSet rs = DbUtil.executeQuery(ctx, sql);
			while(rs.next()) {
				adjustMonth = rs.getInt("FName_l2");
			}
			Date applyDate = info.getApplyDate();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(applyDate);
			calendar.add(Calendar.MONTH, adjustMonth);
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			
			String adjustDate = DateTimeUtils.dateFormat(calendar.getTime(), "yyyy-MM-dd");
			
			BatchSubmitShemeBillEntryCollection entryColl = info.getEntry();
			List<String> personIdList = new ArrayList<String>();
			List<String> cmpEmpOrgIdList = new ArrayList<String>();
			for(int i=0;i<entryColl.size();i++) {
				BatchSubmitShemeBillEntryInfo entryInfo = entryColl.get(i);
				personIdList.add(entryInfo.getPerson().getId().toString());
				cmpEmpOrgIdList.add(entryInfo.getCmpEmpORelation().getId().toString());
			}
			
			StringBuffer strBuffer = new StringBuffer();
	        for (int i = 0; i < cmpEmpOrgIdList.size(); i++) {
	        	strBuffer.append("'"+cmpEmpOrgIdList.get(i)+"'");
	            if (i != cmpEmpOrgIdList.size() - 1) {
	            	strBuffer.append(", ");
	            }
	        }
			
			String empOrgSql = "/*dialect*/SELECT c.fnumber,c.fid FROM T_HR_SCmpEmpORelation a "
					+ "left join T_HR_EmpOrgRelation b on a.femporgrelationid = b.fid "
					+ "left join T_BD_Person c on a.FPERSONID = c.fid "
					+ "where b.feffdt <= '"+adjustDate+"' and b.fleffdt >= '"+adjustDate+"' "
					+ "and a.fid in ("+strBuffer.toString()+")";
			logger.error("获取员工发薪任职日期SQL："+empOrgSql);
			IRowSet empRowSet = DbUtil.executeQuery(ctx, empOrgSql);
			List<String> empPerIdList = new ArrayList<String>();
			while(empRowSet.next()) {
				empPerIdList.add(empRowSet.getString("fid"));
			}
			
			StringBuffer personIdBuffer = new StringBuffer();
			for(String personId:personIdList) {
				if(!empPerIdList.contains(personId)) {
					personIdBuffer.append("'"+personId+"',");
				}
			}
			
			if(personIdBuffer.length()>0) {
				personIdBuffer = personIdBuffer.deleteCharAt(personIdBuffer.length()-1);
				String personSql = "select fnumber from T_BD_Person where fid in ("+personIdBuffer+")";
				IRowSet personRowSet = DbUtil.executeQuery(ctx, personSql);
				StringBuffer numberBuffer = new StringBuffer();
				while(personRowSet.next()) {
					numberBuffer.append("'"+personRowSet.getString("fnumber")+"',");
				}
				numberBuffer = numberBuffer.deleteCharAt(numberBuffer.length()-1);
				throw new ShrWebBizException("The following employees: ("+numberBuffer.toString()+") The adjusted occurrence date is not within the range of salary and employment dates");
			}
			
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 校验员工+方案+发生日期不能重复
	 * @param info
	 * @throws ShrWebBizException
	 */
	public static void checkSubmitRepeat(BatchSubmitShemeBillInfo info) throws ShrWebBizException{
		Context ctx = SHRContext.getInstance().getContext();
		BatchSubmitShemeBillEntryCollection entryColl = info.getEntry();
		String submitSchemeId = info.getSubmitScheme().getId().toString();
		StringBuffer personBuffer = new StringBuffer();
		for(int i=0;i<entryColl.size();i++) {
			BatchSubmitShemeBillEntryInfo entryInfo = entryColl.get(i);
			personBuffer.append("'"+entryInfo.getPerson().getId().toString()+"',");
		}
		personBuffer = personBuffer.deleteCharAt(personBuffer.length()-1);
		
		Date applyDate = info.getApplyDate();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(applyDate);
		int applyYear = calendar.get(Calendar.YEAR);
		int applyMonth = calendar.get(Calendar.MONTH)+1;
		
		String sql = "SELECT c.fnumber FROM T_HR_SBatchSubmitShemeBill a left join T_HR_SchemeBillEntry b on  a.fid = b.fbillid left join T_BD_Person c on b.FPERSONID = c.fid where a.FSUBMITSCHEMEID = '"+submitSchemeId+"' and year(b.FEFFECTDATE) = "+applyYear+" and month(b.FEFFECTDATE) = "+applyMonth+" and a.FBILLSTATE in ('1','2','3') and a.FDATASOURCE = '2' and b.FPERSONID in ("+personBuffer.toString()+") ";
		logger.error("获取员工提报SQL："+sql);
		try {
			IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
			StringBuffer numberBuffer = new StringBuffer();
			while(rowSet.next()) {
				numberBuffer.append("'"+rowSet.getString("fnumber")+"',");
			}
			if(numberBuffer.length()>0) {
				numberBuffer = numberBuffer.deleteCharAt(numberBuffer.length()-1);
				throw new ShrWebBizException("The following employees ("+numberBuffer+") have submitted data for this plan with an occurrence date of that month");
			}
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 校验员工+提报月+方案只能提交一次
	 * @throws ShrWebBizException
	 */
	public static void checkSubmitCount(BatchSubmitShemeBillInfo info) throws ShrWebBizException{
		Context ctx = SHRContext.getInstance().getContext();
		String personId = ContextUtil.getCurrentUserInfo(ctx).getPerson().getId().toString();
		String proposerId = info.getProposer().getId().toString();
		String submitSchemeId = info.getSubmitScheme().getId().toString();
		if(!StringUtils.equals(personId, proposerId)) {
			throw new ShrWebBizException("Only self created documents can be submitted");
		}
		//提报日期
		Date applyDate = info.getApplyDate();
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(applyDate);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		String startDate = DateTimeUtils.dateFormat(calendar.getTime(), "yyyy-MM-dd");
		calendar.add(Calendar.MONTH, 1);
		String endDate = DateTimeUtils.dateFormat(calendar.getTime(), "yyyy-MM-dd");
		
		int count = 0;
		String sql = "select count(1) count from T_HR_SBatchSubmitShemeBill where FPROPOSERID  = '"+personId+"' and fbillstate in ('1','2','3') "
				+ "and fdatasource = '2' and fapplydate >= '"+startDate+"' and fapplydate < '"+endDate+"' and FSUBMITSCHEMEID = '"+submitSchemeId+"'";
		logger.error("查询员工当月提交次数SQL："+sql);
		try {
			IRowSet iRowSet = DbUtil.executeQuery(ctx, sql);
			while(iRowSet.next()) {
				count = iRowSet.getInt("count");
			}
			logger.error("员工该方案当月提交次数："+count);
			if(count>0) {
				throw new ShrWebBizException("Your proposal has been submitted in the month of submission and cannot be resubmitted");
			}
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 校验分录人员是否重复
	 * @param info
	 * @throws ShrWebBizException
	 */
	public static void checkPersonRepeat(BatchSubmitShemeBillInfo info) throws ShrWebBizException{
		BatchSubmitShemeBillEntryCollection entryColl = info.getEntry();
		Set<String> personIdSet = new HashSet<String>();
		for(int i=0;i<entryColl.size();i++) {
			BatchSubmitShemeBillEntryInfo entryInfo = entryColl.get(i);
			PersonInfo person = entryInfo.getPerson();
			if(person != null) {
				personIdSet.add(person.getId().toString());
			}
		}
		if(personIdSet.size() != entryColl.size()) {
			throw new ShrWebBizException("Entries can only have one row of data per person");
		}
	}
	
	/**
	 * 参数校验
	 * @param info
	 * @throws ShrWebBizException 
	 */
	public static void checkExists(BatchSubmitShemeBillInfo info) throws ShrWebBizException{
		Context ctx = SHRContext.getInstance().getContext();
		int day = 0;
		Calendar calendar = Calendar.getInstance();
		int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
		try {
			String paramSql = "SELECT FNUMBER,fname_l2 name FROM T_HR_SHRRSVITEM0 where fstate = '1' and FNUMBER = '1002'";
			IRowSet paramRow = DbUtil.executeQuery(ctx, paramSql);
			while(paramRow.next()) {
				day = paramRow.getObject("name")==null?0:paramRow.getInt("name");
			}
			//最后提交日期校验
			if(day != 0 && thisDay > day) {
				throw new ShrWebBizException(" documents have passed the last submission date !");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (BOSException e) {
			e.printStackTrace();
		}
	}
	
}
