package jp.mosp.payroll.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.dto.PhPaymentDto;

public class PhPaymentDao extends PayrollDao {
	
	/**
	 *  テーブル名。<br>
	 */
	public static final String	TABLE				= "PH_PAYMENT";
	
	/**
	 *  主キー1。<br>
	 */
	public static final String	KEY_01				= "KCODE";
	
	/**
	 *  主キー2。<br>
	 */
	public static final String	KEY_02				= "CALC_MONTH";
	
	public static final String	COL_KCODE			= "KCODE";
	public static final String	COL_CALC_MONTH		= "CALC_MONTH";
	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 PhPaymentDao(Properties cfg, String cmd, CmAspUserDto aspUser, CmUserDto user, Connection conn) {
		super(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果をDTOとして取得する。<br>
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private PhPaymentDto mapping() throws SQLException {
		PhPaymentDto dto = new PhPaymentDto();
		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<PhPaymentDto> mappingAll() throws SQLException {
		List<PhPaymentDto> all = new ArrayList<PhPaymentDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * キーによりデータを取得する。<br>
	 * @param kCode     社員コード
	 * @param calcMonth 計算年月
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PhPaymentDto 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 calcMonth 計算年月
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 */
	public List<PhPaymentDto> find(Date calcMonth) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_CALC_MONTH + " = ? ");
			prepareStatement(getSelectQuery(getClass()) + sb.toString());
			setDateParam(index++, calcMonth);
			executeQuery();
			return mappingAll();
		} 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<PhPaymentDto> 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(PhPaymentDto 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(PhPaymentDto 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(PhPaymentDto 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 startDate 対象開始年月
	 * @param endDate 対象終了年月
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PhPaymentDto> findForConditionDate(String kCode, Date startDate, Date endDate) throws SQLException,
			IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_KCODE);
		sb.append(" = ? ");
		sb.append(" AND ");
		sb.append(COL_CALC_MONTH);
		sb.append(" >= ? ");
		sb.append(" AND ");
		sb.append(COL_CALC_MONTH);
		sb.append(" <= ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, kCode);
			setParam(index++, startDate);
			setParam(index++, endDate);
			executeQuery();
			List<PhPaymentDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
}
