/*
 * MosP - Mind Open Source Project         http://www.mosp.jp/
 * Copyright (C) 1987-2009 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 General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package jp.mosp.payroll.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.dto.DetailPaDto;

public class PmDetailPaDao extends PayrollDao {
	
	/**
	 *  テーブル名。<br>
	 */
	public static final String TABLE = "PM_DETAIL_PA";
	
	/**
	 *  主キー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 PmDetailPaDao(
			Properties   cfg,
			String       cmd,
			CmAspUserDto aspUser,
			CmUserDto    user,
			Connection   conn
	) {
		super(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果をDTOとして取得する。<br>
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private DetailPaDto mapping() throws SQLException {
		DetailPaDto dto = new DetailPaDto();
		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<DetailPaDto> mappingAll() throws SQLException {
		List<DetailPaDto> all = new ArrayList<DetailPaDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<DetailPaDto> 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 DetailPaDto findForKey(
			String detailCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, detailCode);
			executeQuery();
			DetailPaDto 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 DetailPaDto findForUpdate(
			String detailCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) +
					getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, detailCode);
			executeQuery();
			DetailPaDto 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<DetailPaDto> 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<DetailPaDto> 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<DetailPaDto> 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_PA);
			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(
			DetailPaDto 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(
			DetailPaDto 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(DetailPaDto 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);
	}
	
}
