/*
 * 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.DetailTimeDto;

public class PmDetailPtDao extends PayrollDao {
	
	/**
	 *  テーブル名。<br>
	 */
	public static final String TABLE = "PM_DETAIL_PT";
	
	/**
	 *  主キー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_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 PmDetailPtDao(
			Properties   cfg,
			String       cmd,
			CmAspUserDto aspUser,
			CmUserDto    user,
			Connection   conn
	) {
		super(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果をDTOとして取得する。<br>
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private DetailTimeDto mapping() throws SQLException {
		DetailTimeDto dto = new DetailTimeDto();
		dto.setDetailCode (rs.getString(COL_DETAIL_CODE ));
		dto.setDetailName (rs.getString(COL_DETAIL_NAME ));
		dto.setDetailAbbr (rs.getString(COL_DETAIL_ABBR ));
		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<DetailTimeDto> mappingAll() throws SQLException {
		List<DetailTimeDto> all = new ArrayList<DetailTimeDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<DetailTimeDto> 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 DetailTimeDto findForKey(
			String detailCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, detailCode);
			executeQuery();
			DetailTimeDto 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 DetailTimeDto findForUpdate(
			String detailCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) +
					getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, detailCode);
			executeQuery();
			DetailTimeDto 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<DetailTimeDto> 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<DetailTimeDto> 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<DetailTimeDto> 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_PT);
			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(
			DetailTimeDto 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(
			DetailTimeDto 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(DetailTimeDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getDetailCode ());
		setParam(index++, dto.getDetailName ());
		setParam(index++, dto.getDetailAbbr ());
		setParam(index++, dto.getDisplayType());
		setParam(index++, dto.getExpression ());
		setParam(index++, dto.getInputType  ());
		setParam(index++, dto.getEditFlag   ());
		setParam(index++, dto.getDeleteFlag ());
		setCommonParams(isInsert);
	}
	
}
