/*
 * 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.util.Calendar;
import java.util.Date;
import java.util.Iterator;
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.NumberUtil;
import jp.mosp.common.utils.StringUtil;
import jp.mosp.common.utils.TimeUtil;
import jp.mosp.kintai.common.action.MosPWorkflowAction;
import jp.mosp.kintai.common.part.KintaiApprovalPart;
import jp.mosp.kintai.common.part.KintaiCommonPart;
import jp.mosp.kintai.dto.MSyukkinboDto;
import jp.mosp.kintai.workflow.vo.ApprovalListVo;

/**
 * @author yoshida
 *
 */
public class ApprovalListAction extends MosPWorkflowAction {
	
	// コマンド
	private static final String	CMD_APPROVAL_LIST_SELECT	= "K2121";
	private static final String	CMD_APPROVAL_LIST_SEARCH	= "K2122";
	private static final String	CMD_LUMP_SUM_1ST_APPROVAL	= "K2123";
	private static final String	CMD_LUMP_SUM_2ND_APPROVAL	= "K2124";
	
	// 所有承認フラグ
	private boolean				is1stApproval				= false;
	private boolean				is2ndApproval				= false;
	
	// 承認残存フラグ
	private boolean				is1stRemain					= false;
	private boolean				is2ndRemain					= false;
	

	/**
	 * コンストラクタ
	 */
	public ApprovalListAction() {
		super();
	}
	
	/**
	 * アクション
	 */
	public void action() throws Exception {
		// VOの取得
		prepareVo();
		// 初期処理
		init();
		// コマンド毎の処理
		if (cmd.equals(CMD_APPROVAL_LIST_SELECT)) {
			// 選択
			select();
		} else if (cmd.equals(CMD_APPROVAL_LIST_SEARCH)) {
			// 検索
			search();
		} else if (cmd.equals(CMD_LUMP_SUM_1ST_APPROVAL)) {
			// 月一覧一次承認
			runApprovalProcess();
		} else if (cmd.equals(CMD_LUMP_SUM_2ND_APPROVAL)) {
			// 月一覧二次承認
			runApprovalProcess();
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}
	}
	
	@Override
	protected BaseVo getSpecificVo() {
		return new ApprovalListVo();
	}
	
	@Override
	protected void init() throws Exception {
		// MANAGER権限確認
		confirmManagerAuth();
		ApprovalListVo vo = (ApprovalListVo)getVo();
		// ユーザー情報取得
		getInfo(user.getUserId());
		// プルダウン取得
		vo.aryPltYear = StringUtil.getYearArray(MospUtility.getYear(getCalcMonth()), 3, 1);
		vo.aryPltMonth = StringUtil.getMonthArray();
	}
	
	@Override
	protected void select() throws Exception {
		ApprovalListVo vo = (ApprovalListVo)getVo();
		// 対象社員設定
		vo.setSelectKCode(key1);
		// 対象年月日設定
		String[] aryDate = StringUtil.divideByHyphen(key2, 1);
		vo.setPltYear(aryDate[0]);
		vo.setPltMonth(aryDate[1]);
		// 検索
		searchApprovalList();
	}
	
	@Override
	protected void search() throws Exception {
		ApprovalListVo vo = (ApprovalListVo)getVo();
		// 対象年月日設定
		vo.setParams(request);
		// 検索
		searchApprovalList();
	}
	
	/**
	 * 勤怠一覧検索
	 * @throws Exception	例外処理が発生した場合
	 */
	private void searchApprovalList() throws Exception {
		ApprovalListVo vo = (ApprovalListVo)getVo();
		// 対象年月取得
		Date targetDate = DateUtil.getYearMonth(vo.getPltYear(), vo.getPltMonth());
		// 社員コード
		String kCode = vo.getSelectKCode();
		// 承認ルート情報設定
		String[] aryRouteInfo = getTargetRouteInfo(kCode, targetDate);
		// 一次承認
		if (isApprover(aryRouteInfo[0], targetDate)) {
			is1stApproval = true;
		}
		// 二次承認
		if (isApprover(aryRouteInfo[1], targetDate)) {
			is2ndApproval = true;
		}
		// 勤怠データ取得
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		getAttendanceListForView(kCode, targetDate);
		// 勤怠情報設定
		setCalcParam();
		// 選択社員労使協定情報取得
		setLaborAgreementInfo(kCode, targetDate);
		// 日集計データ配列作成
		makeApprovalArray(kCode, attendanceList);
		// 月集計
		totalAttendanceDaily(kCode, attendanceList);
		// 承認情報のセット
		setApprovalInfo();
		// 選択情報の設定
		setLabelBasisInfo(part().human().getBasisInfo(kCode));
		// 月集計データとラベルを分離
		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);
		// モード設定
		setMode();
	}
	
	/**
	 * 日集計データ配列作成
	 * @param kCode 社員コード
	 * @param attendanceList attendanceList
	 * @throws Exception	例外処理が発生した場合
	 */
	private void makeApprovalArray(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 size = 40;
		aryAttendance = StringUtil.getBlankArray(count, size);
		// 日付設定
		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] = 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_OVERTIME;
				aryAttendance[i][16] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
			}
			// 休暇申請
			if (part().holidayRequest().existHolidayRequest(kCode, cal.getTime())) {
				aryAttendance[i][16] += CommonConst.NAM_VACATION_LEAVE;
				aryAttendance[i][16] += CommonConst.NAM_COMMON_HALF_KANA_SPACE;
			}
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
		// 1ヶ月の時間外時間
		int overTimeMonthly = 0;
		// データの設定
		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) {
					// 下書きの場合、表示しない。
					if (!KintaiApprovalPart.isDraft(dto)) {
						// 勤務形態
						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";
							// 月60時間時間外時間
							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)) {
							// 週休→所定休日表示
							//kinmu = CommonConst.ATTENDANCE_TYPE_WEEK_HOLIDAY;
							kinmuName = CommonConst.NAM_STANDARD_WEEK_HOLIDAY;
						} else if (KintaiCommonPart.isOfficialHoliday(dto)) {
							kinmuName = part().worktype().getWorkTypeName(dto.getKinmu());
						} else if (KintaiCommonPart.isSubstituteAll(dto)) {
							kinmuName = CommonConst.NAM_SUB_HOLIDAY;
						} else {
							// 休暇理由
							kinmuName = part().mospcode().getHolidayName(dto.getKKRiyuu());
						}
						aryAttendance[i][3] = kinmuName;
						// 一次承認、二次承認
						aryAttendance[i][13] = part().kintaiApproval().getApprovalName(dto);
						String result = dto.getSnRiyuu();
						if (KintaiApprovalPart.isRequest(dto)) {
							is1stRemain = true;
							// 一次承認権限保有の場合
							if (is1stApproval) {
								aryAttendance[i][14] = result;
							}
						} else if (KintaiApprovalPart.is1stApproved(dto)) {
							// 二次承認権限保有の場合
							is2ndRemain = true;
							if (is2ndApproval) {
								aryAttendance[i][14] = result;
							}
						}
						// 承認者
						aryAttendance[i][15] = getKName(dto.getNinsyo());
						// 半休
						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);
			}
		}
	}
	
	/**
	 * 勤怠承認情報
	 * @throws Exception	例外処理が発生した場合
	 */
	private void setApprovalInfo() throws Exception {
		ApprovalListVo vo = (ApprovalListVo)getVo();
		// 対象年月取得
		Date targetDate = DateUtil.getFirstDateOfMonth(vo.getPltYear(), vo.getPltMonth());
		// 承認ルート情報設定
		String[] aryRouteInfo = getTargetRouteInfo(vo.getSelectKCode(), targetDate);
		if (StringUtil.isNull(aryRouteInfo[0]) || StringUtil.isNull(aryRouteInfo[1])) {
			// 勤怠情報クリア
			for (int i = 0; i < aryAttendance.length; i++) {
				aryAttendance[i][3] = "";
				aryAttendance[i][4] = "";
				aryAttendance[i][5] = "";
				aryAttendance[i][6] = "";
				aryAttendance[i][7] = "";
				aryAttendance[i][8] = "";
				aryAttendance[i][9] = "";
				aryAttendance[i][10] = "";
				aryAttendance[i][11] = "";
				aryAttendance[i][12] = "";
				aryAttendance[i][13] = "";
				aryAttendance[i][14] = "";
			}
			for (int i = 0; i < aryAttendanceCompile.length; i++) {
				aryAttendanceCompile[i][1] = "0";
			}
		}
		// 両方の承認権限を保有してる場合の申請中残存時の処理
		for (int i = 0; i < aryAttendance.length; i++) {
			if (is1stRemain && is1stApproval && is2ndApproval && KintaiApprovalPart.is1stApproved(aryAttendance[i][14])) {
				aryAttendance[i][14] = "";
			}
		}
	}
	
	/**
	 * 月一覧承認処理
	 * @throws Exception	例外処理が発生した場合
	 */
	private void runApprovalProcess() throws Exception {
		ApprovalListVo vo = (ApprovalListVo)getVo();
		// 承認コメント
		String comment = "";
		// 一次承認
		if (cmd.equals(CMD_LUMP_SUM_1ST_APPROVAL)) {
			comment = getMessage(CommonConst.MSG_NUMBER_OF_APPROVED, NumberUtil.NAM_ONE);
		}
		// 二次承認
		if (cmd.equals(CMD_LUMP_SUM_2ND_APPROVAL)) {
			comment = getMessage(CommonConst.MSG_NUMBER_OF_APPROVED, NumberUtil.NAM_TWO);
		}
		// 対象年月日
		String[] aryTargetDate = request.getParameterValues(ApprovalListVo.PRM_CKB_DATE);
		for (String element : aryTargetDate) {
			// 承認処理
			runDailyApprovalProcess(vo.getSelectKCode(), DateUtil.convStringDateToDate(element), comment, true);
		}
		// コミット
		commit();
		// メッセージ設定
		setMessage(getMessage(MospConst.MSG_UPDATE, ""));
		// 検索
		searchApprovalList();
	}
	
	/**
	 * 承認モード設定
	 */
	private void setMode() {
		ApprovalListVo vo = (ApprovalListVo)getVo();
		// 出勤フラグ（有休休暇も含める）
		boolean isAttendance = false;
		int count = 0;
		for (int i = 0; i < vo.getEscAryAttendance().length; i++) {
			if (StringUtil.isNotNull(vo.getEscAryAttendance()[i][3])) {
				count++;
			}
		}
		if (count > 0) {
			isAttendance = true;
		}
		// 一件でも一次承認が残っている場合、一次承認が優先される。
		if (is1stRemain) {
			if (is1stApproval) {
				vo.setMode(ApprovalListVo.MODE_1ST_APPROVAL);
			} else if (is2ndApproval) {
				vo.setMode(ApprovalListVo.MODE_2ND_APPROVAL);
			}
		} else if (is2ndApproval && isAttendance && is2ndRemain) {
			vo.setMode(ApprovalListVo.MODE_2ND_APPROVAL);
		} else {
			vo.setMode(ApprovalListVo.MODE_NOT_AUTH);
		}
	}
	
}
