package com.kingdee.shr.ats.web.handler;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

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

import com.kingdee.eas.custom.facade.leave.LeaveAllowanceFacadeFactory;
import com.kingdee.util.DateTimeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
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.SHRWebException;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;

public class HolidayLimitListHandlerEx extends HolidayLimitListHandler{
	
	/**
	 * 年假额度生成
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 * @throws SHRWebException
	 * @throws BOSException 
	 */
	public String annualLeaveAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException, BOSException {

		//1、获取当前年
		Context ctx = SHRContext.getInstance().getContext();
	    Calendar cal = Calendar.getInstance();
	    int year = cal.get(1);
	    StringBuffer annualSql = new StringBuffer();
	    
	    annualSql.append("  /*dialect*/ update a set a.CFLastCarryforward = b.lastRemainLimit ,  a.FRemainLimit = (a.FStandardLimit + b.lastRemainLimit - a.FUsedLimit - a.FreezeLimit - a.FPreOverdraftLimit)  ");
	    annualSql.append(" from  T_HR_ATS_HolidayLimit as a ");
	    annualSql.append(" left join  ( ");
	    annualSql.append("  select  case when d.FNumber = 'GTIIT_FACULTY' or d.FNumber = 'GTIIT_OTHER'   ");
	    annualSql.append("   then (case when (isnull(b.FRemainLimit,0) + a.FStandardLimit) > c.CFFae  then (c.CFFae - isnull(b.FStandardLimit,0)) else isnull(b.FRemainLimit,0) end )  ");
	    annualSql.append("  else (case when (isnull(b.FRemainLimit,0) + a.FStandardLimit) > 30 then (30 - isnull(b.FStandardLimit,0))  else isnull(b.FRemainLimit,0) end ) end as lastRemainLimit ,a.fid  ");
	    annualSql.append("  from T_HR_ATS_HolidayLimit a  ");
	    annualSql.append("  left join (select * from T_HR_ATS_HolidayLimit where FYear = '" + (year - 1) +  "' and FHolidayPolicyID = 'G+WlV0oQT9WDnd/Wk4hxgV/BCRA=' ) as b on a.FProposerID = b.FProposerID ");
	    annualSql.append(" inner join  t_bd_person as c  on  a.FProposerID = c.fid    ");
	    annualSql.append("  left join CT_MP_WorkerCategory d on c.CFWorkercategoryID = d.fid   ");
	    annualSql.append(" where a.FYear = '" + year + "'  and a.FHolidayPolicyID = 'G+WlV0oQT9WDnd/Wk4hxgV/BCRA='  ) b on a.FID  = b.fid ");
	    annualSql.append(" where a.FYear = '" + year + "'  and a.FHolidayPolicyID = 'G+WlV0oQT9WDnd/Wk4hxgV/BCRA='  ");
		System.out.println("年假额度生成："+ annualSql);
		DbUtil.execute(ctx, annualSql.toString());

		StringBuffer lastAnnualSql = new StringBuffer();
		lastAnnualSql.append("  /*dialect*/ update a set ");
		lastAnnualSql.append(" CFCarryforward = isnull(b.lastRemainLimit,0) , FRemainLimit = FRealLimit - FUsedLimit - FreezeLimit - isnull(b.lastRemainLimit,0)  ");
	    lastAnnualSql.append(" from T_HR_ATS_HolidayLimit a ");
	    lastAnnualSql.append(" left join ( select b.CFLastCarryforward as lastRemainLimit ,a.fid  ");
	    lastAnnualSql.append(" from T_HR_ATS_HolidayLimit a ");
	    lastAnnualSql.append(" left join (select * from T_HR_ATS_HolidayLimit where FYear = '" + year +  "' and FHolidayPolicyID = 'G+WlV0oQT9WDnd/Wk4hxgV/BCRA=' ) as b on a.FProposerID = b.FProposerID ");
	    lastAnnualSql.append(" where a.FYear = '" + (year-1) + "'  and a.FHolidayPolicyID = 'G+WlV0oQT9WDnd/Wk4hxgV/BCRA=' ");
	    lastAnnualSql.append(" ) as b on a.FID  = b.fid ");
	    lastAnnualSql.append(" where a.FYear = '" + (year-1) + "'  and a.FHolidayPolicyID = 'G+WlV0oQT9WDnd/Wk4hxgV/BCRA='  ");
		System.out.println("更新上一年结转"+ lastAnnualSql);
		DbUtil.execute(ctx, lastAnnualSql.toString());
        JSONUtils.writeJson(response, true);
        return null;
    }

	/**
	 * 年假额度生成
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 * @throws SHRWebException
	 * @throws BOSException
	 */
	public String generateAnnualLeaveAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException, BOSException {
		Context ctx = SHRContext.getInstance().getContext();
		int year = DateTimeUtils.getYear(new Date());
		LeaveAllowanceFacadeFactory.getLocalInstance(ctx).createAnnualLeave(year,null);
		JSONUtils.writeJson(response,true);
		return null;
	}

		/**
         * 护理假
         */
    public void creareNursingLeaveAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws BOSException {
    	// TODO Auto-generated method stub
		try {
			List<String> personList = getPersonData(ctx,"P");
			for(String personId : personList){
				String selData = "select  CFStartTime,isnull(CFEndTime,'2199-12-31') as CFEndTime from T_HR_PersonFamily " +
						" where FPERSONID = '"+personId+"' and CFCnleave = 'P' " +
						" and (year(CFEndTime) >= YEAR(getdate()) or CFEndTime is null) " +
						" and year(CFStartTime) <= YEAR(getdate())  " +
						" order by CFStartTime ";
				IRowSet rs = DbUtil.executeQuery(ctx, selData);
				int sumMonth = 0;
		        Date lastEndDate = null;
		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		        while(rs.next()) {
		            System.out.println("查询接口开始时间："+ sdf.format(rs.getDate("CFStartTime")));
		            Date startDate = getStartDate(rs.getDate("CFStartTime"));
		            System.out.println("开始时间："+ sdf.format(startDate));
		            System.out.println("查询接口结束时间："+ sdf.format(rs.getDate("CFEndTime")));
		            Date endDate = getEndDate(rs.getDate("CFEndTime"));
		            System.out.println("结束时间："+ sdf.format(endDate));
		            //��
		            int nowMonth = 0;
		            if(lastEndDate != null){
		                //�Ƿ�ͬһ����
		                if(lastEndDate.getMonth() == startDate.getMonth()){
		                    nowMonth = endDate.getMonth() - startDate.getMonth();
		                }else if(lastEndDate.after(startDate)){
		                    //���ڽ���
		                    nowMonth = endDate.getMonth() - lastEndDate.getMonth();
		                }else{
		                    nowMonth = (endDate.getMonth() - startDate.getMonth()) + 1;
		                }
		            }else{
		                nowMonth = (endDate.getMonth() - startDate.getMonth()) + 1;
		            }
		            sumMonth = sumMonth + nowMonth;
		            System.out.println("当前计算月数："+ nowMonth);
		            System.out.println("总月数："+ sumMonth);
		            if(sumMonth >= 12){
		                break;
		            }
		            lastEndDate = endDate;
		        }
		        double ceil = getLeaveDay(5.0,sumMonth);
		        String updateSql = "update T_HR_ATS_HolidayLimit set FStandardLimit = '" + ceil + "'" +
		        		" where FProposerID = '" +personId + "' and FHolidayPolicyID = 'c9IJLg55RPKXG4Jo9HQld1/BCRA=' " + 
		        		" and FYear =  YEAR(getdate()) ";
	            System.out.println("更新护理假"+ updateSql);
	    		DbUtil.execute(ctx, updateSql);
			}
			
		} catch (BOSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

	
	
    
    /**
	 * 员工列表
	 * @param ctx
	 * @param Cnleave
	 * @return
	 * @throws BOSException 
	 * @throws SQLException 
	 */
	private List<String> getPersonData(Context ctx,String Cnleave) throws BOSException, SQLException{
		String nursingSql = " select distinct a.FPERSONID from T_HR_PersonFamily as a, t_bd_person as b " +
				" where a.FPERSONID  = b.fid and CFCnleave = '" + Cnleave + "' and (year(CFEndTime) = YEAR(getdate()) or CFEndTime is null) " +
				" and b.FEMPLOYEETYPEID not in ('00000000-0000-0000-0000-000000000006A29E85B3','00000000-0000-0000-0000-000000000007A29E85B3'," +
				"'00000000-0000-0000-0000-000000000008A29E85B3','FTCmJT3SSRi1twufIaRb56KehbM=')";
		IRowSet rs = DbUtil.executeQuery(ctx, nursingSql);
		List<String> personList = new ArrayList<String>(); 
		while(rs.next()){
			personList.add(rs.getString("FPERSONID"));
		}
		return personList;
	}
	
	/**
     * 开始时间
     * @param calendar
     * @return
     */
    private static Date getStartDate(Date startDate ){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        System.out.println("获取开始时间："+ sdf.format(startDate));
        System.out.println("获取开始时间："+ sdf.format(calendar.getTime()));
        if(startDate.before(calendar.getTime())){
            startDate = calendar.getTime();
        }
        return startDate;
    }

    /**
     * 结束时间
     * @param calendar
     * @return
     */
    private static Date getEndDate(Date endDate){
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        if(endDate.after(calendar.getTime())){
            endDate = calendar.getTime();
        }
        return endDate;
    }
    
    
    /**
	 * 返回休假天数
	 * @param day
	 * @param month
	 * @return
	 */
	public double getLeaveDay(double day,int month) {
		double leaveDay = day / 12.0 * month;
		int floorInt = (int) leaveDay;
		double decimals = leaveDay - floorInt;
		if(decimals < 0.5) {
			System.out.print("可休假额度：" + floorInt);
			return floorInt ; 
		}else {
			System.out.print("可休假额度：" + floorInt + 0.5);
			return floorInt + 0.5; 
		}
		
	}
	
	
}
