/*
 * 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 Affero General Public License
 * as published by the Free Software Foundation, either version 3
 * 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 Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jp.mosp.time.bean.impl;

import java.sql.Connection;
import java.util.Date;
import java.util.List;

import jp.mosp.framework.base.BaseDtoInterface;
import jp.mosp.framework.base.MospException;
import jp.mosp.framework.base.MospParams;
import jp.mosp.framework.utils.DateUtility;
import jp.mosp.platform.bean.workflow.WorkflowReferenceBeanInterface;
import jp.mosp.platform.bean.workflow.WorkflowRegistBeanInterface;
import jp.mosp.platform.constant.PlatformConst;
import jp.mosp.platform.dto.workflow.WorkflowDtoInterface;
import jp.mosp.time.base.TimeBean;
import jp.mosp.time.bean.ApplicationReferenceBeanInterface;
import jp.mosp.time.bean.ApprovalInfoReferenceBeanInterface;
import jp.mosp.time.bean.AttendanceCalcBeanInterface;
import jp.mosp.time.bean.AttendanceListRegistBeanInterface;
import jp.mosp.time.bean.AttendanceRegistBeanInterface;
import jp.mosp.time.bean.DifferenceRequestRegistBeanInterface;
import jp.mosp.time.bean.HolidayRequestRegistBeanInterface;
import jp.mosp.time.bean.OvertimeRequestRegistBeanInterface;
import jp.mosp.time.bean.RequestUtilBeanInterface;
import jp.mosp.time.bean.ScheduleDateReferenceBeanInterface;
import jp.mosp.time.bean.ScheduleReferenceBeanInterface;
import jp.mosp.time.bean.SubHolidayRequestRegistBeanInterface;
import jp.mosp.time.bean.SubstituteReferenceBeanInterface;
import jp.mosp.time.bean.TimeApprovalBeanInterface;
import jp.mosp.time.bean.WorkOnHolidayRequestRegistBeanInterface;
import jp.mosp.time.bean.WorkTypeReferenceBeanInterface;
import jp.mosp.time.constant.TimeConst;
import jp.mosp.time.dto.settings.ApplicationDtoInterface;
import jp.mosp.time.dto.settings.AttendanceDtoInterface;
import jp.mosp.time.dto.settings.DifferenceRequestDtoInterface;
import jp.mosp.time.dto.settings.HolidayRequestDtoInterface;
import jp.mosp.time.dto.settings.OvertimeRequestDtoInterface;
import jp.mosp.time.dto.settings.ScheduleDateDtoInterface;
import jp.mosp.time.dto.settings.ScheduleDtoInterface;
import jp.mosp.time.dto.settings.SubHolidayRequestDtoInterface;
import jp.mosp.time.dto.settings.SubstituteDtoInterface;
import jp.mosp.time.dto.settings.WorkOnHolidayRequestDtoInterface;
import jp.mosp.time.dto.settings.WorkTypeDtoInterface;

/**
 * 勤怠関連申請承認クラス。<br>
 * 勤怠関連の申請に対して承認、差戻などの機能を提供する。<br>
 */
public class TimeApprovalBean extends TimeBean implements TimeApprovalBeanInterface {
	
	/**
	 * 承認情報参照クラス。<br>
	 */
	protected ApprovalInfoReferenceBeanInterface	approvalInfo;
	
	/**
	 * ワークフロー参照クラス。<br>
	 */
	protected WorkflowReferenceBeanInterface		workflowRefer;
	
	/**
	 * ワークフロー登録クラス。<br>
	 */
	protected WorkflowRegistBeanInterface			workflowRegist;
	
	/**
	 * 勤怠一覧登録クラス。<br>
	 */
	private AttendanceListRegistBeanInterface		attendanceListRegist;
	
	/**
	 * 勤怠データ登録クラス。<br>
	 */
	private AttendanceRegistBeanInterface			attendanceRegist;
	
	/**
	 * 勤怠データ自動計算クラス。<br>
	 */
	private AttendanceCalcBeanInterface				attendanceCalc;
	
	/**
	 * 時差出勤申請登録クラス。
	 */
	private DifferenceRequestRegistBeanInterface	differenceRequestRegist;
	
	/**
	 * 代休申請登録クラス。
	 */
	private SubHolidayRequestRegistBeanInterface	subHolidayRequestRegist;
	
	/**
	 * 休日出勤申請登録クラス。
	 */
	private WorkOnHolidayRequestRegistBeanInterface	workOnHolidayRequestRegist;
	
	/**
	 * 休暇申請登録クラス。
	 */
	private HolidayRequestRegistBeanInterface		holidayRequestRegist;
	
	/**
	 * 残業申請登録クラス。
	 */
	private OvertimeRequestRegistBeanInterface		overtimeRequestRegist;
	
	/**
	 * 振替休日データ参照クラス。
	 */
	private SubstituteReferenceBeanInterface		substituteReference;
	
	/**
	 * 設定適用管理参照クラス。
	 */
	private ApplicationReferenceBeanInterface		applicationReference;
	
	/**
	 * カレンダ管理参照クラス。
	 */
	private ScheduleReferenceBeanInterface			scheduleReference;
	
	/**
	 * カレンダ日参照クラス。
	 */
	private ScheduleDateReferenceBeanInterface		scheduleDateReference;
	
	/**
	 * 勤務形態マスタ参照クラス。
	 */
	private WorkTypeReferenceBeanInterface			workTypeReference;
	

	/**
	 * {@link TimeBean#TimeBean()}を実行する。<br>
	 */
	public TimeApprovalBean() {
		super();
	}
	
	/**
	 * {@link TimeBean#TimeBean(MospParams, Connection)}を実行する。<br>
	 * @param mospParams MosP処理情報
	 * @param connection DBコネクション
	 */
	public TimeApprovalBean(MospParams mospParams, Connection connection) {
		super(mospParams, connection);
	}
	
	@Override
	public void initBean() throws MospException {
		//
		approvalInfo = (ApprovalInfoReferenceBeanInterface)createBean(ApprovalInfoReferenceBeanInterface.class);
		workflowRefer = (WorkflowReferenceBeanInterface)createBean(WorkflowReferenceBeanInterface.class);
		workflowRegist = (WorkflowRegistBeanInterface)createBean(WorkflowRegistBeanInterface.class);
		attendanceListRegist = (AttendanceListRegistBeanInterface)createBean(AttendanceListRegistBeanInterface.class);
		attendanceRegist = (AttendanceRegistBeanInterface)createBean(AttendanceRegistBeanInterface.class);
		attendanceCalc = (AttendanceCalcBeanInterface)createBean(AttendanceCalcBeanInterface.class);
		differenceRequestRegist = (DifferenceRequestRegistBeanInterface)createBean(DifferenceRequestRegistBeanInterface.class);
		subHolidayRequestRegist = (SubHolidayRequestRegistBeanInterface)createBean(SubHolidayRequestRegistBeanInterface.class);
		overtimeRequestRegist = (OvertimeRequestRegistBeanInterface)createBean(OvertimeRequestRegistBeanInterface.class);
		holidayRequestRegist = (HolidayRequestRegistBeanInterface)createBean(HolidayRequestRegistBeanInterface.class);
		workOnHolidayRequestRegist = (WorkOnHolidayRequestRegistBeanInterface)createBean(WorkOnHolidayRequestRegistBeanInterface.class);
		substituteReference = (SubstituteReferenceBeanInterface)createBean(SubstituteReferenceBeanInterface.class);
		applicationReference = (ApplicationReferenceBeanInterface)createBean(ApplicationReferenceBeanInterface.class);
		scheduleReference = (ScheduleReferenceBeanInterface)createBean(ScheduleReferenceBeanInterface.class);
		scheduleDateReference = (ScheduleDateReferenceBeanInterface)createBean(ScheduleDateReferenceBeanInterface.class);
		workTypeReference = (WorkTypeReferenceBeanInterface)createBean(WorkTypeReferenceBeanInterface.class);
	}
	
	@Override
	public void approve(long workflow, String workflowComment) throws MospException {
		// 申請情報の取得
		BaseDtoInterface requestDto = approvalInfo.getRequestDtoForWorkflow(workflow, true);
		// 承認時の確認処理
		checkApproval(requestDto);
		// 処理結果確認
		if (mospParams.hasErrorMessage()) {
			return;
		}
		// DTOの準備
		WorkflowDtoInterface dto = workflowRefer.getLatestWorkflowInfo(workflow);
		// 承認処理
		workflowRegist.approve(dto, PlatformConst.WORKFLOW_TYPE_TIME, workflowComment);
		if (PlatformConst.CODE_STATUS_COMPLETE.equals(dto.getWorkflowStatus())) {
			// 承認済の場合は勤怠を下書し直す
			reDraft(dto.getPersonalId(), dto.getWorkflowDate());
		}
	}
	
	@Override
	public void revert(long workflow, String workflowComment) throws MospException {
		// DTOの準備
		WorkflowDtoInterface dto = workflowRefer.getLatestWorkflowInfo(workflow);
		// 差戻処理
		workflowRegist.revert(dto, PlatformConst.WORKFLOW_TYPE_TIME, workflowComment);
	}
	
	@Override
	public void approve(long[] aryWorkflow, String workflowComment) throws MospException {
		// ワークフロー毎に処理
		for (long workflow : aryWorkflow) {
			// 承認処理
			approve(workflow, workflowComment);
		}
	}
	
	@Override
	public void cancel(long workflow, String workflowComment) throws MospException {
		// 申請情報の取得
		BaseDtoInterface requestDto = approvalInfo.getRequestDtoForWorkflow(workflow, true);
		// 承認解除時の確認処理
		checkCancel(requestDto);
		// 処理結果確認
		if (mospParams.hasErrorMessage()) {
			return;
		}
		// DTOの準備
		WorkflowDtoInterface dto = workflowRefer.getLatestWorkflowInfo(workflow);
		// 承認解除処理
		workflowRegist.cancel(dto, PlatformConst.WORKFLOW_TYPE_TIME, workflowComment);
		if (TimeConst.CODE_FUNCTION_WORK_HOLIDAY.equals(dto.getFunctionCode())) {
			// 振出・休出申請の場合は勤怠を削除する
			attendanceRegist.delete(dto.getPersonalId(), dto.getWorkflowDate());
			return;
		} else if (TimeConst.CODE_FUNCTION_OVER_WORK.equals(dto.getFunctionCode())
				|| TimeConst.CODE_FUNCTION_VACATION.equals(dto.getFunctionCode())
				|| TimeConst.CODE_FUNCTION_COMPENSATORY_HOLIDAY.equals(dto.getFunctionCode())
				|| TimeConst.CODE_FUNCTION_DIFFERENCE.equals(dto.getFunctionCode())) {
			// 残業申請、休暇申請、代休申請、時差出勤申請の場合は勤怠を下書し直す
			reDraft(dto.getPersonalId(), dto.getWorkflowDate());
		}
	}
	
	@Override
	public void checkApproval(BaseDtoInterface dto) throws MospException {
		// 勤怠データ
		if (dto instanceof AttendanceDtoInterface) {
			attendanceRegist.checkApproval((AttendanceDtoInterface)dto);
		}
		// 残業申請
		if (dto instanceof OvertimeRequestDtoInterface) {
			overtimeRequestRegist.checkApproval((OvertimeRequestDtoInterface)dto);
		}
		// 休暇申請
		if (dto instanceof HolidayRequestDtoInterface) {
			holidayRequestRegist.checkApproval((HolidayRequestDtoInterface)dto);
		}
		// 休日出勤
		if (dto instanceof WorkOnHolidayRequestDtoInterface) {
			workOnHolidayRequestRegist.checkApproval((WorkOnHolidayRequestDtoInterface)dto);
		}
		// 代休申請
		if (dto instanceof SubHolidayRequestDtoInterface) {
			subHolidayRequestRegist.checkApproval((SubHolidayRequestDtoInterface)dto);
		}
		// 時差出勤
		if (dto instanceof DifferenceRequestDtoInterface) {
			differenceRequestRegist.checkApproval((DifferenceRequestDtoInterface)dto);
		}
	}
	
	@Override
	public void checkCancel(BaseDtoInterface dto) throws MospException {
		// 勤怠データ
		if (dto instanceof AttendanceDtoInterface) {
			attendanceRegist.checkCancel((AttendanceDtoInterface)dto);
		}
		// 残業申請
		if (dto instanceof OvertimeRequestDtoInterface) {
			overtimeRequestRegist.checkCancel((OvertimeRequestDtoInterface)dto);
		}
		// 休暇申請
		if (dto instanceof HolidayRequestDtoInterface) {
			holidayRequestRegist.checkCancel((HolidayRequestDtoInterface)dto);
		}
		// 休日出勤
		if (dto instanceof WorkOnHolidayRequestDtoInterface) {
			workOnHolidayRequestRegist.checkCancel((WorkOnHolidayRequestDtoInterface)dto);
		}
		// 代休申請
		if (dto instanceof SubHolidayRequestDtoInterface) {
			subHolidayRequestRegist.checkCancel((SubHolidayRequestDtoInterface)dto);
		}
		// 時差出勤
		if (dto instanceof DifferenceRequestDtoInterface) {
			differenceRequestRegist.checkCancel((DifferenceRequestDtoInterface)dto);
		}
	}
	
	@Override
	public void reDraft(String personalId, Date workDate) throws MospException {
		RequestUtilBeanInterface requestUtil = (RequestUtilBeanInterface)createBean(RequestUtilBeanInterface.class);
		requestUtil.setRequests(personalId, workDate);
		AttendanceDtoInterface dto = requestUtil.getDraftAttendance();
		if (dto == null) {
			return;
		}
		// 勤務形態をセット
		dto.setWorkTypeCode(getWorkTypeCode(requestUtil));
		// 始業終業時刻自動計算
		attendanceCalc.calcStartEndTime(dto, false);
		String startTime = "";
		if (dto.getStartTime() != null) {
			StringBuffer sb = new StringBuffer();
			sb.append(DateUtility.getStringHour(dto.getStartTime(), dto.getWorkDate()));
			sb.append(DateUtility.getStringMinute(dto.getStartTime()));
			startTime = sb.toString();
		}
		String endTime = "";
		if (dto.getEndTime() != null) {
			StringBuffer sb = new StringBuffer();
			sb.append(DateUtility.getStringHour(dto.getEndTime(), dto.getWorkDate()));
			sb.append(DateUtility.getStringMinute(dto.getEndTime()));
			endTime = sb.toString();
		}
		// 勤怠データ下書
		attendanceListRegist.draft(dto.getPersonalId(), new String[]{ DateUtility.getStringDate(dto.getWorkDate()) },
				new String[]{ startTime }, new String[]{ endTime });
	}
	
	/**
	 * 勤務形態コードを取得する。<br>
	 * @param requestUtil 申請ユーティリティ
	 * @return 勤務形態コード
	 * @throws MospException インスタンスの取得及びSQL実行に失敗した場合
	 */
	protected String getWorkTypeCode(RequestUtilBeanInterface requestUtil) throws MospException {
		AttendanceDtoInterface attendanceDto = requestUtil.getDraftAttendance();
		if (attendanceDto == null) {
			return "";
		}
		Date targetDate = attendanceDto.getWorkDate();
		DifferenceRequestDtoInterface differenceRequestDto = requestUtil.getDifferenceDto(true);
		if (differenceRequestDto != null) {
			return differenceRequestDto.getDifferenceType();
		}
		WorkOnHolidayRequestDtoInterface workOnHolidayRequestDto = requestUtil.getWorkOnHolidayDto(true);
		if (workOnHolidayRequestDto != null) {
			int substitute = workOnHolidayRequestDto.getSubstitute();
			if (substitute == TimeConst.CODE_WORK_ON_HOLIDAY_SUBSTITUTE_ON) {
				// 振替出勤
				List<SubstituteDtoInterface> list = substituteReference.getSubstituteList(workOnHolidayRequestDto
					.getWorkflow());
				for (SubstituteDtoInterface substituteDto : list) {
					targetDate = substituteDto.getSubstituteDate();
					break;
				}
			} else if (substitute == TimeConst.CODE_WORK_ON_HOLIDAY_SUBSTITUTE_OFF) {
				// 休日出勤
				if (TimeConst.CODE_HOLIDAY_LEGAL_HOLIDAY.equals(workOnHolidayRequestDto.getWorkOnHolidayType())) {
					// 法定休日労動
					return TimeConst.CODE_WORK_ON_LEGAL_HOLIDAY;
				} else if (TimeConst.CODE_HOLIDAY_PRESCRIBED_HOLIDAY.equals(workOnHolidayRequestDto
					.getWorkOnHolidayType())) {
					// 所定休日労動
					return TimeConst.CODE_WORK_ON_PRESCRIBED_HOLIDAY;
				}
			}
		}
		WorkTypeDtoInterface attendanceWorkTypeDto = workTypeReference.findForInfo(attendanceDto.getWorkTypeCode(),
				attendanceDto.getWorkDate());
		if (attendanceWorkTypeDto != null) {
			return attendanceWorkTypeDto.getWorkTypeCode();
		}
		ApplicationDtoInterface applicationDto = applicationReference.findForPerson(attendanceDto.getPersonalId(),
				targetDate);
		applicationReference.chkExistApplication(applicationDto, attendanceDto.getWorkDate());
		if (mospParams.hasErrorMessage()) {
			return "";
		}
		ScheduleDtoInterface scheduleDto = scheduleReference.getScheduleInfo(applicationDto.getScheduleCode(),
				targetDate);
		scheduleReference.chkExistSchedule(scheduleDto, attendanceDto.getWorkDate());
		if (mospParams.hasErrorMessage()) {
			return "";
		}
		ScheduleDateDtoInterface scheduleDateDto = scheduleDateReference.getScheduleDateInfo(scheduleDto
			.getScheduleCode(), scheduleDto.getActivateDate(), targetDate);
		scheduleDateReference.chkExistScheduleDate(scheduleDateDto, attendanceDto.getWorkDate());
		if (mospParams.hasErrorMessage()) {
			return "";
		}
		WorkTypeDtoInterface workTypeDto = workTypeReference.findForInfo(scheduleDateDto.getWorkTypeCode(), targetDate);
		if (workTypeDto == null) {
			return "";
		}
		return workTypeDto.getWorkTypeCode();
	}
	
}
