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 jp.mosp.common.common.MospException;
import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.dto.CmUnitAmountDto;

public class CmUnitAmountDao extends PayrollDao {
	
	// テーブル名及びキー列名
	public static final String	TABLE			= "CM_UNIT_AMOUNT";
	public static final String	KEY_1			= "K_CODE";		// 社員コード
	public static final String	KEY_2			= "UNIT_TYPE";		// 計算単価区分
																	
	// 列名
	public static final String	COL_K_CODE		= "K_CODE";		// 社員コード
	public static final String	COL_UNIT_TYPE	= "UNIT_TYPE";		// 計算単価区分
	public static final String	COL_UNIT_AMOUNT	= "UNIT_AMOUNT";	// 計算単価
																	
	
	/**
	 * コンストラクタ
	 */
	public CmUnitAmountDao() {
		super();
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<CmUnitAmountDto> mappingAll() throws SQLException {
		List<CmUnitAmountDto> all = new ArrayList<CmUnitAmountDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return CmUnitAmountDto レコード
	 * @throws SQLException
	 */
	private CmUnitAmountDto mapping() throws SQLException {
		CmUnitAmountDto dto = new CmUnitAmountDto();
		dto.setKCode(rs.getString(COL_K_CODE)); // 社員コード
		dto.setUnitType(rs.getString(COL_UNIT_TYPE)); // 計算単価区分
		dto.setUnitAmount(rs.getDouble(COL_UNIT_AMOUNT)); // 計算単価
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 検索結果取得(DTOのMap)
	 * @return Map 検索マップ
	 * @throws SQLException
	 */
	private Map<String, List<CmUnitAmountDto>> mappingAllMap() throws SQLException {
		Map<String, List<CmUnitAmountDto>> map = new HashMap<String, List<CmUnitAmountDto>>();
		List<CmUnitAmountDto> 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<CmUnitAmountDto> getSubList(List<CmUnitAmountDto> list, int fromIndex, int toIndex) {
		List<CmUnitAmountDto> subList = new ArrayList<CmUnitAmountDto>();
		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<CmUnitAmountDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<CmUnitAmountDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param kCode    社員コード(検索キー)
	 * @param unitType 計算単価区分(検索キー)
	 * @return CmUnitAmountDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmUnitAmountDto findForKey(String kCode, String unitType) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, kCode);
			setParam(index++, unitType);
			executeQuery();
			CmUnitAmountDto 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<CmUnitAmountDto> findForEmployee(String kCode) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			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<CmUnitAmountDto> findForUpdate(String kCode) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			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(CmUnitAmountDto 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(CmUnitAmountDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getUnitType());
			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 + " = ? ");
			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(CmUnitAmountDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getUnitType());
			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<CmUnitAmountDto>> findForHumanData() throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			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(CmUnitAmountDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getKCode()); // 社員コード
		setParam(index++, dto.getUnitType()); // 計算単価区分
		setParam(index++, dto.getUnitAmount()); // 計算単価
		setCommonParams(isInsert);
	}
}
