/*
 * 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.payroll.action;

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

import jp.mosp.common.CommonConst;
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.StringUtil;
import jp.mosp.common.utils.VariousUtil;
import jp.mosp.kintai.common.action.AttendanceTotalAction;
import jp.mosp.kintai.common.dto.MKihonDto;
import jp.mosp.kintai.common.part.KintaiCompilePart;
import jp.mosp.payroll.dto.CompileAmendmentDto;
import jp.mosp.payroll.vo.CompileAmendmentListVo;

/**
 * @author yoshida
 *
 */
public class CompileAmendmentListAction extends AttendanceTotalAction {
	
	// コマンド
	private static final String	CMD_AMENDMENT_LIST_SHOW			= "P1040";
	private static final String	CMD_AMENDMENT_LIST_SEARCH		= "P1041";
	/**
	 * 
	 */
	public static final String	CMD_AMENDMENT_LIST_RE_SEARCH	= "P1042";
	private static final String	CMD_AMENDMENT_LIST_SORT			= "P1043";
	

	/**
	 * コンストラクタ
	 */
	public CompileAmendmentListAction() {
		super();
	}
	
	public void action() throws Exception {
		// VOの取得
		prepareVo();
		// 初期処理
		init();
		// コマンド毎の処理
		if (cmd.equals(CMD_AMENDMENT_LIST_SHOW)) {
			// 表示
			show();
		} else if (cmd.equals(CMD_AMENDMENT_LIST_SEARCH)) {
			// 検索
			search();
		} else if (cmd.equals(CMD_AMENDMENT_LIST_RE_SEARCH)) {
			// 再検索
			research();
		} else if (cmd.equals(CMD_AMENDMENT_LIST_SORT)) {
			// ソート
			sortList(key1);
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}
	}
	
	@Override
	protected BaseVo getSpecificVo() {
		return new CompileAmendmentListVo();
	}
	
	@Override
	protected void init() throws Exception {
		// コネクション取得
		getConnection();
		// PAYROLL権限確認
		confirmPayrollAuth();
		// ユーザー情報取得
		getInfo(user.getUserId());
		// プルダウン取得
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		// 勤怠承認機能確認
		if (isAttendanceApprovalFunction()) {
			vo.setMode(CompileAmendmentListVo.MODE_POSSIBLE);
		} else {
			vo.setMode(CompileAmendmentListVo.MODE_IMPOSSIBLE);
		}
		// 所属リストのセット
		if (hasCalculateAuth()) {
			vo.aryPltSection = StringUtil.addArrayFirstRowValue(getSectionArrayAll(),
					CommonConst.NAM_COMMON_STRING_INITIAL_VALUE, CommonConst.NAM_ALL_SECTION);
		} else {
			vo.aryPltSection = getSectionArrayForManager();
		}
		// 年月リスト取得
		vo.aryPltYear = StringUtil.getYearArray(MospUtility.getYear(getCalcMonth()), 1, 1);
		vo.aryPltMonth = StringUtil.getMonthArray();
		// 未承認有無
		if (isAttendanceApprovalFunction()) {
			vo.aryPltApprovalFlag = StringUtil.addArrayFirstRowSpace(StringUtil.getExistenceArray());
		} else {
			vo.aryPltApprovalFlag = StringUtil.getBlankArray();
		}
		// 未計算有無
		vo.aryPltCompileFlag = StringUtil.addArrayFirstRowSpace(StringUtil.getExistenceArray());
		// 時間外警告設定
		setUseOver60Hour();
		vo.setUseOver60Hour(useOver60Hour);
	}
	
	@Override
	protected void show() throws Exception {
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		// 集計年
		vo.setPltYear(String.valueOf(MospUtility.getYear(getCalcMonth())));
		// 集計月
		vo.setPltMonth(String.valueOf(MospUtility.getMonth(getCalcMonth())));
		// 検索履歴を初期値にセット
		vo.setSearchmode(CompileAmendmentListVo.SEARCH_OFF);
	}
	
	@Override
	protected void search() throws Exception {
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		vo.setParams(request);
		serachEmployeeList();
		vo.setFormerKey(vo.KEY_K_CODE);
		vo.setIsAscending(true);
		vo.initListInfo();
		// 検索履歴をありにセット
		vo.setSearchmode(CompileAmendmentListVo.SEARCH_ON);
	}
	
	@Override
	protected void research() throws Exception {
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		removeSessionDto();
		if (vo.getSearchmode() == CompileAmendmentListVo.SEARCH_ON) {
			serachEmployeeList();
			vo.setPageButton();
			sortList();
		} else {
			// 勤怠集計情報
			setCompileInfo();
			serachEmployeeList();
			vo.setFormerKey(vo.KEY_K_CODE);
			vo.setIsAscending(true);
			vo.initListInfo();
			// 検索履歴をありにセット
			vo.setSearchmode(CompileAmendmentListVo.SEARCH_ON);
			sortList();
		}
	}
	
	/**
	 * 社員リスト検索
	 * @throws Exception  	例外処理が発生した場合
	 */
	private void serachEmployeeList() throws Exception {
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		// 集計月取得
		Date targetMonth = DateUtil.getFirstDateOfMonth(vo.getPltYear(), vo.getPltMonth());
		// 選択社員一覧検索
		List<MKihonDto> humanList = part().human().getMKihonDao().findForCondition(vo.getTxtKCode(), vo.getTxtKName(),
				vo.getPltSection(), userBasis.getJCode(), userBasis.getKCode(), user.getDataLevel(),
				DateUtil.convDateToInteger(getStartDate(targetMonth)),
				DateUtil.convDateToInteger(getEndDate(targetMonth)));
		// 勤怠集計検索
		List<CompileAmendmentDto> compileList = new ArrayList<CompileAmendmentDto>();
		for (MKihonDto humanDto : humanList) {
			CompileAmendmentDto dto = compile().getCompileAmendmentInfo(humanDto.getKCode(), targetMonth,
					humanDto.getSCode());
			// 未集計設定
			if (VariousUtil.isNull(dto)) {
				dto = new CompileAmendmentDto();
				dto.setKCode(humanDto.getKCode());
				dto.setKName(humanDto.getSimei());
				dto.setSCode(humanDto.getSCode());
			} else {
				// 集計済
				dto.setCompiledFlag(true);
			}
			// 所属名の変更。
			dto.setSCode(getSectionName(dto.getSCode()));
			// 労使協定情報設定取得
			setLaborAgreementInfo(humanDto.getKCode(), targetMonth);
			if (VariousUtil.isNotNull(agreement)) {
				dto.setCautionMonthly(agreement.getCautionMonth());
			}
			boolean addFlag = false;
			// 勤怠承認機能確認
			if (vo.getMode() == CompileAmendmentListVo.MODE_POSSIBLE) {
				// 未承認有無検索
				dto.setApprovedFlag(KintaiCompilePart
					.checkApproval(getAttendanceList(humanDto.getKCode(), targetMonth)));
				if (StringUtil.isNull(vo.getPltCompile())) {
					// 未集計全件選択の場合
					if (vo.getPltApproval().equals(StringUtil.convTrueIsOff(dto.isApprovedFlag()))) {
						// 未承認選択項目
						addFlag = true;
					} else if (StringUtil.isNull(vo.getPltApproval())) {
						// 全件選択の場合				
						addFlag = true;
					}
				} else {
					// 未集計選択項目
					if (vo.getPltCompile().equals(StringUtil.convTrueIsOff(dto.isCompiledFlag()))) {
						if (vo.getPltApproval().equals(StringUtil.convTrueIsOff(dto.isApprovedFlag()))) {
							// 未承認選択項目
							addFlag = true;
						} else if (StringUtil.isNull(vo.getPltApproval())) {
							// 全件選択の場合
							addFlag = true;
						}
					}
				}
			} else {
				// 未集計選択、全件選択の場合
				if (vo.getPltCompile().equals(StringUtil.convTrueIsOff(dto.isCompiledFlag()))
						|| StringUtil.isNull(vo.getPltCompile())) {
					addFlag = true;
				}
			}
			if (addFlag) {
				compileList.add(dto);
			}
		}
		// VO設定
		vo.setFields(compileList);
		// 選択年月
		vo.setHidSelectDate(DateUtil.convDateToStringYearMonthShort(targetMonth));
		// 対象が無かった場合のメッセージ設定
		if (vo.getAryCompile().length == 0) {
			vo.addErrMessage(getMessage(MospConst.MSG_NO_DATA, ""));
		}
	}
	
	/**
	 * 勤怠集計情報のセット
	 * @throws Exception  	例外処理が発生した場合
	 */
	private void setCompileInfo() throws Exception {
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		// 集計所属コード
		vo.setPltSection((String)request.getAttribute(COMPILE_SECTION));
		// 集計社員コード
		vo.setTxtKCode((String)request.getAttribute(COMPILE_K_CODE));
		// 集計年
		vo.setPltYear(String.valueOf(MospUtility.getYear(getCalcMonth())));
		// 集計月
		vo.setPltMonth(String.valueOf(MospUtility.getMonth(getCalcMonth())));
	}
	
	@Override
	protected void sortList(String key) throws MospException {
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		vo.sortList(key, getComparator(key));
		vo.setFields(vo.getList());
	}
	
	@Override
	protected void sortList() throws MospException {
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		vo.sortList(getComparator(vo.getFormerKey()));
		vo.setFields(vo.getList());
	}
	
	@Override
	protected Comparator<Object> getComparator(String key) throws MospException {
		CompileAmendmentListVo vo = (CompileAmendmentListVo)getVo();
		Comparator<Object> comp = null;
		if (key.equals(vo.KEY_K_CODE)) {
			comp = new CompKCode();
		} else if (key.equals(vo.KEY_K_NAME)) {
			comp = new CompKName();
		} else if (key.equals(vo.KEY_SECTION)) {
			comp = new CompSection();
		} else {
			throw new MospException(MospConst.EX_SORTKEY_INVALID);
		}
		return comp;
	}
	

	/**
	 * 社員コードによる比較クラス
	 */
	protected static class CompKCode implements Comparator<Object>, Serializable {
		
		private static final long	serialVersionUID	= 2785426316163131119L;
		

		public int compare(Object obj1, Object obj2) {
			CompileAmendmentDto dto1 = (CompileAmendmentDto)obj1;
			CompileAmendmentDto dto2 = (CompileAmendmentDto)obj2;
			return dto1.getKCode().compareTo(dto2.getKCode());
		}
	}
	
	/**
	 * 社員名による比較クラス
	 */
	protected static class CompKName implements Comparator<Object>, Serializable {
		
		private static final long	serialVersionUID	= 6920023209991067840L;
		

		public int compare(Object obj1, Object obj2) {
			CompileAmendmentDto dto1 = (CompileAmendmentDto)obj1;
			CompileAmendmentDto dto2 = (CompileAmendmentDto)obj2;
			return dto1.getKName().compareTo(dto2.getKName());
		}
	}
	
	/**
	 * 所属による比較クラス
	 */
	protected static class CompSection implements Comparator<Object>, Serializable {
		
		private static final long	serialVersionUID	= 8039660004898020825L;
		

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