/*
 * 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.MosPWorkflowAction;
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.KintaiApprovalPart;
import jp.mosp.common.part.KintaiCommonPart;
import jp.mosp.common.part.PartManager;

import jp.mosp.kintai.dto.MSyukkinboDto;
import jp.mosp.kintai.vo.ApprovalListVo;

public class ApprovalListAction extends MosPWorkflowAction {

	// コマンド
	private static final String CMD_APPROVAL_LIST_SELECT		= "K2121";
	public  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 {
		// コネクション取得
		getConnection();
		// MANAGER権限確認
		confirmManagerAuth();
		// VOの取得
		ApprovalListVo vo;
		vo = (ApprovalListVo)getStoredVo(CommonConst.VO_APPROVAL_LIST);
		if (vo == null) {
			vo = new ApprovalListVo();
		}
		vo.initVo(cfg, msg, cmd, aspUser, user);
		vo.clearMessage();
		vo.clearErrField();
		storeVo(CommonConst.VO_APPROVAL_LIST, vo);
		// VO及びフォワード先URLの設定
		setVo(vo);
		setUrl(vo.getRetUrl());
		// ユーザー情報取得
		getInfo(user.getUserId());
		// 表示月
		Date current = getCalcMonth();
		// 勤怠管理コマンド
		vo.setCmdMenuButton(vo.CMD_MENU_MAMAGE);
		vo.setCmdListButton(EmployeeApprovalListAction.CMD_APPROVAL_LIST_RE_SEARCH);
		vo.setNamListButton(CommonConst.TTL_EMPLOYEE_APPROVAL);
		// プルダウン取得
		vo.aryPltYear  = util.getYearArray(MospUtility.getYear (current));
		vo.aryPltMonth = util.getMonthArray();
		// コマンド毎の処理
		if (cmd.equals(CMD_APPROVAL_LIST_SELECT)) {
			// 選択
			// 対象社員設定
			vo.setSelectKCode(key1);
			// 対象年月日設定
			String[] aryDate = util.divideByHyphen(key2, 1);
			vo.setPltYear(aryDate[0]);
			vo.setPltMonth(aryDate[1]);
			// 表示
			show(vo);
		} else if (cmd.equals(CMD_APPROVAL_LIST_SEARCH)) {
			// 対象年月日設定
			vo.setParams(request);
			// 表示
			show(vo);
		} else if (cmd.equals(CMD_LUMP_SUM_1ST_APPROVAL)) {
			// 対象年月日設定
			vo.setParams(request);
			// 月一覧一次承認
			runApprovalProcess(vo);
			// 表示
			show(vo);
		} else if (cmd.equals(CMD_LUMP_SUM_2ND_APPROVAL)) {
			// 対象年月日設定
			vo.setParams(request);
			// 月一覧二次承認
			runApprovalProcess(vo);
			// 表示
			show(vo);
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}  
	}

	/**
	 * 表示
	 * @param vo			対象VO
	 * @throws Exception
	 */
	private void show(ApprovalListVo vo) throws Exception {
		// 承認権限のセット
		setApprovalAuth(vo);
		// 検索
		searchApprovalList(vo);
		// モード設定
		setMode(vo);
	}

	/**
	 * 承認権限設定
	 * @param vo
	 * @throws Exception
	 */
	private void setApprovalAuth(ApprovalListVo vo) throws Exception {
		// 対象年月取得
		Date targetDate = util.getFirstDateOfMonth(vo.getPltYear(), vo.getPltMonth());
		// 承認ルート情報設定
		String[] aryRouteInfo = getTargetRouteInfo(vo.getSelectKCode(), targetDate);
		// 一次承認
		if (isApprover(aryRouteInfo[0], targetDate)) {
			is1stApproval = true;
		}
		// 二次承認
		if (isApprover(aryRouteInfo[1], targetDate)) {
			is2ndApproval = true;
		}
	}

	/**
	 * 勤怠一覧検索
	 * @param vo Voインスタンス
	 * @throws Exception
	 */
	private void searchApprovalList(
			ApprovalListVo vo
	) throws Exception {
		// 対象期間設定
		Date targetMonth = util.getYearMonth(vo.getPltYear(), vo.getPltMonth());
		// 勤怠データ取得
		/*						
		 *  	2009/01/20	m.yoshida	締め日対応
		 */
		getAttendanceListForView(vo.getSelectKCode(), targetMonth);
		// 勤怠情報設定
		setCalcParam();
		// 日集計データ配列作成
		makeApprovalArray(attendanceList);
		// 月集計
		totalAttendanceDaily(vo.getSelectKCode(), attendanceList);
		// 承認情報のセット
		setApprovalInfo(vo);
		// 人事基本情報の取得
		HumanBasisDtoInterface mKihonDto = getBasisInfo(vo.getSelectKCode());
		// 選択情報の設定
		vo.setSelectKName(mKihonDto.getSimei());
		vo.setSelectSectionName(getSectionName(mKihonDto.getSCode()));
		// 月集計データとラベルを分離
		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);
	}

	/**
	 * 日集計データ配列作成
	 * @throws Exception
	 */
	private void makeApprovalArray(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();
			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 = dto.getSnRiyuu();
					aryAttendance[i][13] = PartManager.kintaiapproval(partInfo()).getApprovalName(dto);
					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.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 vo
	 * @throws Exception
	 */
	private void setApprovalInfo(ApprovalListVo vo) throws Exception {
		// DBコネクション取得
		if (conn == null) {
			getConnection();
		}
		// 対象年月取得
		Date targetDate = util.getFirstDateOfMonth(vo.getPltYear(), vo.getPltMonth());
		// 承認ルート情報設定
		String[] aryRouteInfo = getTargetRouteInfo(vo.getSelectKCode(), targetDate);
		// 一次承認
		String layer1 = aryRouteInfo[0];
		// 二次承認
		String lastLayer = aryRouteInfo[1];
		if (layer1.equals("") || lastLayer.equals("")) {
			// 勤怠情報クリア
			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] = "";
			}
		}
	}

	/**
	 * 月一覧承認処理
	 * @param vo			対象VO
	 * @param cmd			選択承認階層
	 * @throws Exception
	 */
	private void runApprovalProcess(ApprovalListVo vo) throws Exception {
		// 承認理由
		String reason = "";
		// 承認コメント
		String comment = "";
		// 一次承認
		if (cmd.equals(CMD_LUMP_SUM_1ST_APPROVAL)) {
			reason = CommonConst.NUM_ATTENDANCE_1ST_APPROVED;
			comment = MospUtility.getMessage(
					msg, CommonConst.MSG_NUMBER_OF_APPROVED, CommonConst.getKanjiNumberArray()[1]);
		}
		// 二次承認
		if (cmd.equals(CMD_LUMP_SUM_2ND_APPROVAL)) {
			reason = CommonConst.NUM_ATTENDANCE_2ND_APPROVED;
			comment = MospUtility.getMessage(
					msg, CommonConst.MSG_NUMBER_OF_APPROVED, CommonConst.getKanjiNumberArray()[2]);
		}
		// 対象年月日
		String[] aryTargetDate = vo.getAryApprovalDate();
		for (int i = 0; i < aryTargetDate.length; i++) {
			// 承認処理
			runApprovalProcess(vo.getSelectKCode(), aryTargetDate[i], reason, comment, mKihon.getKCode());			
		}
		// コミット
		commit();	
		// メッセージ設定
		vo.setMessage(MospUtility.getMessage(msg, MospConst.MSG_UPDATE, ""));
	}

	/**
	 * 承認モード設定
	 * @param vo
	 */
	private void setMode(ApprovalListVo vo) {
		// 出勤フラグ（有休休暇も含める）
		boolean isAttendance = false;
		int count = 0;
		for (int i = 0; i < vo.getEscAryAttendance().length; i++) {
			if (!vo.getEscAryAttendance()[i][3].equals("")) {
				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);
		}
	}

}
