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

import java.util.Calendar;
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.common.ValidateUtility;
import jp.mosp.common.utils.DateUtil;
import jp.mosp.common.utils.NumberUtil;
import jp.mosp.common.utils.StringUtil;
import jp.mosp.common.utils.TimeUtil;
import jp.mosp.common.utils.VariousUtil;
import jp.mosp.kintai.common.action.AttendanceTotalAction;
import jp.mosp.kintai.common.part.KintaiCommonPart;
import jp.mosp.kintai.kintai.dto.MSyukkinboDto;
import jp.mosp.kintai.kintai.vo.AttendanceListVo;
import jp.mosp.kintai.kintai.vo.EmployeeAttendanceListVo;

/**
 * @author yoshida
 *
 */
public class AttendanceListAction extends AttendanceTotalAction {
	
	// コマンド
	private static final String	CMD_ATTENDANCE_LIST_SHOW		= "K1010";
	private static final String	CMD_ATTENDANCE_LIST_SELECT		= "K1011";
	private static final String	CMD_ATTENDANCE_LIST_SEARCH		= "K1012";
	/**
	 * 再検索
	 */
	public static final String	CMD_ATTENDANCE_LIST_RE_SEARCH	= "K1013";
	private static final String	CMD_ATTENDANCE_CARD_SELECT		= "K1014";
	

	/**
	 * コンストラクタ
	 */
	public AttendanceListAction() {
		super();
	}
	
	/**
	 * アクション
	 */
	public void action() throws Exception {
		// VOの取得
		prepareVo();
		// 初期処理
		init();
		// コマンド毎の処理
		if (cmd.equals(CMD_ATTENDANCE_LIST_SHOW)) {
			// 表示
			show();
		} else if (cmd.equals(CMD_ATTENDANCE_LIST_SELECT)) {
			// 選択
			select();
		} else if (cmd.equals(CMD_ATTENDANCE_LIST_SEARCH)) {
			// 検索
			search();
		} else if (cmd.equals(CMD_ATTENDANCE_LIST_RE_SEARCH)) {
			// 再検索
			research();
		} else if (cmd.equals(CMD_ATTENDANCE_CARD_SELECT)) {
			// 検索
			searchAttendance();
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}
	}
	
	@Override
	protected BaseVo getSpecificVo() {
		return new AttendanceListVo();
	}
	
	@Override
	protected void init() throws Exception {
		AttendanceListVo vo = (AttendanceListVo)getVo();
		// ユーザー情報取得
		getInfo(user.getUserId());
		// 勤怠管理コマンド
		if (VariousUtil.isNotNull(getStoredVo(EmployeeAttendanceListVo.class.getName()))) {
			// 状態遷移確認
			vo.setCmdMenuButton(CommonConst.CMD_MENU_MAMAGE);
			vo.setCmdListButton(EmployeeAttendanceListAction.CMD_EMPLOYEE_LIST_RE_SEARCH);
			vo.setNamListButton(CommonConst.TTL_EMPLOYEE_SELECT);
			// メニューコマンドの設定
			vo.setAryMenu(true);
		} else {
			vo.setCmdMenuButton(CommonConst.CMD_MENU_INPUT);
			vo.setCmdListButton(CommonConst.CMD_MENU_INPUT);
			vo.setNamListButton(CommonConst.NAM_MENU);
			// メニューコマンドの設定
			vo.setAryMenu(false);
		}
		// プルダウン取得
		vo.aryPltYear = StringUtil.getYearArray(MospUtility.getYear(DateUtil.getSystemDate()), 3, 1);
		vo.aryPltMonth = StringUtil.getMonthArray();
		// 勤怠承認機能確認
		if (isAttendanceApprovalFunction()) {
			vo.setMode(AttendanceListVo.MODE_POSSIBLE);
		} else {
			vo.setMode(AttendanceListVo.MODE_IMPOSSIBLE);
		}
	}
	
	@Override
	protected void show() throws Exception {
		AttendanceListVo vo = (AttendanceListVo)getVo();
		// 対象社員設定
		vo.setSelectKCode(userBasis.getKCode());
		// 表示月
		Date current = DateUtil.getSystemDate();
		// 対象年月日設定
		vo.setPltYear(String.valueOf(MospUtility.getYear(current)));
		vo.setPltMonth(String.valueOf(MospUtility.getMonth(current)));
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		vo.setHidDay(String.valueOf(MospUtility.getDay(current)));
		// 検索
		searchAttendanceList();
	}
	
	@Override
	protected void select() throws Exception {
		AttendanceListVo vo = (AttendanceListVo)getVo();
		// 対象社員設定
		vo.setSelectKCode(key1);
		// 表示月
		Date current = DateUtil.getSystemDate();
		// 対象年月日設定
		vo.setPltYear(String.valueOf(MospUtility.getYear(current)));
		vo.setPltMonth(String.valueOf(MospUtility.getMonth(current)));
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		vo.setHidDay(String.valueOf(MospUtility.getDay(current)));
		// 検索
		searchAttendanceList();
	}
	
	@Override
	protected void search() throws Exception {
		AttendanceListVo vo = (AttendanceListVo)getVo();
		// 対象年月日設定
		vo.setParams(request);
		// 検索
		searchAttendanceList();
	}
	
	@Override
	protected void research() throws Exception {
		removeSessionDto();
		AttendanceListVo vo = (AttendanceListVo)getVo();
		// 対象社員設定
		vo.setSelectKCode(request.getParameter(AttendanceListVo.PRM_HID_K_CODE));
		// 対象年月日設定
		vo.setPltYear(request.getParameter(AttendanceListVo.PRM_HID_YEAR));
		vo.setPltMonth(request.getParameter(AttendanceListVo.PRM_HID_MONTH));
		vo.setHidDay(request.getParameter(AttendanceListVo.PRM_HID_DAY));
		// 検索
		searchAttendanceList();
	}
	
	/**
	 * 勤怠一覧検索
	 * @throws Exception	例外処理が発生した場合
	 */
	private void searchAttendanceList() throws Exception {
		AttendanceListVo vo = (AttendanceListVo)getVo();
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		// 対象期間設定
		Date targetMonth;
		if (StringUtil.isNotNull(vo.getHidDay())) {
			int day = NumberUtil.getIntParam(vo.getHidDay());
			while (!ValidateUtility.chkDate(NumberUtil.getIntParam(vo.getPltYear()), NumberUtil.getIntParam(vo
				.getPltMonth()) - 1, day)) {
				// 存在しない日付の場合は1日マイナスする
				day--;
			}
			targetMonth = DateUtil.getDate(vo.getPltYear(), vo.getPltMonth(), String.valueOf(day));
		} else {
			targetMonth = DateUtil.getYearMonth(vo.getPltYear(), vo.getPltMonth());
		}
		// 勤怠データ取得
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		getAttendanceListForView(vo.getSelectKCode(), targetMonth);
		// 労使協定情報取得
		setLaborAgreementInfo(vo.getSelectKCode(), DateUtil.convStringDateToDate(startDate));
		// 勤怠情報設定
		setCalcParam();
		// 日集計データ配列作成
		makeAttendanceArray(vo.getSelectKCode(), attendanceList);
		// 月集計
		totalAttendanceDaily(vo.getSelectKCode(), attendanceList);
		// 選択情報の設定
		setLabelBasisInfo(vo.getSelectKCode());
		// 皆勤手当設定
		// 役職情報取得
		if (!part().position().isApplyAttendanceAllowance(vo.getSelectKCode())) {
			aryAttendanceCompile[17][1] = "";
		}
		// 月集計データとラベルを分離
		String[] aryLabel = new String[aryAttendanceCompile.length];
		String[] aryCompile = new String[aryAttendanceCompile.length];
		for (int i = 0; i < aryAttendanceCompile.length; i++) {
			aryLabel[i] = aryAttendanceCompile[i][0];
			aryCompile[i] = aryAttendanceCompile[i][1];
		}
		// VO設定
		vo.setFields(aryAttendance, aryCompile, aryLabel);
	}
	
	/**
	 * 日集計データ配列作成
	 * @param kCode					対象社員コード
	 * @param attendanceList		対象出勤簿リスト
	 * @throws Exception	例外処理が発生した場合
	 */
	private void makeAttendanceArray(String kCode, List<MSyukkinboDto> attendanceList) throws Exception {
		// データ数取得
		Calendar cal = Calendar.getInstance();
		cal.setTime(MospUtility.getDate(startDate));
		int count = 0;
		while (MospUtility.getDate(endDate).compareTo(cal.getTime()) >= 0) {
			cal.add(Calendar.DAY_OF_MONTH, 1);
			count++;
		}
		// 配列初期化
		final int childSize = 40;
		aryAttendance = StringUtil.getBlankArray(count, childSize);
		// 日付設定
		cal.setTime(MospUtility.getDate(startDate));
		for (int i = 0; i < aryAttendance.length; i++) {
			// 日付（検索用）
			aryAttendance[i][0] = DateUtil.convDateFormatted(cal.getTime());
			// 日付（M/d）
			aryAttendance[i][1] = DateUtil.convDateToMonthDayShort(cal.getTime());
			// 曜日
			aryAttendance[i][2] = getDayOfWeek(cal.get(Calendar.DAY_OF_WEEK));
			// 曜日の色
			aryAttendance[i][17] = getDayOfWeekColorClass(cal.getTime());
			// 備考（祝祭日、半休）
			StringBuffer remark = new StringBuffer();
			String holidayName = getPublicHolidayName(cal.getTime());
			if (StringUtil.isNotNull(holidayName)) {
				remark.append(holidayName);
				remark.append(CommonConst.NAM_COMMON_HALF_KANA_SPACE);
			}
			aryAttendance[i][16] = remark.toString();
			// 残業申請
			if (part().overtime().isOverTimeRequest(kCode, cal.getTime())) {
				aryAttendance[i][16] += CommonConst.NAM_OVER_TIME_REQUEST_SHORT;
				aryAttendance[i][16] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
			}
			// 休暇申請
			if (part().holidayRequest().existHolidayRequest(kCode, cal.getTime())) {
				aryAttendance[i][16] += CommonConst.NAM_HOLIDAY_REQUEST_SHORT;
				aryAttendance[i][16] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
			}
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
		// 1ヶ月の時間外時間
		int overTimeMonthly = 0;
		// データの設定
		for (MSyukkinboDto dto : attendanceList) {
			cal.setTime(MospUtility.getDate(startDate));
			Date attendanceDate = MospUtility.getDate(dto.getHizuke());
			for (int i = 0; i < aryAttendance.length; i++) {
				if (attendanceDate.compareTo(cal.getTime()) == 0) {
					// 勤務形態
					String kinmuName = "";
					// 出勤の場合
					if (KintaiCommonPart.isAvailableWorkType(dto)) {
						kinmuName = part().worktype().getWorkTypeName(dto.getKinmu());
						// 出勤時刻
						aryAttendance[i][4] = dto.getSyJikoku();
						// 退勤時刻
						aryAttendance[i][5] = dto.getTaJikoku();
						// 勤務時間
						aryAttendance[i][6] = getHourString(TimeUtil.convIntegerTimeToDoubleTime(dto.getKinmuJi()));
						// 休憩時間
						aryAttendance[i][7] = getHourString(TimeUtil.convIntegerTimeToDoubleTime(dto.getKyukeiJi()));
						// 遅刻時間
						aryAttendance[i][8] = getHourString(TimeUtil.convIntegerTimeToDoubleTime(dto.getTiJikan()));
						// 早退時間
						aryAttendance[i][9] = getHourString(TimeUtil.convIntegerTimeToDoubleTime(dto.getSoJikan()));
						// 残業時間
						aryAttendance[i][10] = getHourString(TimeUtil.convIntegerTimeToDoubleTime(dto.getZaJikan()));
						// 時間外警告対応
						overTimeMonthly += dto.getZaJikan();
						String cssClass = "TimeTd";
						if (checkCautionOverTime(overTimeMonthly, 0)) {
							cssClass = CommonConst.CSS_CLASS_CAUTION_TD;
						}
						if (checkWarningOverTime(overTimeMonthly, 0)) {
							cssClass = CommonConst.CSS_CLASS_WARNING_TD;
						}
						aryAttendance[i][18] = cssClass;
						// 休出時間
						aryAttendance[i][11] = getHourString(TimeUtil.convIntegerTimeToDoubleTime(dto.getKsJikan()));
						// 深夜時間
						aryAttendance[i][12] = getHourString(TimeUtil.convIntegerTimeToDoubleTime(dto.getSnJikan()));
					} else if (KintaiCommonPart.isWeekHoliday(dto) || KintaiCommonPart.isOfficialHoliday(dto)) {
						// 週休→所定休日、法定休日表示
						kinmuName = part().worktype().getWorkTypeName(dto.getKinmu());
					} else {
						// 休暇理由
						kinmuName = part().mospcode().getHolidayName(dto.getKKRiyuu());
					}
					aryAttendance[i][3] = kinmuName;
					// 一次承認、二次承認
					String[] result = getApproval(dto.getSnRiyuu());
					aryAttendance[i][13] = result[0];
					aryAttendance[i][14] = result[1];
					// 手当等
					StringBuffer sb = new StringBuffer();
					sb.append(dto.getSyokuji());
					sb.append(CommonConst.STR_SLASH_SEPARATOR);
					sb.append(dto.getCyoku1());
					sb.append(dto.getCyoku2());
					sb.append(dto.getCyoku3());
					sb.append(CommonConst.STR_SLASH_SEPARATOR);
					sb.append(dto.getHoka1());
					sb.append(dto.getHoka2());
					sb.append(dto.getHoka3());
					sb.append(dto.getHoka4());
					sb.append(dto.getHoka5());
					aryAttendance[i][15] = sb.toString();
					// 半休
					if (KintaiCommonPart.isHalfHoliday(dto)) {
						aryAttendance[i][16] += CommonConst.NAM_VACATION_LEAVE_HALF;
						aryAttendance[i][16] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
					}
					// 休出
					if (KintaiCommonPart.isWorkOnHoliday(dto)) {
						aryAttendance[i][16] += CommonConst.NAM_WORK_ON_HOLIDAY;
						aryAttendance[i][16] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
					}
					// 時間外代休(半日)
					if (KintaiCommonPart.isOverTimeSubHolidayHalf(dto)) {
						aryAttendance[i][16] += CommonConst.NAM_SUB_HOLIDAY_HALF;
						aryAttendance[i][16] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
					}
					break;
				}
				cal.add(Calendar.DAY_OF_MONTH, 1);
			}
		}
	}
	
}
