package jp.mosp.payroll.bonus.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import jp.mosp.common.common.MospConst;
import jp.mosp.common.common.MospException;
import jp.mosp.common.dto.CmAspUserDto;
import jp.mosp.common.dto.CmUserDto;
import jp.mosp.payroll.base.PayrollConst;
import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.bonus.dto.PmDetailBaDto;
import jp.mosp.payroll.dao.PsSlipDao;

public class PmDetailBaDao extends PayrollDao {
	
	/**
	 *  テーブル名。<br>
	 */
	public static final String	TABLE				= "PM_DETAIL_BA";
	
	/**
	 *  主キー1。<br>
	 */
	public static final String	KEY_01				= "DETAIL_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_ABBR		= "DETAIL_ABBR";
	
	public static final String	COL_TAXATION_TYPE	= "TAXATION_TYPE";
	public static final String	COL_OVERTIME_TYPE	= "OVERTIME_TYPE";
	public static final String	COL_UE_INS_TYPE		= "UE_INS_TYPE";
	public static final String	COL_BONUS_TYPE		= "BONUS_TYPE";
	public static final String	COL_FIXED_TYPE		= "FIXED_TYPE";
	public static final String	COL_SOC_INS_TYPE	= "SOC_INS_TYPE";
	public static final String	COL_MEAL_TYPE		= "MEAL_TYPE";
	public static final String	COL_LEAVE_TYPE		= "LEAVE_TYPE";
	
	public static final String	COL_DISPLAY_TYPE	= "DISPLAY_TYPE";
	public static final String	COL_EXPRESSION		= "EXPRESSION";
	public static final String	COL_INPUT_TYPE		= "INPUT_TYPE";
	public static final String	COL_EDIT_FLAG		= "EDIT_FLAG";
	public static final String	COL_DELETE_FLAG		= "DELETE_FLAG";
	

	/**
	 * {@link PayrollDao#PayrollDao(Properties, String, CmAspUserDto, CmUserDto, Connection)}
	 * を行う。<br>
	 * @param cfg     設定ファイル
	 * @param cmd     コマンド
	 * @param aspUser ASPユーザー
	 * @param user    ユーザー
	 * @param conn    DBコネクション
	 */
	public PmDetailBaDao(Properties cfg, String cmd, CmAspUserDto aspUser, CmUserDto user, Connection conn) {
		super(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果をDTOとして取得する。<br>
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private PmDetailBaDto mapping() throws SQLException {
		PmDetailBaDto dto = new PmDetailBaDto();
		dto.setDetailCode(rs.getString(COL_DETAIL_CODE));
		dto.setDetailName(rs.getString(COL_DETAIL_NAME));
		dto.setDetailAbbr(rs.getString(COL_DETAIL_ABBR));
		dto.setTaxationType(rs.getByte(COL_TAXATION_TYPE));
		dto.setOvertimeType(rs.getByte(COL_OVERTIME_TYPE));
		dto.setUeInsType(rs.getByte(COL_UE_INS_TYPE));
		dto.setBonusType(rs.getByte(COL_BONUS_TYPE));
		dto.setFixedType(rs.getByte(COL_FIXED_TYPE));
		dto.setSocInsType(rs.getByte(COL_SOC_INS_TYPE));
		dto.setMealType(rs.getByte(COL_MEAL_TYPE));
		dto.setLeaveType(rs.getByte(COL_LEAVE_TYPE));
		dto.setDisplayType(rs.getByte(COL_DISPLAY_TYPE));
		dto.setExpression(rs.getString(COL_EXPRESSION));
		dto.setInputType(rs.getByte(COL_INPUT_TYPE));
		dto.setEditFlag(rs.getByte(COL_EDIT_FLAG));
		dto.setDeleteFlag(rs.getByte(COL_DELETE_FLAG));
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 検索結果をDTOのListとして取得する。<br>
	 * @return 検索結果リスト
	 * @throws SQLException
	 */
	private List<PmDetailBaDto> mappingAll() throws SQLException {
		List<PmDetailBaDto> all = new ArrayList<PmDetailBaDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PmDetailBaDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによりデータを取得する。
	 * @param detailCode 明細項目コード(検索キー)
	 * @return dto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PmDetailBaDto findForKey(String detailCode) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, detailCode);
			executeQuery();
			PmDetailBaDto dto = null;
			if (rs.next()) {
				dto = mapping();
				mappingCommonInfo(dto);
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによりデータ及び行ロックを取得する。
	 * @param detailCode 明細項目コード(検索キー)
	 * @return dto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PmDetailBaDto findForUpdate(String detailCode) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, detailCode);
			executeQuery();
			PmDetailBaDto dto = null;
			if (rs.next()) {
				dto = mapping();
				mappingCommonInfo(dto);
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件によりデータを取得する。<br>
	 * @param detailAbbr  明細略称
	 * @param deleteFlag  削除フラグ
	 * @param sortKey     ソートキー
	 * @param isAscending 昇順フラグ
	 * @param limit       リミット
	 * @param offset      オフセット
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PmDetailBaDto> find(String detailAbbr, String deleteFlag, String sortKey, boolean isAscending,
			int limit, int offset) throws SQLException, IllegalAccessException {
		try {
			index = 1;
			prepareStatement(getSelectStatement(getClass()) + getConditionForDetailList(deleteFlag)
					+ getPageStatement(sortKey, isAscending));
			setParam(index++, "%" + detailAbbr + "%");
			if (deleteFlag != null && !deleteFlag.equals("")) {
				setParam(index++, Byte.parseByte(deleteFlag));
			}
			setParam(index++, limit);
			setParam(index++, offset);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文により得られるデータの件数を取得する。<br>
	 * @param detailAbbr 明細略称
	 * @param deleteFlag 削除フラグ
	 * @return int 検索結果
	 * @throws SQLException
	 */
	public int count(String detailAbbr, String deleteFlag) throws SQLException {
		try {
			index = 1;
			prepareStatement(getSelectCountStatement() + getConditionForDetailList(deleteFlag));
			setParam(index++, "%" + detailAbbr + "%");
			if (deleteFlag != null && !deleteFlag.equals("")) {
				setParam(index++, Byte.parseByte(deleteFlag));
			}
			executeQuery();
			int count = 0;
			if (rs.next()) {
				count = rs.getInt(1);
			}
			return count;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 明細設定一覧用条件SQLを取得する。
	 * @param deleteFlag 削除フラグ
	 * @return	給与計算用条件SQL 
	 */
	private static String getConditionForDetailList(String deleteFlag) {
		StringBuffer sb = new StringBuffer();
		sb.append("FROM " + TABLE + " ");
		sb.append("WHERE ");
		sb.append(COL_DETAIL_ABBR + " LIKE ? ");
		if (deleteFlag == null || deleteFlag.equals("")) {
			return sb.toString();
		}
		sb.append("AND ");
		sb.append(COL_DELETE_FLAG + " = ? ");
		return sb.toString();
	}
	
	/**
	 * 条件によりデータを取得する。
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PmDetailBaDto> findNotDelete() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_DELETE_FLAG + " = " + MospConst.DELETE_FLAG_OFF + " ");
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * PS_SLIPに設定されている明細リストを取得する。
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PmDetailBaDto> findForSlip(String slipCode) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectStatement(getClass(), true) + PsSlipDao.getQueryForSlip(getTable(getClass())));
			setParam(index++, slipCode);
			setParam(index++, PayrollConst.DETAIL_TYPE_BA);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データを挿入する。<br>
	 * @param dto     挿入対象DTO
	 * @param needLog ログ要否フラグ
	 * @return 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(PmDetailBaDto dto, boolean needLog) throws SQLException, IllegalAccessException,
			NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getInsertQuery(getClass()));
			setParams(dto, true);
			executeUpdate(needLog);
			chkInsert(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データを更新する。<br>
	 * @param dto 更新対象DTO
	 * @param needLog ログ要否フラグ
	 * @return 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(PmDetailBaDto dto, boolean needLog) throws SQLException, IllegalAccessException,
			NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getDetailCode());
			executeUpdate(needLog);
			chkUpdate(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * パラメータを設定する。<br>
	 * @param dto      更新対象DTO
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(PmDetailBaDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getDetailCode());
		setParam(index++, dto.getDetailName());
		setParam(index++, dto.getDetailAbbr());
		setParam(index++, dto.getTaxationType());
		setParam(index++, dto.getOvertimeType());
		setParam(index++, dto.getUeInsType());
		setParam(index++, dto.getBonusType());
		setParam(index++, dto.getFixedType());
		setParam(index++, dto.getSocInsType());
		setParam(index++, dto.getMealType());
		setParam(index++, dto.getLeaveType());
		setParam(index++, dto.getDisplayType());
		setParam(index++, dto.getExpression());
		setParam(index++, dto.getInputType());
		setParam(index++, dto.getEditFlag());
		setParam(index++, dto.getDeleteFlag());
		setCommonParams(isInsert);
	}
	
}
