/*
 * MosP - Mind Open Source Project    http://www.mosp.jp/
 * Copyright (C) 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.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.Query;

import jp.getset.gae.bigtable.Statement.Mode;
import jp.mosp.common.common.MospException;
import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.dto.CmPaymentMeansDto;

public class CmPaymentMeansDao extends PayrollDao {
	
	// テーブル名及びキー列名
	public static final String	TABLE					= "CM_PAYMENT_MEANS";
	public static final String	KEY_1					= "K_CODE";			// 社員コード
	public static final String	KEY_2					= "MEANS_SEQUENCE";	// 支給方法連番
																				
	// 列名
	public static final String	COL_K_CODE				= "K_CODE";			// 社員コード
	public static final String	COL_MEANS_SEQUENCE		= "MEANS_SEQUENCE";	// 支給方法連番
	public static final String	COL_ALLOWANCE_TYPE		= "ALLOWANCE_TYPE";	// 支給区分
	public static final String	COL_CO_BANK_CODE		= "CO_BANK_CODE";		// 会社銀行コード
	public static final String	COL_PAID_BANK_CODE		= "PAID_BANK_CODE";	// 振込銀行コード
	public static final String	COL_PAID_BRANCH_CODE	= "PAID_BRANCH_CODE";	// 振込銀行支店コード
	public static final String	COL_ACCOUNT_TYPE		= "ACCOUNT_TYPE";		// 預金区分
	public static final String	COL_ACCOUNT_NO			= "ACCOUNT_NO";		// 口座番号
	public static final String	COL_HOLDER_NAME			= "HOLDER_NAME";		// 口座名義
	public static final String	COL_HOLDER_KANA			= "HOLDER_KANA";		// 口座名義ﾌﾘｶﾞﾅ
	public static final String	COL_PAYMENT_MEANS		= "PAYMENT_MEANS";		// 支給方法
	public static final String	COL_AMOUNT_TYPE			= "AMOUNT_TYPE";		// 金額区分
	public static final String	COL_FIXED_AMOUNT		= "FIXED_AMOUNT";		// 固定金額
	public static final String	COL_DELETE_FLAG			= "DELETE_FLAG";		// 削除フラグ
																				
	
	/**
	 * コンストラクタ
	 */
	public CmPaymentMeansDao() {
		super();
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<CmPaymentMeansDto> mappingAll() throws SQLException {
		List<CmPaymentMeansDto> all = new ArrayList<CmPaymentMeansDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return CmPaymentMeansDto レコード
	 * @throws SQLException
	 */
	private CmPaymentMeansDto mapping() throws SQLException {
		CmPaymentMeansDto dto = new CmPaymentMeansDto();
		dto.setKCode(rs.getString(COL_K_CODE)); // 社員コード
		dto.setMeansSequence(rs.getInt(COL_MEANS_SEQUENCE)); // 支給方法連番
		dto.setAllowanceType(rs.getString(COL_ALLOWANCE_TYPE)); // 支給区分
		dto.setCoBankCode(rs.getString(COL_CO_BANK_CODE)); // 会社銀行コード
		dto.setPaidBankCode(rs.getString(COL_PAID_BANK_CODE)); // 振込銀行コード
		dto.setPaidBranchCode(rs.getString(COL_PAID_BRANCH_CODE)); // 振込銀行支店コード
		dto.setAccountType(rs.getString(COL_ACCOUNT_TYPE)); // 預金区分
		dto.setAccountNo(rs.getString(COL_ACCOUNT_NO)); // 口座番号
		dto.setHolderName(rs.getString(COL_HOLDER_NAME)); // 口座名義
		dto.setHolderKana(rs.getString(COL_HOLDER_KANA)); // 口座名義ﾌﾘｶﾞﾅ
		dto.setPaymentMeans(rs.getString(COL_PAYMENT_MEANS)); // 支給方法
		dto.setAmountType(rs.getString(COL_AMOUNT_TYPE)); // 金額区分
		dto.setFixedAmount(rs.getInt(COL_FIXED_AMOUNT)); // 固定金額
		dto.setDeleteFlag(rs.getInt(COL_DELETE_FLAG)); // 削除フラグ
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 検索結果取得(DTOのMap)
	 * @return Map 検索マップ
	 * @throws SQLException
	 */
	private Map<String, List<CmPaymentMeansDto>> mappingAllMap() throws SQLException {
		Map<String, List<CmPaymentMeansDto>> map = new HashMap<String, List<CmPaymentMeansDto>>();
		List<CmPaymentMeansDto> list = mappingAll();
		if (list.size() == 0) {
			return map;
		}
		String currentKCode = list.get(0).getKCode();
		int startIndex = 0;
		for (int i = 1; i < list.size(); i++) {
			if (list.get(i).getKCode().equals(currentKCode)) {
				continue;
			}
			map.put(currentKCode, getSubList(list, startIndex, i - 1));
			startIndex = i;
			currentKCode = list.get(i).getKCode();
		}
		map.put(currentKCode, getSubList(list, startIndex, list.size() - 1));
		return map;
	}
	
	/**
	 * サブリスト取得
	 * @param list      基リスト
	 * @param fromIndex 開始インデックス
	 * @param toIndex   終了インデックス
	 * @return リスト
	 */
	private List<CmPaymentMeansDto> getSubList(List<CmPaymentMeansDto> list, int fromIndex, int toIndex) {
		List<CmPaymentMeansDto> subList = new ArrayList<CmPaymentMeansDto>();
		for (int i = fromIndex; i <= toIndex; i++) {
			if (i >= list.size()) {
				break;
			}
			subList.add(list.get(i));
		}
		return subList;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmPaymentMeansDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<CmPaymentMeansDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @return CmPaymentMeansDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmPaymentMeansDto findForKey(String kCode, int meansSequence) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, kCode);
			setParam(index++, meansSequence);
			executeQuery();
			CmPaymentMeansDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員によるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmPaymentMeansDto> findForEmployee(String kCode) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL);
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, kCode);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員、金額区分によるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmPaymentMeansDto> findForEmployeeAmount(String kCode, String amountType) throws SQLException,
			IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append(" AND ");
			sb.append(COL_AMOUNT_TYPE + " = ? ");
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL);
			this.pob.appendWhere(COL_AMOUNT_TYPE, Query.FilterOperator.EQUAL);
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, kCode);
			setParam(index++, amountType);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員、支給区分によるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmPaymentMeansDto> findForEmployeeAllowance(String kCode, String allowanceType) throws SQLException,
			IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			sb.append(" AND ");
			sb.append(COL_ALLOWANCE_TYPE + " = ? ");
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL);
			this.pob.appendWhere(COL_ALLOWANCE_TYPE, Query.FilterOperator.EQUAL);
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, kCode);
			setParam(index++, allowanceType);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員による行ロック取得
	 * @param kCode 社員コード(検索キー)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmPaymentMeansDto> findForUpdate(String kCode) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL);
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()) + getForUpdate());
			setParam(index++, kCode);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データ挿入
	 * @param dto 挿入対象DTO
	 * @return int 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(CmPaymentMeansDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getInsertQuery(getClass()));
			setParams(dto, true);
			executeUpdate();
			chkInsert(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データ更新
	 * @param dto 更新対象DTO
	 * @return int 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(CmPaymentMeansDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getMeansSequence());
			executeUpdate();
			chkUpdate(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員によるデータ削除
	 * @param kCode 削除対象社員コード
	 * @return int 削除結果(件数)
	 * @throws SQLException
	 */
	public int deleteForEmployee(String kCode) throws SQLException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("DELETE FROM " + TABLE + " ");
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			
			this.setPreparedStatement(Mode.DELETE, TABLE);
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL);
			
			prepareStatement(sb.toString());
			setParam(index++, kCode);
			executeUpdate();
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データ削除
	 * @param dto 更新対象DTO
	 * @return int 削除結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int delete(CmPaymentMeansDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getMeansSequence());
			executeUpdate();
			chkDelete(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(人事情報出力用)
	 * @return Map 検索結果(DTOのListのMap)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 */
	public Map<String, List<CmPaymentMeansDto>> findForHumanData() throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			return mappingAllMap();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * パラメータ設定
	 * @param dto 更新対象DTO
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(CmPaymentMeansDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getKCode()); // 社員コード
		setParam(index++, dto.getMeansSequence()); // 支給方法連番
		setParam(index++, dto.getAllowanceType()); // 支給区分
		setParam(index++, dto.getCoBankCode()); // 会社銀行コード
		setParam(index++, dto.getPaidBankCode()); // 振込銀行コード
		setParam(index++, dto.getPaidBranchCode()); // 振込銀行支店コード
		setParam(index++, dto.getAccountType()); // 預金区分
		setParam(index++, dto.getAccountNo()); // 口座番号
		setParam(index++, dto.getHolderName()); // 口座名義
		setParam(index++, dto.getHolderKana()); // 口座名義ﾌﾘｶﾞﾅ
		setParam(index++, dto.getPaymentMeans()); // 支給方法
		setParam(index++, dto.getAmountType()); // 金額区分
		setParam(index++, dto.getFixedAmount()); // 固定金額
		setParam(index++, dto.getDeleteFlag()); // 削除フラグ
		setCommonParams(isInsert);
	}
}
