package jp.mosp.payroll.bonus.dao;

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

import jp.mosp.payroll.bonus.BonusConst;
import jp.mosp.payroll.bonus.dto.PsDetailDto;

import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.common.common.MospException;

public class PsDetailDao  extends PayrollDao {
	
	// テーブル名及びキー列名
	public static final String TABLE = "US_DETAIL";
	public static final String KEY_1 = "EMPLOYMENT_TYPE";
	public static final String KEY_2 = "POSITION_CODE";
	public static final String KEY_3 = "DETAIL_CODE";
	
	// 列名
	public static final String COL_EMPLOYMENT_TYPE      = "EMPLOYMENT_TYPE"     ; // 雇用区分
	public static final String COL_POSITION_CODE        = "POSITION_CODE"       ; // 職位コード
	public static final String COL_DETAIL_CODE          = "DETAIL_CODE"         ; // 明細コード
	public static final String COL_DETAIL_NAME          = "DETAIL_NAME"         ; // 明細名
	public static final String COL_DETAIL_DISPLAY       = "DETAIL_DISPLAY"      ; // 明細表示方法
	public static final String COL_TAX_OBJECT_TYPE      = "TAX_OBJECT_TYPE"     ; // 課税対象区分
	public static final String COL_TAX_FREE_UPPER_LIMIT = "TAX_FREE_UPPER_LIMIT"; // 非課税上限額
	public static final String COL_SOC_INS_OBJECT_TYPE  = "SOC_INS_OBJECT_TYPE" ; // 社会保険対象区分
	
	/**
	 * コンストラクタ
	 */
	public PsDetailDao() {
		super();
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return PsDetailDto UhBasisレコード
	 * @throws SQLException
	 */
	private PsDetailDto mapping() throws SQLException {
		PsDetailDto dto = new PsDetailDto();
		dto.setEmploymentType   (rs.getString(COL_EMPLOYMENT_TYPE     )); // 雇用区分
		dto.setPositonCode      (rs.getString(COL_POSITION_CODE       )); // 職位コード
		dto.setDetailCode       (rs.getString(COL_DETAIL_CODE         )); // 明細コード
		dto.setDetailName       (rs.getString(COL_DETAIL_NAME         )); // 明細名
		dto.setDetailDisplay    (rs.getString(COL_DETAIL_DISPLAY      )); // 明細表示方法
		dto.setTaxObjectType    (rs.getString(COL_TAX_OBJECT_TYPE     )); // 課税対象区分
		dto.setTaxFreeUpperLimit(rs.getInt   (COL_TAX_FREE_UPPER_LIMIT)); // 非課税上限額
		dto.setSocInsObjectType (rs.getString(COL_SOC_INS_OBJECT_TYPE )); // 社会保険対象区分

		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<PsDetailDto> mappingAll() throws SQLException {
		List<PsDetailDto> all = new ArrayList<PsDetailDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTOのMapのMap)
	 * @return Map 検索マップ
	 * @throws SQLException
	 */
	private Map<String, Map<String, PsDetailDto>> mappingAllMap(
	) throws SQLException {
		Map<String, Map<String, PsDetailDto>> map =
				new HashMap<String, Map<String, PsDetailDto>>();
		Map<String, PsDetailDto> subMap = new HashMap<String, PsDetailDto>();
		String current = null;
		while (rs.next()) {
			// DTO取得
			PsDetailDto dto = mapping();
			// キー設定
			String key = dto.getEmploymentType() +
					BonusConst.KEY_SEPARATOR + dto.getPositionCode();
			// 初回判定
			if (current == null) {
				current = key;
			}
			// キーが変わった場合
			if (!key.equals(current)) {
				map.put(current, subMap);
				current = key;
				subMap = new HashMap<String, PsDetailDto>();
			}
			subMap.put(dto.getDetailCode(), dto);
		}
		if (current != null) {
			map.put(current, subMap);
		}
		return map;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PsDetailDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<PsDetailDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 全データ取得
	 * @return Map 検索結果(DTOのMapのMap)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public Map<String, Map<String, PsDetailDto>> findAllAsMap(
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			return mappingAllMap();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 賞与明細データ取得
	 * @return Map 検索結果(DTOのMapのMap)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public Map<String, Map<String, PsDetailDto>> findBonusAsMap(
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_DETAIL_CODE + " like ? ");
			sb.append("AND ");
			sb.append(COL_DETAIL_CODE + " IS NOT NULL ");
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, BonusConst.BONUS_DETAIL + "%");
			executeQuery();
			return mappingAllMap();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param employmentType 雇用区分(検索キー)
 	 * @param positionCode   職位コード(検索キー)
	 * @param detailCode     明細区分(検索キー)
	 * @return PsDetailDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PsDetailDto findForKey(
			String  employmentType,String  positionCode, String detailCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, employmentType);
			setParam(index++, positionCode);
			setParam(index++, detailCode);
			executeQuery();
			PsDetailDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得
	 * @param employmentType   検索雇用区分
	 * @param detailCode       検索明細区分
	 * @param taxObjectType    検索課税対象区分
	 * @param SocInsObjectType 検索社会保険対象区分
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PsDetailDto> findForCondition(
			String employmentType,
			String positionCode,
			String detailCode,
			String taxObjectType,
			String socInsObjectType
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		if ( !employmentType.equals ("") ||
			 !positionCode.equals   ("") ||
			 !detailCode.equals      ("")||
			 !taxObjectType.equals   ("")||
			 !socInsObjectType.equals("")
		 ){
			  sb.append(" WHERE ");
		}		
		if ( !employmentType.equals("") ){
			sb.append(COL_EMPLOYMENT_TYPE);
			sb.append(" = ?  ");
			if (
     		 !positionCode.equals   ("") ||
				!detailCode.equals      ("")||
				!taxObjectType.equals   ("")||
				!socInsObjectType.equals("")
			){
				sb.append(" AND  ");
			}
		}
		if ( !positionCode.equals("") ){
			sb.append(COL_POSITION_CODE);
			sb.append(" = ?  ");
			if (
				!detailCode.equals      ("")||
				!taxObjectType.equals   ("")||
				!socInsObjectType.equals("")
			){
				sb.append(" AND  ");
			}
		}
		if (!detailCode.equals("")){
			sb.append(COL_DETAIL_CODE);
			sb.append("  = ?  ");
			if (
				!taxObjectType.equals   ("")||
				!socInsObjectType.equals("")
			){
				sb.append(" AND  ");
			}
		}
		if (!taxObjectType.equals   ("")){
			sb.append(COL_TAX_OBJECT_TYPE);
			sb.append("  = ?  ");
			if (!socInsObjectType.equals("")){
				sb.append(" AND  ");
			}
		}
		if (!socInsObjectType.equals("")){
			sb.append(COL_SOC_INS_OBJECT_TYPE);
			sb.append("  = ?  ");
		}
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			if (!employmentType.equals("")){
				setParam(index++,   employmentType   );
			}
			if (!positionCode.equals("")){
				setParam(index++,   positionCode   );
			}
			if (!detailCode.equals("")){
				setParam(index++,   detailCode       );
			}
			if (!taxObjectType.equals("")){
				setParam(index++,   taxObjectType    );
			}
			if (!socInsObjectType.equals("")){
				setParam(index++,   socInsObjectType );
			}
			executeQuery();
			List<PsDetailDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 雇用区分によるデータ取得
	 * @param employmentType 雇用区分(検索キー)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PsDetailDto> findForEmployeeAll(
			String employmentType
	) throws SQLException, NoSuchFieldException, IllegalAccessException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_EMPLOYMENT_TYPE + " = ? ");
			sb.append("AND ");
			sb.append(COL_DETAIL_CODE + " IS NOT NULL ");
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, employmentType);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによる行ロック取得
	 * @param employmentType 雇用区分(検索キー)
	 * @param positionCode   職位コード(検索キー)
	 * @param detailCode     明細区分(検索キー)
	 * @return PsDetailDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PsDetailDto findForUpdate(
			String employmentType,
			String positionCode,
			String   detailCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, employmentType);
			setParam(index++, positionCode);
			setParam(index++, detailCode);
			executeQuery();
			PsDetailDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	
	/**
	 * データ挿入
	 * @param dto 挿入対象DTO
	 * @return int 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(PsDetailDto 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(PsDetailDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getEmploymentType());
			setParam(index++, dto.getPositionCode());
			setParam(index++, dto.getDetailCode());
			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(PsDetailDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getEmploymentType());
			setParam(index++, dto.getPositionCode());
			setParam(index++, dto.getDetailCode());
			executeUpdate();
			chkDelete(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * パラメータ設定
	 * @param dto 更新対象DTO
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(PsDetailDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getEmploymentType   ()); // 雇用区分
		setParam(index++, dto.getPositionCode     ()); // 職位コード
		setParam(index++, dto.getDetailCode       ()); // 明細コード
		setParam(index++, dto.getDetailName       ()); // 明細名
		setParam(index++, dto.getDetailDisplay    ()); // 明細表示方法
		setParam(index++, dto.getTaxObjectType    ()); // 課税対象区分
		setParam(index++, dto.getTaxFreeUpperLimit()); // 非課税上限額
		setParam(index++, dto.getSocInsObjectType ()); // 社会保険対象区分

		setCommonParams(isInsert);
	}
}
