/*
 * MosP - Mind Open Source Project         http://www.mosp.jp/
 * Copyright (C) 1987-2009 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.action;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import jp.mosp.common.CommonConst;
import jp.mosp.common.action.AttendanceTotalAction;
import jp.mosp.common.common.MospConst;
import jp.mosp.common.common.MospException;
import jp.mosp.common.common.MospUtility;
import jp.mosp.common.dto.HumanBasisDtoInterface;
import jp.mosp.common.part.KintaiCommonPart;
import jp.mosp.common.part.PartManager;
import jp.mosp.common.part.VariousPart;

import jp.mosp.kintai.dto.MSyukkinboDto;
import jp.mosp.kintai.vo.AttendanceListVo;
import jp.mosp.kintai.vo.AttendanceMenuVo;

public class AttendanceListAction extends AttendanceTotalAction {

	// コマンド
	public  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";
	public  static final String CMD_ATTENDANCE_CARD_SELECT  	= "K1014";

	/**
	 * コンストラクタ
	 */
	public AttendanceListAction() {
		super();
	}

	/**
	 * アクション
	 */
	public void action() throws Exception {
		// DBコネクション取得
		getConnection();
		// VOの取得
		AttendanceListVo vo;
		vo = (AttendanceListVo)getStoredVo(CommonConst.VO_ATTENDANCE_LIST);
		if (vo == null) {
			vo = new AttendanceListVo();
		}
		vo.initVo(cfg, msg, cmd, aspUser, user);
		vo.clearMessage();
		vo.clearErrField();
		storeVo(CommonConst.VO_ATTENDANCE_LIST, vo);
		// VO及びフォワード先URLの設定
		setVo(vo);
		setUrl(vo.getRetUrl());
		// ユーザー情報取得
		getInfo(user.getUserId());
		// 表示月
		Date current = util.getSystemDate();
		// 勤怠管理コマンド
		if (getStoredVo(CommonConst.VO_EMPLOYEE_ATTENDANCE_LIST) != null) {
			// 状態遷移確認
			vo.setCmdMenuButton(vo.CMD_MENU_MAMAGE);
			vo.setCmdListButton(EmployeeAttendanceListAction.CMD_EMPLOYEE_LIST_RE_SEARCH);
			vo.setNamListButton(CommonConst.TTL_EMPLOYEE_SELECT);
		} else {
			vo.setCmdMenuButton(vo.CMD_MENU_INPUT);
			vo.setCmdListButton(vo.CMD_MENU_INPUT);
			vo.setNamListButton(CommonConst.NAM_MENU);			
		}
		// プルダウン取得
		vo.aryPltYear  = util.getYearArray(MospUtility.getYear (current), 2, 1);
		vo.aryPltMonth = util.getMonthArray();
		// 勤怠承認機能確認
		if (isAttendanceApprovalFunction()) {
			vo.setMode(AttendanceListVo.MODE_POSSIBLE);
		} else {
			vo.setMode(AttendanceListVo.MODE_IMPOSSIBLE);
		}
		// コマンド毎の処理
		if (cmd.equals(CMD_ATTENDANCE_LIST_SHOW)) {
			// 表示
			// 対象社員設定
			vo.setSelectKCode(mKihon.getKCode());
			// 対象年月日設定
			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(vo);
		} else if (cmd.equals(CMD_ATTENDANCE_LIST_SELECT)) {
			// 選択
			// 対象社員設定
			vo.setSelectKCode(key1);
			// 対象年月日設定
			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(vo);
		} else if (cmd.equals(CMD_ATTENDANCE_LIST_SEARCH)) {
			// 対象年月日設定
			vo.setParams(request);
			// 検索
			searchAttendanceList(vo);
		} else if (cmd.equals(CMD_ATTENDANCE_LIST_RE_SEARCH)) {
			// 再検索
			session.removeAttribute(MospConst.ATT_DTO);
			AttendanceMenuVo menuVo = (AttendanceMenuVo)getStoredVo(CommonConst.VO_ATTENDANCE_MENU);
			// 対象社員設定
			vo.setSelectKCode(menuVo.getHidKCode());
			// 対象年月日設定
			vo.setPltYear(menuVo.getHidYear());
			vo.setPltMonth(menuVo.getHidMonth());
			/*						
			 *  	2009/01/20	m.yoshida	締め日対応
			 */
			vo.setHidDay(menuVo.getHidDay());
			// 検索
			searchAttendanceList(vo);
		} else if (cmd.equals(CMD_ATTENDANCE_CARD_SELECT)) {
			// 対象年月日設定
			vo.setParams(request);
			// 検索
			searchAttendance();
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}
	}

	/**
	 * 勤怠一覧検索
	 * @param vo AttendanceListVoインスタンス
	 * @throws Exception
	 */
	private void searchAttendanceList(
			AttendanceListVo vo
	) throws Exception {
		// DBコネクション取得
		if (conn == null) {
			getConnection();
		}
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		// 対象期間設定
		Date targetMonth;
		if (vo.getHidDay().length() != 0) {
			targetMonth = util.getDate(vo.getPltYear(), vo.getPltMonth(), vo.getHidDay());
		} else {
			targetMonth = util.getYearMonth(vo.getPltYear(), vo.getPltMonth());
		}
		// 勤怠データ取得
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		getAttendanceListForView(vo.getSelectKCode(), targetMonth);
		// 勤怠情報設定
		setCalcParam();
		// 日集計データ配列作成
		makeAttendanceArray(vo.getSelectKCode(), attendanceList);
		// 月集計
		totalAttendanceDaily(vo.getSelectKCode(), attendanceList);
		// 人事基本情報の取得
		HumanBasisDtoInterface mKihonDto = getBasisInfo(vo.getSelectKCode());
		// 選択情報の設定
		vo.setSelectKName(mKihonDto.getSimei());
		vo.setSelectSectionName(getSectionName(mKihonDto.getSCode()));
		// 皆勤手当設定
		// 役職情報取得
		if (!PartManager.position(partInfo()).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 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++;
		}
		// 配列初期化
		aryAttendance = new String[count][40];
		for (int i = 0; i < aryAttendance.length; i++) {
			for (int j = 0; j < aryAttendance[i].length; j++) {
				aryAttendance[i][j] = "";
			}
		}
		// 日付設定
		cal.setTime(MospUtility.getDate(startDate));
		for (int i = 0; i < aryAttendance.length; i++) {
			// 日付（検索用）
			aryAttendance[i][0] = MospUtility.getDateString(cal.getTime(), CommonConst.FORMAT_DATE);
			// 日付
			aryAttendance[i][1] = String.valueOf(MospUtility.getMonth(cal.getTime()))
			+ CommonConst.SEPARATOR_DATE
			+ String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
			// 曜日
			aryAttendance[i][2] = getDayOfWeek(cal.get(Calendar.DAY_OF_WEEK));
			// 備考（祝祭日、半休）
			StringBuffer remark = new StringBuffer();
			String holidayName = getPublicHolidayName(cal.getTime());
			if (holidayName.length() != 0) {
				remark.append(holidayName);
				remark.append(CommonConst.NAM_COMMON_HALF_KANA_SPACE);
			}
			aryAttendance[i][16] = remark.toString();
			// 残業申請
			if (isOverTimeRequest(kCode, cal.getTime())) {
				aryAttendance[i][16] += CommonConst.NAM_OVERTIME;
			}
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
		// データの設定
		Iterator<MSyukkinboDto> it = attendanceList.iterator();
		while (it.hasNext()) {
			cal.setTime(MospUtility.getDate(startDate));
			MSyukkinboDto dto = it.next();
			Date attendanceDate = MospUtility.getDate(dto.getHizuke());
			for (int i = 0; i < aryAttendance.length; i++) {
				if (attendanceDate.compareTo(cal.getTime()) == 0) {
					// 勤務形態
					String kinmu = "";
					// 出勤の場合
					if (KintaiCommonPart.isAvailableWorkType(dto)) {
						kinmu = getWorkTypeInfo(dto.getKinmu()).getShiftName();
						// 出勤時刻
						aryAttendance[i][4 ] = dto.getSyJikoku();
						// 退勤時刻
						aryAttendance[i][5 ] = dto.getTaJikoku();
						// 勤務時間
						aryAttendance[i][6 ] = getHourString(util.convIntegerTimeToDoubleTime(dto.getKinmuJi()));
						// 休憩時間
						aryAttendance[i][7 ] = getHourString(util.convIntegerTimeToDoubleTime(dto.getKyukeiJi()));
						// 遅刻時間
						aryAttendance[i][8 ] = getHourString(util.convIntegerTimeToDoubleTime(dto.getTiJikan()));
						// 早退時間
						aryAttendance[i][9 ] = getHourString(util.convIntegerTimeToDoubleTime(dto.getSoJikan()));
						// 残業時間
						aryAttendance[i][10] = getHourString(util.convIntegerTimeToDoubleTime(dto.getZaJikan()));
						// 休出時間
						aryAttendance[i][11] = getHourString(util.convIntegerTimeToDoubleTime(dto.getKsJikan()));
						// 深夜時間
						aryAttendance[i][12] = getHourString(util.convIntegerTimeToDoubleTime(dto.getSnJikan()));
					} else if (KintaiCommonPart.isWeekHoliday(dto)) {
						kinmu = CommonConst.ATTENDANCE_TYPE_WEEK_HOLIDAY;
					} else {
						for (int k = 0; k < aryHolidayReason.length; k++) {
							if (aryHolidayReason[k][0].equals(dto.getKKRiyuu())) {
								kinmu = aryHolidayReason[k][1];
							}
						}
					}
					aryAttendance[i][3 ] = kinmu;
					// 一次承認、二次承認
					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.isStartHalfHoliday(dto) 
							|| KintaiCommonPart.isQuitHalfHoliday(dto)
					) {
						aryAttendance[i][16] += CommonConst.NAM_VACATION_LEAVE_HALF + CommonConst.NAM_COMMON_HALF_KANA_SPACE;
					}
					// 休出
					if (KintaiCommonPart.isWorkOnHoliday(dto)) {
						aryAttendance[i][16] += CommonConst.NAM_WORK_ON_HOLIDAY + CommonConst.NAM_COMMON_HALF_KANA_SPACE;		
					}
					break;
				}
				cal.add(Calendar.DAY_OF_MONTH, 1);
			}
		}
	}

	/**
	 * 残業申請判断
	 * @param kCode
	 * @param targetDate
	 * @return
	 * @throws Exception
	 */
	private boolean isOverTimeRequest(String kCode, Date targetDate) throws Exception {
		if (VariousPart.chkExistDto(PartManager.overtime(partInfo())
				.getTargetOverTimeRequest(kCode, targetDate))
		) {
			return true;
		}
		return false;
	}

}
