/*
 * MosP - Mind Open Source Project    http://www.mosp.jp/
 * Copyright (C) MIND Co., Ltd.       http://www.e-mind.co.jp/
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package jp.mosp.kintai.workflow.action;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import jp.mosp.common.common.BaseVo;
import jp.mosp.common.common.MospConst;
import jp.mosp.common.common.MospException;
import jp.mosp.common.common.MospUtility;
import jp.mosp.common.utils.DateUtil;
import jp.mosp.common.utils.NumberUtil;
import jp.mosp.common.utils.StringUtil;
import jp.mosp.kintai.common.action.MosPWorkflowAction;
import jp.mosp.kintai.common.part.KintaiApprovalPart;
import jp.mosp.kintai.common.part.PaidHolidayPart;
import jp.mosp.kintai.workflow.dto.HolidayRequestDto;
import jp.mosp.kintai.workflow.dto.KtHolidayRequestDto;
import jp.mosp.kintai.workflow.vo.HolidayRequestListVo;

/**
 * @author yoshida
 *
 */
public class HolidayRequestListAction extends MosPWorkflowAction {
	
	// コマンド
	private static final String	CMD_LIST_SHOW		= "K1420";
	private static final String	CMD_LIST_SEARCH		= "K1421";
	/**
	 * 
	 */
	public static final String	CMD_LIST_RE_SEARCH	= "K1422";
	private static final String	CMD_LIST_SORT		= "K1423";
	

	/**
	 * コンストラクタ
	 */
	public HolidayRequestListAction() {
		super();
	}
	
	public void action() throws Exception {
		// VOの初期化
		prepareVo();
		// 初期処理
		init();
		// コマンド毎の処理
		if (cmd.equals(CMD_LIST_SHOW)) {
			// 表示
			show();
		} else if (cmd.equals(CMD_LIST_SEARCH)) {
			// 検索
			search();
		} else if (cmd.equals(CMD_LIST_RE_SEARCH)) {
			// 再検索
			research();
		} else if (cmd.equals(CMD_LIST_SORT)) {
			// ソート
			sortList(key1);
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}
		
	}
	
	@Override
	protected BaseVo getSpecificVo() {
		return new HolidayRequestListVo();
	}
	
	@Override
	protected void init() throws Exception {
		// プルダウンの設定
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		vo.aryPltYear = StringUtil.getYearArray(MospUtility.getYear(DateUtil.getSystemDate()), 3, 1);
		vo.aryPltMonth = StringUtil.getMonthArray();
		// ユーザ情報の設定
		getInfo(user.getUserId());
		setLabelBasisInfo(userBasis);
	}
	
	@Override
	protected void show() throws Exception {
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		Date todayDate = DateUtil.getSystemDate();
		vo.setPltYear(String.valueOf(MospUtility.getYear(todayDate)));
		vo.setPltMonth(String.valueOf(MospUtility.getMonth(todayDate)));
		searchRequestList();
		vo.setFormerKey(vo.KEY_HOLIDAY_DATE);
		vo.setIsAscending(true);
		vo.initListInfo();
		sortList();
	}
	
	@Override
	protected void search() throws Exception {
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		vo.setParams(request);
		// 検索条件による一覧取得
		searchRequestList();
		vo.setFormerKey(vo.KEY_HOLIDAY_DATE);
		vo.setIsAscending(true);
		vo.initListInfo();
		sortList();
	}
	
	@Override
	protected void research() throws Exception {
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		removeSessionDto();
		searchRequestList();
		vo.setPageButton();
		sortList();
	}
	
	/**
	 * 検索条件による一覧設定
	 * @throws Exception 	例外処理が発生した場合
	 */
	private void searchRequestList() throws Exception {
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		// 開始年月日
		Date startDate = null;
		// 終了年月日
		Date endDate = null;
		if (StringUtil.isNotNull(vo.getPltMonth())) {
			startDate = DateUtil.getFirstDateOfMonth(vo.getPltYear(), vo.getPltMonth());
			endDate = DateUtil.getLastDateOfMonth(vo.getPltYear(), vo.getPltMonth());
		} else {
			startDate = DateUtil.getFirstDateOfYear(vo.getPltYear());
			endDate = DateUtil.getLastDateOfYear(vo.getPltYear());
		}
		List<KtHolidayRequestDto> list = holidayDao().findForCondition(userBasis.getKCode(), startDate, endDate);
		List<HolidayRequestDto> viewList = new ArrayList<HolidayRequestDto>();
		for (KtHolidayRequestDto dto : list) {
			HolidayRequestDto viewDto = new HolidayRequestDto(dto);
			// 休暇理由
			viewDto.setReason(part().holidayRequest().getReasonNameWithType(dto, false));
			// 承認状況
			viewDto.setApprovalStatus(getApprovalName(toKintaiApprovalStatus(dto.getWorkflow())));
			// 承認者名
			String approverName = "";
			if (KintaiApprovalPart.is1stApproved(toKintaiApprovalStatus(dto.getWorkflow()))
					|| KintaiApprovalPart.is2ndApproved(toKintaiApprovalStatus(dto.getWorkflow()))) {
				approverName = getKName(getWorkflowDto(dto.getWorkflow()).getUpdateUser());
			}
			viewDto.setApproverName(approverName);
			viewList.add(viewDto);
		}
		// VOにセット
		vo.setFields(viewList);
		// 対象が無かった場合のメッセージ設定
		if (vo.getEscAryHoliday().length == 0) {
			vo.addErrMessage(getMessage(MospConst.MSG_NO_DATA, ""));
		}
		// 休暇残数対応
		setHolidayRemain();
	}
	
	private void setHolidayRemain() throws Exception {
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		// 有休情報対応
		Map<String, Double> map = part().paidHoliday().getAvairablePaidHolidayMap(userBasis.getKCode(),
				NumberUtil.getIntParam(vo.getPltYear()), NumberUtil.getIntParam(vo.getPltMonth()));
		Date endDate;
		if (StringUtil.isNotNull(vo.getPltMonth())) {
			endDate = DateUtil.getLastDateOfMonth(vo.getPltYear(), vo.getPltMonth());
		} else {
			endDate = DateUtil.getLastDateOfYear(vo.getPltYear());
		}
		vo.setLblTotalRemainDays("");
		vo.setLblTotalRemainHour("");
		vo.setUseHourHoliday(part().mospcode().useHourPaidHolidayFunction());
		StringBuffer sb = new StringBuffer();
		sb.append(PaidHolidayPart.getMapLastRemainDays(map) + PaidHolidayPart.getMapRemainDays(map));
		if (vo.isUseHourHoliday()) {
			/*
						// 労使協定情報
						setLaborAgreementInfo(userBasis.getKCode(), endDate);
						int prescribedTime = LaborAgreementPart.getPrescribedTime(agreement);
						int prescribedHour = Double.valueOf(Math.ceil(TimeUtil.convMinutesToDoubleHour(prescribedTime))).intValue();
						sb.append(StringUtil.surroundRoundBracket(String.valueOf(PaidHolidayPart.getMapPossible(map)
								/ prescribedHour)));
						vo.setLblTotalRemainHour(String.valueOf(PaidHolidayPart.getMapPossible(map) % prescribedHour));
			*/
			sb.append(StringUtil.surroundRoundBracket(String.valueOf(PaidHolidayPart.getMapPossible(map))));
			vo.setLblTotalRemainHour(String.valueOf(PaidHolidayPart.getMapPossible(map)));
		}
		vo.setLblTotalRemainDays(sb.toString());
		// 代休情報対応
		double subRemainDays = part().subHoliday().getRemainSubstituteHoliday(userBasis.getKCode(), endDate);
		vo.setLblSubstituteRemain("");
		vo.setLblSubstituteRemain(NumberUtil.getNumberString(subRemainDays, 3, 1));
		vo.setUseSubstitute(part().mospcode().useSubstituteHolidayFunction());
	}
	
	@Override
	protected void sortList(String key) throws MospException {
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		vo.sortList(key, getComparator(key));
		vo.setFields(vo.getList());
	}
	
	@Override
	protected void sortList() throws MospException {
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		vo.sortList(getComparator(vo.getFormerKey()));
		vo.setFields(vo.getList());
	}
	
	@Override
	protected Comparator<Object> getComparator(String key) throws MospException {
		HolidayRequestListVo vo = (HolidayRequestListVo)getVo();
		Comparator<Object> comp = null;
		if (key.equals(vo.KEY_HOLIDAY_DATE)) {
			comp = new CompHolidayDate();
		} else if (key.equals(vo.KEY_REASON)) {
			comp = new CompReason();
		} else if (key.equals(vo.KEY_STATUS)) {
			comp = new CompStatus();
		} else if (key.equals(vo.KEY_APPROVER)) {
			comp = new CompApprover();
		} else {
			throw new MospException(MospConst.EX_SORTKEY_INVALID);
		}
		return comp;
	}
	

	/**
	 * 休暇日による比較クラス
	 */
	protected static class CompHolidayDate implements Comparator<Object>, Serializable {
		
		private static final long	serialVersionUID	= 7742424634407439114L;
		

		public int compare(Object obj1, Object obj2) {
			HolidayRequestDto dto1 = (HolidayRequestDto)obj1;
			HolidayRequestDto dto2 = (HolidayRequestDto)obj2;
			return dto1.getHolidayDate().compareTo(dto2.getHolidayDate());
		}
	}
	
	/**
	 * 休暇理由による比較クラス
	 */
	protected static class CompReason implements Comparator<Object>, Serializable {
		
		private static final long	serialVersionUID	= 7831871246299417519L;
		

		public int compare(Object obj1, Object obj2) {
			HolidayRequestDto dto1 = (HolidayRequestDto)obj1;
			HolidayRequestDto dto2 = (HolidayRequestDto)obj2;
			return dto1.getReason().compareTo(dto2.getReason());
		}
	}
	
	/**
	 * 承認状況による比較クラス
	 */
	protected static class CompStatus implements Comparator<Object>, Serializable {
		
		private static final long	serialVersionUID	= 7143311063774870712L;
		

		public int compare(Object obj1, Object obj2) {
			HolidayRequestDto dto1 = (HolidayRequestDto)obj1;
			HolidayRequestDto dto2 = (HolidayRequestDto)obj2;
			return dto1.getApprovalStatus().compareTo(dto2.getApprovalStatus());
		}
	}
	
	/**
	 * 承認者による比較クラス
	 */
	protected static class CompApprover implements Comparator<Object>, Serializable {
		
		private static final long	serialVersionUID	= 1923632050645529241L;
		

		public int compare(Object obj1, Object obj2) {
			HolidayRequestDto dto1 = (HolidayRequestDto)obj1;
			HolidayRequestDto dto2 = (HolidayRequestDto)obj2;
			return dto1.getApproverName().compareTo(dto2.getApproverName());
		}
	}
	
}
