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

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

import jp.mosp.common.dto.CmAspUserDto;
import jp.mosp.common.dto.CmUserDto;
import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.bonus.dto.PmDetailBsDto;
import jp.mosp.payroll.dto.DetailMoneyDto;

/**
 * 各種明細テーブルを操作をする機能を提供する。<br><br>
 * {@link DetailMoneyDto}を用いて、DBとJavaプログラム間でレコードを共有する。<br>
 */
public class DetailMoneyDao extends PayrollDao {
	/**
	 *  主キー1。<br>
	 */
	public static final String KEY_01 = "KCODE";
	
	/**
	 *  主キー2。<br>
	 */
	public static final String KEY_02 = "CALC_DATE";
	
	/**
	 *  主キー3。<br>
	 */
	public static final String KEY_03 = "DETAIL_CODE";
	
	public static final String COL_KCODE         = "KCODE"      ;
	public static final String COL_CALC_DATE     = "CALC_DATE"  ;
	public static final String COL_DETAIL_CODE   = "DETAIL_CODE";
	public static final String COL_AMOUNT        = "AMOUNT"     ;
	
	/**
	 * {@link PayrollDao#PayrollDao(Properties, String, CmAspUserDto, CmUserDto, Connection)}
	 * を行う。<br>
	 * @param cfg     設定ファイル
	 * @param cmd     コマンド
	 * @param aspUser ASPユーザー
	 * @param user    ユーザー
	 * @param conn    DBコネクション
	 */
	public DetailMoneyDao(
			Properties   cfg,
			String       cmd,
			CmAspUserDto aspUser,
			CmUserDto    user,
			Connection   conn
	) {
		super(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果をDTOとして取得する。<br>
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private PmDetailBsDto mapping() throws SQLException {
		PmDetailBsDto dto = new PmDetailBsDto();
		dto.setKCode     (rs.getString(COL_KCODE       ));
		dto.setCalcDate  (rs.getDate  (COL_CALC_DATE   ));
		dto.setDetailCode(rs.getString(COL_DETAIL_CODE ));
		dto.setAmount    (rs.getInt   (COL_AMOUNT      ));
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 検索結果をDTOのListとして取得する。<br>
	 * @return 検索結果リスト
	 * @throws SQLException
	 */
	private List<PmDetailBsDto> mappingAll() throws SQLException {
		List<PmDetailBsDto> all = new ArrayList<PmDetailBsDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 条件によりデータを取得する。<br>
	 * @param kCode     社員コード
	 * @param calcDate 計算年月
	 * @return 検索結果(DTOのList)
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws NoSuchFieldException 
	 */
	public List<PmDetailBsDto> find(
			String kCode, Date calcDate
	) throws SQLException, NoSuchFieldException, IllegalAccessException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_KCODE + " = ? ");
		sb.append("AND ");
		sb.append(COL_CALC_DATE + " = ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString());
			setParam    (index++, kCode    );
			setDateParam(index++, calcDate);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データを挿入する。<br>
	 * @param list 挿入対象リスト
	 * @return int 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 */
	public int insert(
			List<?> list
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			if (list == null || list.size() == 0) {
				return 0;
			}
			int count = 0;
			int max = 3;	// 一度に更新するレコードの最大値
			// 挿入準備
			index = 1;
			prepareStatement(getInsertQuery(getClass(), list.size(), max));
			for (int i = 0; i < list.size(); i++) {
				setParams((PmDetailBsDto)list.get(i), true);
				executeUpdate(getClass(), list.size(), max, i);
				count += cnt;
			}
			return count;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件により削除を行う。
	 * @param calcDate 計算年月
	 * @return 削除結果(件数)
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws NoSuchFieldException 
	 */
	public int delete(
			Date calcDate
	) throws SQLException, NoSuchFieldException, IllegalAccessException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("DELETE FROM " + getTable(getClass()) + " ");
		sb.append("WHERE ");
		sb.append(COL_CALC_DATE + " = ? ");
		try {
			prepareStatement(sb.toString());
			setDateParam(index++, calcDate);
			executeUpdate(false);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件により削除を行う。
	 * @param kCode    社員コード
	 * @param calcDate 計算年月
	 * @return 削除結果(件数)
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws NoSuchFieldException 
	 */
	public int delete(
			String kCode, Date calcDate
	) throws SQLException, NoSuchFieldException, IllegalAccessException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("DELETE FROM " + getTable(getClass()) + " ");
		sb.append("WHERE ");
		sb.append(COL_KCODE + " = ? ");
		sb.append("AND ");
		sb.append(COL_CALC_DATE + " = ? ");
		try {
			prepareStatement(sb.toString());
			setParam    (index++, kCode    );
			setDateParam(index++, calcDate);
			executeUpdate(false);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * パラメータを設定する。<br>
	 * @param dto      更新対象DTO
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(PmDetailBsDto dto, boolean isInsert) throws SQLException {
		setParam    (index++, dto.getKCode     ());
		setDateParam(index++, dto.getCalcDate  ());
		setParam    (index++, dto.getDetailCode());
		setParam    (index++, dto.getAmount    ());
		setCommonParams(isInsert);
	}

}
