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

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

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.TimeUtil;
import jp.mosp.kintai.common.action.AttendanceTotalAction;
import jp.mosp.kintai.common.part.KintaiCommonPart;
import jp.mosp.kintai.dto.MScheduleDto;
import jp.mosp.kintai.vo.ScheduleEditCardVo;

/**
 * @author yoshida
 *
 */
public class ScheduleEditCardAction extends AttendanceTotalAction {
	
	// コマンド
	private static final String	CMD_EDIT_CARD_SHOW		= "K1240";
	private static final String	CMD_EDIT_CARD_SEARCH	= "K1242";
	private static final String	CMD_EDIT_CARD_REGIST	= "K1244";
	

	/**
	 * コンストラクタ
	 */
	public ScheduleEditCardAction() {
		super();
	}
	
	/**
	 * アクション
	 */
	public void action() throws Exception {
		// VOの取得
		prepareVo(false);
		// 初期処理
		init();
		// コマンド毎の処理
		if (cmd.equals(CMD_EDIT_CARD_SHOW)) {
			// 表示
			show();
		} else if (cmd.equals(CMD_EDIT_CARD_SEARCH)) {
			// 検索
			search();
		} else if (cmd.equals(CMD_EDIT_CARD_REGIST)) {
			// 登録
			regist();
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}
	}
	
	@Override
	protected BaseVo getSpecificVo() {
		return new ScheduleEditCardVo();
	}
	
	@Override
	protected void init() throws Exception {
		ScheduleEditCardVo vo = (ScheduleEditCardVo)getVo();
		// ユーザー情報取得
		getInfo(user.getUserId());
		// プルダウン取得
		vo.aryPltYear = StringUtil.getYearArray(MospUtility.getYear(DateUtil.getSystemDate()), 3, 1);
		vo.aryPltMonth = StringUtil.getMonthArray();
		vo.aryPltWorkType = StringUtil.addArrayFirstRowSpace(part().worktype().getWorkTypeInfoArrayWithHoliday());
		// 対象社員設定
		vo.setSelectKCode(userBasis.getKCode());
		// メッセージ表示
		// 予定簿から削除する方法をメッセージにセットする。
		setMessage(CommonConst.MSG_SCHEDULE_EDIT_METHODS);
		setScheduleMenuButton();
	}
	
	@Override
	protected void show() throws Exception {
		ScheduleEditCardVo vo = (ScheduleEditCardVo)getVo();
		// 表示月
		Date current = DateUtil.getSystemDate();
		// 対象年月日設定
		vo.setPltYear(String.valueOf(MospUtility.getYear(current)));
		vo.setPltMonth(String.valueOf(MospUtility.getMonth(current)));
		// 検索
		searchScheduleList();
	}
	
	@Override
	protected void search() throws Exception {
		ScheduleEditCardVo vo = (ScheduleEditCardVo)getVo();
		// 対象年月日設定
		vo.setParams(request);
		// 検索
		searchScheduleList();
	}
	
	/**
	 * 予定一覧検索
	 * @throws Exception 	例外処理が発生した場合
	 */
	private void searchScheduleList() throws Exception {
		ScheduleEditCardVo vo = (ScheduleEditCardVo)getVo();
		// 勤怠データ取得
		getScheduleListForView(vo.getSelectKCode(), DateUtil.getYearMonth(vo.getPltYear(), vo.getPltMonth()));
		// 日集計データ時間設定
		setScheduleHours(scheduleList);
		// 日集計データ配列作成
		makeScheduleArray(vo.getSelectKCode(), scheduleList);
		// 選択情報の設定
		setLabelBasisInfo(part().human().getBasisInfo(vo.getSelectKCode()));
		// VO設定
		vo.setFields(aryAttendance);
	}
	
	/**
	 * 日集計データ配列作成
	 * @param kCode 対象社員コード
	 * @param scheduleList 予定簿情報リスト
	 * @throws Exception 	例外処理が発生した場合
	 */
	private void makeScheduleArray(String kCode, List<MScheduleDto> scheduleList) 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 size = 40;
		aryAttendance = new String[count][size];
		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] = DateUtil.convDateToMonthDayShort(cal.getTime());
			// 曜日
			aryAttendance[i][1] = getDayOfWeek(cal.get(Calendar.DAY_OF_WEEK));
			aryAttendance[i][9] = 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][8] = remark.toString();
			// 残業申請
			if (part().overtime().isOverTimeRequest(kCode, cal.getTime())) {
				aryAttendance[i][8] += CommonConst.NAM_OVERTIME;
				aryAttendance[i][8] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
			}
			// 休暇申請
			if (part().holidayRequest().existHolidayRequest(kCode, cal.getTime())) {
				aryAttendance[i][8] += CommonConst.NAM_VACATION_LEAVE;
				aryAttendance[i][8] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
			}
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
		// データの設定
		Iterator<MScheduleDto> it = scheduleList.iterator();
		while (it.hasNext()) {
			cal.setTime(MospUtility.getDate(startDate));
			MScheduleDto dto = it.next();
			Date scheduleDate = MospUtility.getDate(dto.getHizuke());
			for (int i = 0; i < aryAttendance.length; i++) {
				if (scheduleDate.compareTo(cal.getTime()) == 0) {
					// 勤務形態名称
					String kinmuName = "";
					// 勤務形態コード
					String workCode = dto.getKinmu();
					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()));
					} else if (KintaiCommonPart.isWeekHoliday(dto) || KintaiCommonPart.isOfficialHoliday(dto)) {
						// 週休→所定休日、法定休日表示
						kinmuName = part().worktype().getWorkTypeName(dto.getKinmu());
					} else {
						// 休暇理由
						kinmuName = part().mospcode().getHolidayName(dto.getKKRiyuu());
					}
					aryAttendance[i][2] = kinmuName;
					aryAttendance[i][3] = workCode;
					break;
				}
				cal.add(Calendar.DAY_OF_MONTH, 1);
			}
		}
	}
	
	/**
	 * 登録処理
	 * @throws Exception 	例外処理が発生した場合
	 */
	private void regist() throws Exception {
		ScheduleEditCardVo vo = (ScheduleEditCardVo)getVo();
		// パラメータ設定
		vo.setParams(request);
		// 勤怠情報設定
		setCalcParam();
		// 更新・登録件数
		int number = registSchedule(vo.getSelectKCode(), makeScheduleMap(DateUtil.getYearMonth(vo.getPltYear(), vo
			.getPltMonth())));
		// コミット
		commit();
		// 予定確認へ遷移
		setNextCmd(ScheduleConfirmListAction.CMD_CONFIRM_LIST_SEARCH);
		// メッセージ設定
		setMessage(getMessage(CommonConst.MSG_NUMBER_OF_UPDATES, String.valueOf(number)));
	}
	
	/**
	 * スケジュールMap生成
	 * @param targetMonth 対象月
	 * @return 登録用スケジュールMap
	 * @throws Exception 	例外処理が発生した場合
	 */
	private Map<Date, String> makeScheduleMap(Date targetMonth) throws Exception {
		ScheduleEditCardVo vo = (ScheduleEditCardVo)getVo();
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		Date startDate = getStartDateForList(targetMonth);
		Date endDate = getEndDateForList(targetMonth);
		// データ数取得
		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);
		// 日数の設定
		int count = 0;
		Map<Date, String> scheduleMap = new HashMap<Date, String>();
		while (endDate.compareTo(cal.getTime()) >= 0) {
			scheduleMap.put(cal.getTime(), vo.getArySelectWorktype()[count]);
			cal.add(Calendar.DAY_OF_MONTH, 1);
			count++;
		}
		return scheduleMap;
	}
	
}
