/**
 *                                                (客先名) 殿
 *                                             サブシステム名
 *                           機能名(プログラム名)(プログラムID)
 *
 *                                                       作成:アイエムシンクタンク株式会社
 *                                                       初版:年月日 by IMTT 作成者
 *                                                       改版:年月日 by
 */
package com.aimluck.eip.exttimecard;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.cayenne.DataRow;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.query.SQLTemplate;

import com.aimluck.eip.cayenne.om.portlet.EipTExtTimecard;
import com.aimluck.eip.cayenne.om.portlet.ImwTExtTimecardSystemDetail;
import com.aimluck.eip.cayenne.om.portlet.ImwTJobOrder;
import com.aimluck.eip.cayenne.om.portlet.ImwTOfficeCalendar;
import com.aimluck.eip.common.ALData;
import com.aimluck.eip.common.ALEipHolidaysManager;
import com.aimluck.eip.common.ALHoliday;
import com.aimluck.eip.exttimecard.util.CalculateDate;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.util.ALEipUtils;

public class ExtTimecardDayResultData implements ALData {

	// 曜日
	private String week;

	// 開始時刻
	private String start_time;

	// 終了時間
	private String end_time;

	// 作業内容
	private String project_contents;

	// 休憩時間
	private String rest_time;

	// 直接作業時間
	private String work_time;

	// 時間外普通
	private String ordinary_time;

	// 時間外深夜
	private String night_time;

	// 時間外法定休日
	private String legal_holiday_time;

	// 時間外休日深夜
	private String legal_holiday_night_time;

	// 時 間外法定外休日
	private String holiday_time;

	// 時 間外休日深夜
	private String holiday_night_time;

	// 遅刻早退時間
	private String late_early_time;

	// 有給休暇（日）
	private String paid_leave;

	// 自家用車通 勤 ○ △ ×
	private String oneself_car;

	// 備考
	private String temp_note;

	// 判決祭
	private String isHoliday;

	private DataContext dataContext;

	private Date date;

	public void initField() {
		// TODO 自動生成されたメソッド・スタブ
		dataContext = DatabaseOrmService.getInstance().getDataContext();
		date = new Date();
		week = " ";
		start_time = " ";
		end_time = " ";
		project_contents = " ";
		rest_time = " ";
		work_time = " ";
		ordinary_time = " ";
		night_time = " ";
		legal_holiday_time = " ";
		legal_holiday_night_time = " ";
		holiday_time = " ";
		holiday_night_time = " ";
		late_early_time = " ";
		paid_leave = " ";
		oneself_car = " ";
		temp_note = " ";
		isHoliday = " ";
	}

	/**
	 * @param userId
	 */
	public void setThisObject(String userId) {
		EipTExtTimecard entity = getTxtTimecards(userId, date);
		SimpleDateFormat format = new SimpleDateFormat("HH:mm");
		if (entity != null) {
			// 開始時刻
			if (entity.getClockInTime() != null) {
				start_time = format.format(entity.getClockInTime());
			}
			// 終了時間
			if (entity.getClockOutTime() != null) {
				end_time = format.format(entity.getClockOutTime());
			}

			// 作業内容
			project_contents = setProjectContents(entity);
			// 曜日
			SimpleDateFormat sdf = new SimpleDateFormat("EE");
			week = sdf.format(date);

			// Calculate Date
			CalculateDate cd = new CalculateDate();
			cd.initFile();
			if (entity.getClockInTime() != null
					&& entity.getClockOutTime() != null) {
				ImwTExtTimecardSystemDetail timecardDetail = getDetailDate(entity);
				if (timecardDetail != null) {
					if (timecardDetail.getStartHour() != null
							&& timecardDetail.getStartMinute() != null
							&& timecardDetail.getEndHour() != null
							&& timecardDetail.getEndMinute() != null) {
						Integer startHour = timecardDetail.getStartHour();
						Integer startMinute = timecardDetail.getStartMinute();
						Integer endHour = timecardDetail.getEndHour();
						Integer endMinute = timecardDetail.getEndMinute();

						Calendar startCalendar = Calendar.getInstance();
						startCalendar.set(date.getYear(), date.getMonth(), date
								.getDate(), startHour, startMinute);
						Date regulationStartTime = startCalendar.getTime();
						Calendar endCalendar = Calendar.getInstance();
						endCalendar.set(date.getYear(), date.getMonth(), date
								.getDate(), endHour, endMinute);
						Date regulationEndTime = endCalendar.getTime();
						cd.setAllDateOrTime(entity.getClockInTime(), entity
								.getClockOutTime(), regulationStartTime,
								regulationEndTime);
					}
				}

			}
			// 休憩時間
			rest_time = cd.getRestTime();
			// 直接作業時間
			work_time = cd.getWorkTime();
			// 時間外普通
			ordinary_time = cd.getOrdinaryTime();
			// 時間外深夜
			night_time = cd.getNightTime();
			// 時間外法定休日
			legal_holiday_time = cd.getLegalHolidayTime();
			// 時間外休日深夜
			legal_holiday_night_time = cd.getLegalHolidayNightTime();
			// 時 間外法定外休日
			holiday_time = cd.getHolidayTime();
			// 時 間外休日深夜
			holiday_night_time = cd.getHolidayNightTime();
			// 遅刻早退時間
			late_early_time = cd.getLateEarlyTime();
			// 有給休暇（日）
			String paidHolidayType = entity.getPaidHolidayType();
			if (paidHolidayType != null) {
				if (paidHolidayType.equals("1")) {
					paid_leave = "1";
				} else if (paidHolidayType.equals("2")) {
					paid_leave = "0.5";
				} else if (paidHolidayType.equals("3")) {
					paid_leave = "0.5";
				} else {
					paid_leave = " ";
				}
			}

			// 自家用車通 勤 ○ △ ×
			if (entity.getCarCommutingClass() != null) {
				String carCommutingClass = entity.getCarCommutingClass();
				if (carCommutingClass.equals("0")) {
					oneself_car = "×";
				} else if (carCommutingClass.equals("1")) {
					oneself_car = "△";
				} else if (carCommutingClass.equals("2")) {
					oneself_car = "○";
				} else {
					oneself_car = " ";
				}
			}

			// 備考
			if (entity.getRemarks() != null) {
				temp_note = entity.getRemarks();
			}
		}
		// 判決祭
		Integer isOfficeCalendar = isOfficeCalendar(entity);
		isHoliday = isHoliday(isOfficeCalendar).toString();
	}

	// 休日の判断
	public Integer isHoliday(Integer isOfficeCalendar) {
		// 祝日かどうかを検証する．
		int result = 0;
		ALEipHolidaysManager holidaysManager = ALEipHolidaysManager
				.getInstance();
		ALHoliday holiday = holidaysManager.isHoliday(date);
		int day = date.getDay();
		if (day == 0) {
			result = 1;
		}
		if (holiday != null) {
			result = 1;
		}
		if (isOfficeCalendar == 1) {
			result = 2;
		}
		return result;

	}

	/**
	 * 計算時間
	 * 
	 * @param startDate
	 * @param endDate
	 * @param fixStartDate
	 * @param fixEndDate
	 */
	public void CalculateDate(Date startDate, Date endDate, Date fixStartDate,
			Date fixEndDate) {

	}

	public Integer isOfficeCalendar(EipTExtTimecard timecard) {
		int result = 0;
		String officeId = null;
		Date puncheDate = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (dataContext == null) {
			dataContext = DatabaseOrmService.getInstance().getDataContext();
		}
		if (timecard == null) {
			return 0;
		}
		if (timecard.getOfficeId() == null
				|| timecard.getOfficeId().toString().equals("")) {
			return 0;
		} else {
			officeId = timecard.getOfficeId().toString();
		}
		if (timecard.getPunchDate() == null
				|| timecard.getPunchDate().toString().equals("")) {
			return 0;
		} else {
			puncheDate = timecard.getPunchDate();
		}
		try {
			String query = "SELECT * FROM IMW_T_OFFICE_CALENDAR AS C WHERE C.OFFICE_ID="
					+ officeId
					+ " AND CALENDAR_DATE = '"
					+ sdf.format(puncheDate) + "'";
			SQLTemplate rawSelect = new SQLTemplate(ImwTOfficeCalendar.class,
					query, true);
			rawSelect.setFetchingDataRows(true);
			List list = dataContext.performQuery(rawSelect);
			DataRow dataRow;
			String officeCalendarResult;
			if (list != null && list.size() != 0) {
				dataRow = (DataRow) list.get(0);
				officeCalendarResult = (String) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTOfficeCalendar.ON_OFF_CLASS_COLUMN);
				if (officeCalendarResult != null) {
					result = Integer.parseInt(officeCalendarResult);
				}
			}
		} catch (RuntimeException e) {
			// TODO 自動生成された catch ブロック
		}
		return result;
	}

	/**
	 * 勤務形態 その時と終了を開始取得
	 * 
	 * @param entity
	 */

	public ImwTExtTimecardSystemDetail getDetailDate(EipTExtTimecard entity) {
		String systemId = null;
		if (dataContext == null) {
			dataContext = DatabaseOrmService.getInstance().getDataContext();
		}
		if (entity == null) {
			return null;
		}
		if (entity.getSystemId() == null
				|| entity.getSystemId().toString().equals("")) {
			return null;
		} else {
			systemId = entity.getSystemId().toString();
		}
		try {
			String query = "SELECT SD.SYSTEM_DETAIL_ID";
			query += ",SD.SYSTEM_ID";
			query += ",SD.WORKSTART_FLAG";
			query += ",SD.START_HOUR";
			query += ",SD.START_MINUTE";
			query += ",SD.END_HOUR";
			query += ",SD.END_MINUTE";
			query += ",SD.WORKTIME";
			query += ",SD.WORKTIME_STATUS ";
			query += "FROM IMW_T_EXT_TIMECARD_SYSTEM_DETAIL AS SD";
			query += ",EIP_T_EXT_TIMECARD_SYSTEM AS S ";
			query += "WHERE S.SYSTEM_ID =" + systemId + "";
			query += " AND SD.SYSTEM_ID= S.SYSTEM_ID";
			SQLTemplate rawSelect = new SQLTemplate(
					ImwTExtTimecardSystemDetail.class, query, true);
			rawSelect.setFetchingDataRows(true);
			List list = dataContext.performQuery(rawSelect);
			DataRow dataRow;
			if (list != null && list.size() != 0) {
				dataRow = (DataRow) list.get(0);
				ImwTExtTimecardSystemDetail detailEntity = new ImwTExtTimecardSystemDetail();
				detailEntity.setSystemId((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTExtTimecardSystemDetail.SYSTEM_ID_COLUMN));
				/* Update 2010/08/19 seki Start--- */
				/*detailEntity
						.setDetailId((String) ALEipUtils
								.getObjFromDataRow(
										dataRow,
										ImwTExtTimecardSystemDetail.SYSTEM_DETAIL_ID_PK_COLUMN));*/
				detailEntity.setDetailId(ALEipUtils.getObjFromDataRow(dataRow,
						ImwTExtTimecardSystemDetail.SYSTEM_DETAIL_ID_PK_COLUMN)
						.toString());
				/* Update 2010/08/19 seki End--- */
				detailEntity.setStartHour((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTExtTimecardSystemDetail.START_HOUR_COLUMN));

				detailEntity
						.setStartMinute((Integer) ALEipUtils
								.getObjFromDataRow(
										dataRow,
										ImwTExtTimecardSystemDetail.START_MINUTE_COLUMN));

				detailEntity.setEndHour((Integer) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTExtTimecardSystemDetail.END_HOUR_COLUMN));

				detailEntity.setEndMinute((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTExtTimecardSystemDetail.END_MINUTE_COLUMN));

				detailEntity.setWorktime((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTExtTimecardSystemDetail.WORKTIME_COLUMN));

				detailEntity
						.setWorktimeStatus((String) ALEipUtils
								.getObjFromDataRow(
										dataRow,
										ImwTExtTimecardSystemDetail.WORKTIME_STATUS_COLUMN));
				return detailEntity;
			} else {
				return null;
			}
		} catch (RuntimeException e) {
			// TODO 自動生成された catch ブロック
			return null;
		}
	}

	/**
	 * 
	 * 作業内容
	 * 
	 * @param entity
	 */

	public String setProjectContents(EipTExtTimecard entity) {
		String result = "";
		String systemId = null;
		if (dataContext == null) {
			dataContext = DatabaseOrmService.getInstance().getDataContext();
		}
		if (entity == null) {
			return result;
		}
		if (entity.getExtTimecardId() == null
				|| entity.getExtTimecardId().toString().equals("")) {
			return result;
		} else {
			systemId = entity.getExtTimecardId().toString();
		}
		try {
			String query = "SELECT O.JOB_ORDER_NAME FROM IMW_T_EXT_TIMECARD_DETAIL AS D,IMW_T_JOB_ORDER AS O  WHERE D.TIMECARD_ID="
					+ systemId
					+ " AND O.JOB_ORDER_ID=D.JOB_ORDER_ID ORDER BY D.TIMECARD_ID ";
			SQLTemplate rawSelect = new SQLTemplate(ImwTJobOrder.class, query,
					true);
			rawSelect.setFetchingDataRows(true);
			List list = dataContext.performQuery(rawSelect);
			String orderName = null;
			DataRow dataRow;
			if (list != null && list.size() != 0) {
				dataRow = (DataRow) list.get(0);
				orderName = (String) ALEipUtils.getObjFromDataRow(dataRow,
						ImwTJobOrder.JOB_ORDER_NAME_COLUMN);
				result = orderName;
			}

		} catch (RuntimeException e) {
			// TODO 自動生成された catch ブロック
		}
		return result;
	}

	/**
	 * ユーザIDと現在の日付にデータを取得するによると
	 * 
	 * @param userId
	 * @param tempDate
	 * @return
	 */
	public EipTExtTimecard getTxtTimecards(String userId, Date tempDate) {
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		if (dataContext == null) {
			dataContext = DatabaseOrmService.getInstance().getDataContext();
		}
		if (userId == null || tempDate == null) {
			return null;
		}
		try {
			String query = "SELECT * FROM EIP_T_EXT_TIMECARD WHERE USER_ID = "
					+ userId + " AND PUNCH_DATE = '" + s.format(tempDate) + "'";
			SQLTemplate rawSelect = new SQLTemplate(EipTExtTimecard.class,
					query, true);
			rawSelect.setFetchingDataRows(true);
			List list = dataContext.performQuery(rawSelect);
			DataRow dataRow;
			if (list != null && list.size() != 0) {
				dataRow = (DataRow) list.get(0);
				EipTExtTimecard entity = new EipTExtTimecard();
				int a = (Integer) ALEipUtils.getObjFromDataRow(dataRow,
						EipTExtTimecard.TIMECARD_ID_COLUMN);
				entity.setExtTimecardId(ALEipUtils.getObjFromDataRow(dataRow,
						EipTExtTimecard.TIMECARD_ID_COLUMN).toString());
				// ユーザＩＤ
				entity.setUserId((Integer) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.USER_ID_COLUMN));
				// 対象日
				entity.setPunchDate((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.PUNCH_DATE_COLUMN));
				// 種類
				entity.setType((String) ALEipUtils.getObjFromDataRow(dataRow,
						EipTExtTimecard.TYPE_COLUMN));
				// タイムカード勤務形態ＩＤ
				/* Update 2010/08/19 seki Start--- */
				/*
				 * entity.setSystemId((Short)
				 * ALEipUtils.getObjFromDataRow(dataRow,
				 * EipTExtTimecard.SYSTEM_ID_COLUMN));
				 */
				entity.setSystemId((Integer) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.SYSTEM_ID_COLUMN));
				/* Update 2010/08/19 seki End--- */
				// 出勤時刻
				entity.setClockInTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.CLOCK_IN_TIME_COLUMN));
				// 退勤時刻
				entity.setClockOutTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.CLOCK_OUT_TIME_COLUMN));
				// 算出退勤時刻
				entity.setCalClockOutTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.CAL_CLOCK_OUT_TIME_COLUMN));
				// 理由
				entity.setReason((String) ALEipUtils.getObjFromDataRow(dataRow,
						EipTExtTimecard.REASON_COLUMN));
				// 外出時刻１-5 復帰時刻１-5
				entity.setOutgoingTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.OUTGOING_TIME1_COLUMN), 1);
				entity.setComebackTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.COMEBACK_TIME1_COLUMN), 1);
				entity.setOutgoingTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.OUTGOING_TIME2_COLUMN), 2);
				entity.setComebackTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.COMEBACK_TIME2_COLUMN), 2);
				entity.setOutgoingTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.OUTGOING_TIME3_COLUMN), 3);
				entity.setComebackTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.COMEBACK_TIME3_COLUMN), 3);
				entity.setOutgoingTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.OUTGOING_TIME4_COLUMN), 4);
				entity.setComebackTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.COMEBACK_TIME4_COLUMN), 4);
				entity.setOutgoingTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.OUTGOING_TIME5_COLUMN), 5);
				entity.setComebackTime((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.COMEBACK_TIME5_COLUMN), 5);
				// 外出先
				entity.setDestination((String) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.DESTINATION_COLUMN));
				// 自家用車通勤区分
				entity.setCarCommutingClass((String) ALEipUtils
						.getObjFromDataRow(dataRow,
								EipTExtTimecard.CAR_COMMUTING_CLASS_COLUMN));
				// 無効
				entity.setDisabled((String) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.DISABLED_COLUMN));
				// 予定
				entity.setPlan((String) ALEipUtils.getObjFromDataRow(dataRow,
						EipTExtTimecard.PLAN_COLUMN));
				// 注意
				entity.setRemarks((String) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.REMARKS_COLUMN));
				// 勤務先ＩＤ
				entity.setOfficeId((Integer) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.OFFICE_ID_COLUMN));
				// 有給ID1 PAID_HOLIDAY_ID1
				entity.setPaidHolidayId1((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								EipTExtTimecard.PAID_HOLIDAY_ID1_COLUMN));
				// 有給ID2 PAID_HOLIDAY_ID2
				entity.setPaidHolidayId2((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								EipTExtTimecard.PAID_HOLIDAY_ID2_COLUMN));
				// 代休時間（分）
				entity.setOffTime((Integer) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.OFF_TIME_COLUMN));
				// 全休・半休
				entity.setPaidHolidayType((String) ALEipUtils
						.getObjFromDataRow(dataRow,
								EipTExtTimecard.PAID_HOLIDAY_TYPE_COLUMN));
				// 作成日
				entity.setCreateDate((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.CREATE_DATE_COLUMN));
				// 更新日
				entity.setUpdateDate((Date) ALEipUtils.getObjFromDataRow(
						dataRow, EipTExtTimecard.UPDATE_DATE_COLUMN));
				return entity;
			} else {
				return null;
			}
		} catch (RuntimeException e) {
			// TODO 自動生成された catch ブロック
			return null;
		}
	}

	public String getWeek() {
		return week;
	}

	public void setWeek(String week) {
		this.week = week;
	}

	public String getStart_time() {
		return start_time;
	}

	public void setStart_time(String start_time) {
		this.start_time = start_time;
	}

	public String getEnd_time() {
		return end_time;
	}

	public void setEnd_time(String end_time) {
		this.end_time = end_time;
	}

	public String getProject_contents() {
		return project_contents;
	}

	public void setProject_contents(String project_contents) {
		this.project_contents = project_contents;
	}

	public String getRest_time() {
		return rest_time;
	}

	public void setRest_time(String rest_time) {
		this.rest_time = rest_time;
	}

	public String getWork_time() {
		return work_time;
	}

	public void setWork_time(String work_time) {
		this.work_time = work_time;
	}

	public String getOrdinary_time() {
		return ordinary_time;
	}

	public void setOrdinary_time(String ordinary_time) {
		this.ordinary_time = ordinary_time;
	}

	public String getNight_time() {
		return night_time;
	}

	public void setNight_time(String night_time) {
		this.night_time = night_time;
	}

	public String getLegal_holiday_time() {
		return legal_holiday_time;
	}

	public void setLegal_holiday_time(String legal_holiday_time) {
		this.legal_holiday_time = legal_holiday_time;
	}

	public String getLegal_holiday_night_time() {
		return legal_holiday_night_time;
	}

	public void setLegal_holiday_night_time(String legal_holiday_night_time) {
		this.legal_holiday_night_time = legal_holiday_night_time;
	}

	public String getHoliday_time() {
		return holiday_time;
	}

	public void setHoliday_time(String holiday_time) {
		this.holiday_time = holiday_time;
	}

	public String getHoliday_night_time() {
		return holiday_night_time;
	}

	public void setHoliday_night_time(String holiday_night_time) {
		this.holiday_night_time = holiday_night_time;
	}

	public String getLate_early_time() {
		return late_early_time;
	}

	public void setLate_early_time(String late_early_time) {
		this.late_early_time = late_early_time;
	}

	public String getPaid_leave() {
		return paid_leave;
	}

	public void setPaid_leave(String paid_leave) {
		this.paid_leave = paid_leave;
	}

	public String getOneself_car() {
		return oneself_car;
	}

	public void setOneself_car(String oneself_car) {
		this.oneself_car = oneself_car;
	}

	public String getTemp_note() {
		return temp_note;
	}

	public void setTemp_note(String temp_note) {
		this.temp_note = temp_note;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getIsHoliday() {
		return isHoliday;
	}

	public void setIsHoliday(String isHoliday) {
		this.isHoliday = isHoliday;
	}

}
