/*
 * 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.common.MospException;
import jp.mosp.common.dto.CmAspUserDto;
import jp.mosp.common.dto.CmUserDto;
import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.bonus.dto.PhBounsDto;

public class PhBounsDao extends PayrollDao {
	/**
	 *  テーブル名。<br>
	 */
	public static final String TABLE = "PH_BONUS";
	
	/**
	 *  主キー1。<br>
	 */
	public static final String KEY_01 = "KCODE";
	
	/**
	 *  主キー2。<br>
	 */
	public static final String KEY_02 = "PAY_DATE";
	
	public static final String COL_KCODE           = "KCODE"          ;
	public static final String COL_CALC_MONTH      = "CALC_DATE"     ;
	public static final String COL_PAY_DATE        = "PAY_DATE"       ;
	public static final String COL_SLIP_CODE       = "SLIP_CODE"      ;
	public static final String COL_ALLOWANCE_TOTAL = "ALLOWANCE_TOTAL";
	public static final String COL_DEDUCTION_TOTAL = "DEDUCTION_TOTAL";
	public static final String COL_PAYMENT_TOTAL   = "PAYMENT_TOTAL"  ;
	public static final String COL_TAXATION        = "TAXATION"       ;
	public static final String COL_SOC_INS_TOTAL   = "SOC_INS_TOTAL"  ;
	public static final String COL_DEPENDENT       = "DEPENDENT"      ;
	public static final String COL_INCOME_TAX      = "INCOME_TAX"     ;
	public static final String COL_ADJUSTED_TAX    = "ADJUSTED_TAX"   ;
	public static final String COL_INSURE_MONEY    = "INSURE_MONEY"   ;
	public static final String COL_INSURE_IN_KIND  = "INSURE_IN_KIND" ;
	public static final String COL_INSURE_FIXED    = "INSURE_FIXED"   ;
	public static final String COL_INSURE_UNEMPLOY = "INSURE_UNEMPLOY";
	//public static final String COL_BONUS_BASE      = "BONUS_BASE"     ;
	
	/**
	 * {@link PayrollDao#PayrollDao(Properties, String, CmAspUserDto, CmUserDto, Connection)}
	 * を行う。<br>
	 * @param cfg     設定ファイル
	 * @param cmd     コマンド
	 * @param aspUser ASPユーザー
	 * @param user    ユーザー
	 * @param conn    DBコネクション
	 */
	public PhBounsDao(
			Properties   cfg,
			String       cmd,
			CmAspUserDto aspUser,
			CmUserDto    user,
			Connection   conn
	) {
		super(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果をDTOとして取得する。<br>
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private PhBounsDto mapping() throws SQLException {
		PhBounsDto dto = new PhBounsDto();
		dto.setKCode         (rs.getString(COL_KCODE          ));
		dto.setCalcMonth     (rs.getDate  (COL_CALC_MONTH     ));
		dto.setPayDate       (rs.getDate  (COL_PAY_DATE       ));
		dto.setSlipCode      (rs.getString(COL_SLIP_CODE      ));
		dto.setAllowanceTotal(rs.getInt   (COL_ALLOWANCE_TOTAL));
		dto.setTaxation      (rs.getInt   (COL_TAXATION       ));
		dto.setSocInsTotal   (rs.getInt   (COL_SOC_INS_TOTAL  ));
		dto.setDependent     (rs.getInt   (COL_DEPENDENT      ));
		dto.setIncomeTax     (rs.getInt   (COL_INCOME_TAX     ));
		dto.setAdjustedTax   (rs.getInt   (COL_ADJUSTED_TAX   ));
		dto.setDeductionTotal(rs.getInt   (COL_DEDUCTION_TOTAL));
		dto.setPaymentTotal  (rs.getInt   (COL_PAYMENT_TOTAL  ));
		dto.setInsureMoney   (rs.getInt   (COL_INSURE_MONEY   ));
		dto.setInsureInKind  (rs.getInt   (COL_INSURE_IN_KIND ));
		dto.setInsureFixed   (rs.getInt   (COL_INSURE_FIXED   ));
		dto.setInsureUnemploy(rs.getInt   (COL_INSURE_UNEMPLOY));
		//dto.setBonusBase     (rs.getInt   (COL_BONUS_BASE     ));
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 検索結果をDTOのListとして取得する。<br>
	 * @return 検索結果リスト
	 * @throws SQLException
	 */
	private List<PhBounsDto> mappingAll() throws SQLException {
		List<PhBounsDto> all = new ArrayList<PhBounsDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * キーによりデータを取得する。<br>
	 * @param kCode     社員コード
	 * @param calcMonth 計算年月
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PhBounsDto findForKey(
			String kCode, Date calcMonth
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam    (index++, kCode    );
			setDateParam(index++, calcMonth);
			executeQuery();
			if (rs.next()) {
				return mapping();
			}
			return null;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	
	/**
	 * 支給日によりデータを取得する。<br>
	 * @param kCode     社員コード
	 * @param 支給日
	 * 	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PhBounsDto>  findForPayday(
			Date payday
		) throws SQLException, IllegalAccessException, NoSuchFieldException {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_PAY_DATE);
			sb.append(" = ? ");
			try {
				prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
				setParam(index++, payday);
				executeQuery();
				List< PhBounsDto > list = mappingAll();
				return list;
			} catch (SQLException e) {
				throw e;
			} finally {
				releaseResultSet();
				releasePreparedStatement();
			}
		}

	/**
	 * 計算日によりデータを取得する。<br>
	 * @param 計算日
	 * 	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PhBounsDto>  findForCalcday(
			Date calcday
		) throws SQLException, IllegalAccessException, NoSuchFieldException {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_CALC_MONTH);
			sb.append(" = ? ");
			try {
				prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
				setParam(index++, calcday);
				executeQuery();
				List< PhBounsDto > list = mappingAll();
				return list;
			} catch (SQLException e) {
				throw e;
			} finally {
				releaseResultSet();
				releasePreparedStatement();
			}
		}

	/**
	 * 条件によりデータを取得する。<br>
	 * @param monthFrom   支給年月From
	 * @param monthTo     支給年月To
	 * @param sortKey     ソートキー
	 * @param isAscending 昇順フラグ
	 * @param limit       リミット
	 * @param offset      オフセット
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 */
	public List<PhBounsDto> find(
			String  kCode      ,
			Date    monthFrom  ,
			Date    monthTo    ,
			String  sortKey    ,
			boolean isAscending,
			int     limit      ,
			int     offset
	) throws SQLException, IllegalAccessException {
		try {
			index = 1;
			
			prepareStatement(getSelectStatement(getClass()) +
					getConditionForReferSlip() + getPageStatement(sortKey, isAscending));
			setParam    (index++, kCode    );
			setDateParam(index++, monthFrom);
			setDateParam(index++, monthTo  );
			setParam    (index++, limit    );
			setParam    (index++, offset   );
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文により得られるデータの件数を取得する。<br>
	 * @param kCode     社員コード
	 * @param monthFrom 支給年月From
	 * @param monthTo   支給年月To
	 * @return int 検索結果
	 * @throws SQLException
	 */
	public int count(
			String kCode, Date monthFrom, Date monthTo
	) throws SQLException {
		try {
			index = 1;
			prepareStatement(getSelectCountStatement() + getConditionForReferSlip());
			setParam    (index++, kCode    );
			setDateParam(index++, monthFrom);
			setDateParam(index++, monthTo  );
			executeQuery();
			int count = 0;
			if (rs.next()) {
				count = rs.getInt(1);
			}
			return count;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 給賞与明細参照用条件SQLを取得する。
	 * @return	給与計算用条件SQL 
	 */
	private static String getConditionForReferSlip() {
		StringBuffer sb = new StringBuffer();
		sb.append("FROM " + TABLE + " ");
		sb.append("WHERE ");
		sb.append(COL_KCODE + " = ? ");
		sb.append("AND ");
		sb.append(COL_PAY_DATE + " >= ? ");
		sb.append("AND ");
		sb.append(COL_PAY_DATE + " <= ? ");
		return sb.toString();
	}

	/**
	 * データを挿入する。<br>
	 * @param dto     挿入対象DTO
	 * @param needLog ログ要否フラグ
	 * @return 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(
			PhBounsDto 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(
			PhBounsDto dto, boolean needLog
	) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam    (index++, dto.getKCode    ());
			setDateParam(index++, dto.getCalcMonth());
			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(PhBounsDto dto, boolean isInsert) throws SQLException {
		setParam    (index++, dto.getKCode         ());
		setDateParam(index++, dto.getCalcMonth     ());
		setDateParam(index++, dto.getPayDate       ());
		setParam    (index++, dto.getSlipCode      ());
		setParam    (index++, dto.getAllowanceTotal());
		setParam    (index++, dto.getDeductionTotal());
		setParam    (index++, dto.getPaymentTotal  ());
		setParam    (index++, dto.getTaxation      ());
		setParam    (index++, dto.getSocInsTotal   ());
		setParam    (index++, dto.getDependent     ());
		setParam    (index++, dto.getIncomeTax     ());
		setParam    (index++, dto.getAdjustedTax   ());
		setParam    (index++, dto.getInsureMoney   ());
		setParam    (index++, dto.getInsureInKind  ());
		setParam    (index++, dto.getInsureFixed   ());
		setParam    (index++, dto.getInsureUnemploy());
		//setParam    (index++, dto.getBonusBase     ());
		setCommonParams(isInsert);
	}

	/**
	 * 条件文によるデータ削除
	 * @param calcDate 支給日
	 * 	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 */
	public int deleteForPayday(
			Date payday
	) throws SQLException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("DELETE FROM ");
		sb.append(TABLE + " ");
		sb.append("WHERE ");
		sb.append( COL_PAY_DATE );
		sb.append(" = ? ");
		try {
			prepareStatement(sb.toString());
			setParam(index++, payday);
			executeUpdate();
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 計算日によるデータ削除
	 * @param calcDate 検索計算年月
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 */
	public int deleteForCalcdateAll(
			Date calcMonth
	) throws SQLException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("DELETE FROM ");
		sb.append(TABLE + " ");
		sb.append("WHERE ");
		sb.append( COL_CALC_MONTH );
		sb.append(" = ? ");
		try {
			prepareStatement(sb.toString());
			setParam(index++, calcMonth);
			executeUpdate();
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 計算日月によるデータ削除
	 * @param kCode     社員コード
	 * @param calcDate 検索計算年月
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 */
	public int deleteForCalcdate(
			String kCode, Date calcMonth
	) throws SQLException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("DELETE FROM ");
		sb.append(TABLE + " ");
		sb.append("WHERE ");
		sb.append( COL_KCODE );
		sb.append(" = ? ");
		sb.append("AND ");
		sb.append( COL_CALC_MONTH );
		sb.append(" = ? ");
		try {
			prepareStatement(sb.toString());
			setParam(index++, kCode);
			setParam(index++, calcMonth);
			executeUpdate();
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
}
