package jp.mosp.payroll.bonus.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.bonus.dto.PhIndividualDto;
import jp.mosp.common.common.MospException;

public class PhIndividualDao extends PayrollDao {
	
	// テーブル名及びキー列名
	public static final String TABLE = "UH_INDIVIDUAL";
	public static final String KEY_1 = "K_CODE"       ;	// 社員コード
	public static final String KEY_2 = "EXPECTED_DATE";	// 適用予定日
	
	// 列名
	public static final String COL_K_CODE             = "K_CODE"            ;	// 社員コード
	public static final String COL_EXPECTED_DATE      = "EXPECTED_DATE"     ;	// 適用予定日
	public static final String COL_APPLIED_DATE       = "APPLIED_DATE"      ;	// 適用日
	public static final String COL_BUSINESS_TYPE      = "BUSINESS_TYPE"     ;	// 事業区分
	public static final String COL_CALENDAR_TYPE      = "CALENDAR_TYPE"     ;	// カレンダー区分
	public static final String COL_EFFORT_TYPE        = "EFFORT_TYPE"       ;	// 成果率区分
	public static final String COL_GRADE              = "GRADE"             ;	// 号数
	public static final String COL_NOTCH              = "NOTCH"             ;	// 等級
	public static final String COL_BASIC_SALARY       = "BASIC_SALARY"      ;	// 基本給
	public static final String COL_ABILITY_ALLOWANCE  = "ABILITY_ALLOWANCE" ;	// 職能手当
	public static final String COL_ABILITY_ALLOWANCE2 = "ABILITY_ALLOWANCE2";	// 職能手当2
	public static final String COL_PAYMENT_TYPE       = "PAYMENT_TYPE"      ;	// 支払区分
	public static final String COL_OVERTIME_TYPE      = "OVERTIME_TYPE"     ;	// 残業区分
	public static final String COL_PAID_HOLIDAY_TYPE  = "PAID_HOLIDAY_TYPE" ;	// 有給区分
	public static final String COL_PAID_HOLIDAY_MONTH = "PAID_HOLIDAY_MONTH";	// 有給休暇起算月
	
	/**
	 * コンストラクタ
	 */
	public PhIndividualDao() {
		super();
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<PhIndividualDto> mappingAll() throws SQLException {
		List<PhIndividualDto> all = new ArrayList<PhIndividualDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTOのMap)
	 * @return Map 検索マップ
	 * @throws SQLException
	 */
	private Map<String, PhIndividualDto> mappingAllMap() throws SQLException {
		Map<String, PhIndividualDto> all = new HashMap<String, PhIndividualDto>();
		while (rs.next()) {
			PhIndividualDto dto = mapping();
			all.put(dto.getKCode(), dto);
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return PhIndividualDto UH_INDIVIDUALレコード
	 * @throws SQLException
	 */
	private PhIndividualDto mapping() throws SQLException {
		PhIndividualDto dto = new PhIndividualDto();
		dto.setKCode            (rs.getString(COL_K_CODE            ));	// 社員コード
		dto.setExpectedDate     (rs.getDate  (COL_EXPECTED_DATE     ));	// 適用予定日
		dto.setAppliedDate      (rs.getDate  (COL_APPLIED_DATE      ));	// 適用日
		dto.setBusinessType     (rs.getString(COL_BUSINESS_TYPE     ));	// 事業区分
		dto.setCalendarType     (rs.getString(COL_CALENDAR_TYPE     ));	// カレンダー区分
		dto.setEffortType       (rs.getString(COL_EFFORT_TYPE       ));	// 成果率区分
		dto.setGrade            (rs.getInt   (COL_GRADE             ));	// 号数
		dto.setNotch            (rs.getInt   (COL_NOTCH             ));	// 等級
		dto.setBasicSalary      (rs.getInt   (COL_BASIC_SALARY      ));	// 基本給
		dto.setAbilityAllowance (rs.getInt   (COL_ABILITY_ALLOWANCE ));	// 職能手当
		dto.setAbilityAllowance2(rs.getInt   (COL_ABILITY_ALLOWANCE2));	// 職能手当2
		dto.setPaymentType      (rs.getString(COL_PAYMENT_TYPE      ));	// 支払区分
		dto.setOvertimeType     (rs.getString(COL_OVERTIME_TYPE     ));	// 残業区分
		dto.setPaidHolidayType  (rs.getString(COL_PAID_HOLIDAY_TYPE ));	// 有給区分
		dto.setPaidHolidayMonth (rs.getDate  (COL_PAID_HOLIDAY_MONTH));	// 有給休暇起算月
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PhIndividualDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<PhIndividualDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @param expectedDate 適用予定日(検索キー)
	 * @return PhIndividualDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PhIndividualDto findForKey(
			String  kCode,
			Date    expectedDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, kCode);
			setParam(index++, expectedDate);
			executeQuery();
			PhIndividualDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 年月によるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @param expectedDate 適用年月(検索キー)
	 * @return PhIndividualDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PhIndividualDto findForDate(
			String  kCode, Date expectedDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append("AND ");
			sb.append(COL_EXPECTED_DATE + " = (");
			sb.append("SELECT MAX(" + COL_EXPECTED_DATE + ") ");
			sb.append("FROM " + TABLE + " ");
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append("AND ");
			sb.append(COL_EXPECTED_DATE + " <= ? ");
			sb.append("AND ");
			sb.append(COL_APPLIED_DATE + " IS NOT NULL ");
			sb.append(")");
			prepareStatement(getSelectQuery(getClass()) + sb.toString());
			setParam(index++, kCode);
			setParam(index++, kCode);
			setParam(index++, expectedDate);
			executeQuery();
			PhIndividualDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員コードによるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @return PhIndividualDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PhIndividualDto> findForEmployeeAll(
			String  kCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append("AND ");
			sb.append(COL_APPLIED_DATE + " IS NOT NULL ");
			prepareStatement(
					getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, kCode);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員コードによるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @return PhIndividualDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PhIndividualDto findForEmployee(
			String  kCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append("AND ");
			sb.append(COL_EXPECTED_DATE + " = (");
			sb.append("SELECT MAX(" + COL_EXPECTED_DATE + ") ");
			sb.append("FROM " + TABLE + " ");
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append("AND ");
			sb.append(COL_APPLIED_DATE + " IS NOT NULL ");
			sb.append(")");
			prepareStatement(getSelectQuery(getClass()) + sb.toString());
			setParam(index++, kCode);
			setParam(index++, kCode);
			executeQuery();
			PhIndividualDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによる行ロック取得
	 * @param kCode 社員コード(検索キー)
	 * @param expectedDate 適用予定日(検索キー)
	 * @return PhIndividualDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PhIndividualDto findForUpdate(
			String kCode,
			Date expectedDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, kCode);
			setParam(index++, expectedDate);
			executeQuery();
			PhIndividualDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得
	 * @param kCode 検索社員コード
	 * @param expectedDate 検索適用予定日
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PhIndividualDto> findForCondition(
			String kCode,
			String expectedDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_K_CODE);
		sb.append(" LIKE ? AND ");
		sb.append(COL_EXPECTED_DATE);
		sb.append(" LIKE ? AND ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, kCode             );
			setParam(index++, expectedDate + "%");
			executeQuery();
			List<PhIndividualDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(人事情報出力用)
	 * @param endDate 集計月終了日
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public Map<String, PhIndividualDto> findForHumanData(
			Date endDate
	) throws SQLException, IllegalAccessException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("FROM ");
			sb.append(getHistoryTable());
			prepareStatement(getSelectStatement(getClass()) + sb.toString());
			setParam(index++, endDate);
			executeQuery();
			return mappingAllMap();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 履歴データSQL取得
	 * @return 履歴データ取得SQL文字列
	 * @throws IllegalAccessException 
	 */
	private String getHistoryTable() throws IllegalAccessException {
		StringBuffer sb = new StringBuffer();
		sb.append("(");
		sb.append(getSelectStatement(getClass()));
		sb.append("FROM ");
		sb.append(TABLE + ", ");
		sb.append("(");
		sb.append(	"SELECT ");
		sb.append(	COL_K_CODE + " AS H_K_CODE, ");
		sb.append(	"MAX(" + COL_EXPECTED_DATE + ") AS H_EXPECTED_DATE " );
		sb.append(	"FROM " + TABLE + " ");
		sb.append(	"WHERE ");
		sb.append(	COL_EXPECTED_DATE + " <= ? ");
		sb.append(	"AND ");
		sb.append(	COL_APPLIED_DATE + " IS NOT NULL ");
		sb.append(	"GROUP BY " + COL_K_CODE + " ");
		sb.append(") HISTORY ");
		sb.append("WHERE ");
		sb.append(COL_K_CODE + " = HISTORY.H_K_CODE ");
		sb.append("AND ");
		sb.append(COL_EXPECTED_DATE + " = HISTORY.H_EXPECTED_DATE");
		sb.append(") " + TABLE +" ");
		return sb.toString();
	}
	
	/**
	 * 社員コードによる未適用データ取得
	 * @param kCode       社員コード(検索キー)
	 * @param isForUpdate UPDATE用フラグ
	 * @return PhIndividualDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PhIndividualDto findForEmployeeNotApplied(
			String  kCode,
			boolean isForUpdate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append("AND ");
			sb.append(COL_APPLIED_DATE  + " IS NULL ");
			if (isForUpdate) {
				sb.append(getForUpdate());
			}
			prepareStatement(getSelectQuery(getClass()) + sb.toString());
			setParam(index++, kCode);
			executeQuery();
			PhIndividualDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員コードによる未適用データ削除
	 * @param expectedDate 適用予定日
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 */
	public int deleteNotApplied(String kCode) throws SQLException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("DELETE FROM " + TABLE + " ");
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append("AND ");
			sb.append(COL_APPLIED_DATE + " IS NULL ");
			prepareStatement(sb.toString());
			setParam(index++, kCode);
			executeUpdate();
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * データ挿入
	 * @param dto 挿入対象DTO
	 * @return int 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(PhIndividualDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getInsertQuery(getClass()));
			setParams(dto, true);
			executeUpdate();
			chkInsert(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	
	/**
	 * データ更新
	 * @param dto 更新対象DTO
	 * @return int 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(PhIndividualDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getExpectedDate());
			executeUpdate();
			chkUpdate(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データ削除
	 * @param dto 更新対象DTO
	 * @return int 削除結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int delete(PhIndividualDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getExpectedDate());
			executeUpdate();
			chkDelete(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員によるデータ削除
	 * @param kCode 削除対象社員コード
	 * @return int 削除結果(件数)
	 * @throws SQLException
	 */
	public int deleteForEmployee(String kCode) throws SQLException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("DELETE FROM " + TABLE + " ");
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			prepareStatement(sb.toString());
			setParam(index++, kCode);
			executeUpdate();
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(人事追加情報出力用)
	 * @param kCode          検索社員コード
	 * @param kName          検索社員名
	 * @param kKana          検索ﾌﾘｶﾞﾅ
	 * @param stationCode    検索所属コード
	 * @param positionCode   検索職位コード
	 * @param retirementFlag 検索退職フラグ
	 * @param startDate      検索開始日
	 * @param endDate        検索終了日
	 * @return UhLicenseTypeDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PhIndividualDto> findForConditionList(
			String kCode,
			String kName,
			String kKana,
			String stationCode,
			String positionCode,
			String retirementFlag,
			Date startDate,
			Date endDate
	) throws SQLException, IllegalAccessException {
		try {
			PmBasisDao pmBasisDao  = new PmBasisDao();
			StringBuffer sb = new StringBuffer();
			index = 1;
			sb.append(getSelectStatement(getClass()) + " ");
			sb.append("FROM ");
			sb.append(TABLE);
			sb.append(" WHERE ");
			sb.append(COL_K_CODE + " IN  ");
			sb.append(" ( ");
			sb.append(pmBasisDao.getForAddHumanListSubQuery(stationCode, positionCode, retirementFlag));
			sb.append(" ) ");
			sb.append(" AND ");
			sb.append(COL_EXPECTED_DATE + " >= ? ");
			sb.append(" AND ");
			sb.append(COL_EXPECTED_DATE + " <= ? ");
			prepareStatement(sb.toString());
			setParam(index++, kCode + "%");
			setParam(index++, "%" + kName + "%");
			setParam(index++, "%" + kKana + "%");
			if (stationCode != null && !stationCode.equals("")) {
				setParam(index++, stationCode);
			}
			if (positionCode != null && !positionCode.equals("")) {
				setParam(index++, positionCode);
			}
			setParam(index++, startDate);
			setParam(index++, endDate);
			executeQuery();
			List<PhIndividualDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * パラメータ設定
	 * @param dto 更新対象DTO
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(PhIndividualDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getKCode())            ;	// 社員コード
		setParam(index++, dto.getExpectedDate())     ;	// 適用予定日
		setParam(index++, dto.getAppliedDate())      ;	// 適用日
		setParam(index++, dto.getBusinessType())     ;	// 事業区分
		setParam(index++, dto.getCalendarType())     ;	// カレンダー区分
		setParam(index++, dto.getEffortType())       ;	// 成果率区分
		setParam(index++, dto.getGrade())            ;	// 号数
		setParam(index++, dto.getNotch())            ;	// 等級
		setParam(index++, dto.getBasicSalary())      ;	// 基本給
		setParam(index++, dto.getAbilityAllowance ());	// 職能手当
		setParam(index++, dto.getAbilityAllowance2());	// 職能手当2
		setParam(index++, dto.getPaymentType())      ;	// 支払区分
		setParam(index++, dto.getOvertimeType())     ;	// 残業区分
		setParam(index++, dto.getPaidHolidayType())  ;	// 有給区分
		setParam(index++, dto.getPaidHolidayMonth ());	// 有給休暇起算月
		setCommonParams(isInsert);
	}

}
