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.PayrollConst;
import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.dto.CmCommutationDto;

public class CmCommutationDao extends PayrollDao {
	
	// テーブル名及びキー列名
	public static final String	TABLE					= "CM_COMMUTATION";
	public static final String	KEY_1					= "K_CODE";			// 社員コード
	public static final String	KEY_2					= "COMMUTE_SEQUENCE";	// 通勤手当連番
																				
	// 列名
	public static final String	COL_K_CODE				= "K_CODE";			// 社員コード
	public static final String	COL_COMMUTE_SEQUENCE	= "COMMUTE_SEQUENCE";	// 通勤手当連番
	public static final String	COL_COMMUTE_TYPE		= "COMMUTE_TYPE";		// 通勤手当区分
	public static final String	COL_PAYMENT_INTERVAL	= "PAYMENT_INTERVAL";	// 支給間隔
	public static final String	COL_LUMP_MONTHLY_TYPE	= "LUMP_MONTHLY_TYPE";	// 一括区分
	public static final String	COL_PAY_START_MONTH		= "PAY_START_MONTH";	// 支給開始月
	public static final String	COL_COMMUTE_DISTANCE	= "COMMUTE_DISTANCE";	// 片道距離
	public static final String	COL_COMMUTE_AMOUNT		= "COMMUTE_AMOUNT";	// 通勤手当支給額
	public static final String	COL_COMMUTE_TAXED		= "COMMUTE_TAXED";		// 課税通勤費
	public static final String	COL_DELETE_FLAG			= "DELETE_FLAG";		// 削除フラグ
																				
	
	/**
	 * コンストラクタ
	 */
	public CmCommutationDao() {
		super();
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<CmCommutationDto> mappingAll() throws SQLException {
		List<CmCommutationDto> all = new ArrayList<CmCommutationDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTOのMap)
	 * @return Map 検索マップ
	 * @throws SQLException
	 */
	private Map<String, List<CmCommutationDto>> mappingAllMap() throws SQLException {
		Map<String, List<CmCommutationDto>> map = new HashMap<String, List<CmCommutationDto>>();
		List<CmCommutationDto> 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<CmCommutationDto> getSubList(List<CmCommutationDto> list, int fromIndex, int toIndex) {
		List<CmCommutationDto> subList = new ArrayList<CmCommutationDto>();
		for (int i = fromIndex; i <= toIndex; i++) {
			if (i >= list.size()) {
				break;
			}
			subList.add(list.get(i));
		}
		return subList;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return CmCommutationDto レコード
	 * @throws SQLException
	 */
	private CmCommutationDto mapping() throws SQLException {
		CmCommutationDto dto = new CmCommutationDto();
		dto.setKCode(rs.getString(COL_K_CODE)); // 社員コード
		dto.setCommuteSequence(rs.getInt(COL_COMMUTE_SEQUENCE)); // 通勤手当連番
		dto.setCommuteType(rs.getString(COL_COMMUTE_TYPE)); // 通勤手当区分
		dto.setPaymentInterval(rs.getString(COL_PAYMENT_INTERVAL)); // 支給間隔
		dto.setLumpMonthlyType(rs.getString(COL_LUMP_MONTHLY_TYPE)); // 一括区分
		dto.setPayStartMonth(rs.getDate(COL_PAY_START_MONTH)); // 支給開始月
		dto.setCommuteDistance(rs.getFloat(COL_COMMUTE_DISTANCE)); // 片道距離
		dto.setCommuteAmount(rs.getInt(COL_COMMUTE_AMOUNT)); // 通勤手当支給額
		dto.setCommuteTaxed(rs.getInt(COL_COMMUTE_TAXED)); // 課税通勤費
		dto.setDeleteFlag(rs.getInt(COL_DELETE_FLAG)); // 削除フラグ
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmCommutationDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<CmCommutationDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @return CmCommutationDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmCommutationDto findForKey(String kCode, int commuteSequence) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, kCode);
			setParam(index++, commuteSequence);
			executeQuery();
			CmCommutationDto 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<CmCommutationDto> 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();
		}
	}
	
	/**
	 * データ取得(交通用具使用による通勤手当計算用)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmCommutationDto> findForCommuteData() throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_COMMUTE_SEQUENCE + " = " + PayrollConst.COMMUTE_SEQ_2);
			sb.append(" AND ");
			sb.append(COL_DELETE_FLAG + " = " + PayrollConst.DEFAULT_FLAG_OFF);
			sb.append(" AND ");
			sb.append("(");
			sb.append(COL_COMMUTE_DISTANCE + " <> " + PayrollConst.AMOUNT_ZERO);
			sb.append(" OR ");
			sb.append(COL_COMMUTE_AMOUNT + " <> " + PayrollConst.AMOUNT_ZERO);
			sb.append(" OR ");
			sb.append(COL_COMMUTE_TAXED + " <> " + PayrollConst.AMOUNT_ZERO);
			sb.append(")");
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			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<CmCommutationDto> 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(CmCommutationDto 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(CmCommutationDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getCommuteSequence());
			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(CmCommutationDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getCommuteSequence());
			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<CmCommutationDto>> 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(CmCommutationDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getKCode()); // 社員コード
		setParam(index++, dto.getCommuteSequence()); // 通勤手当連番
		setParam(index++, dto.getCommuteType()); // 通勤手当区分
		setParam(index++, dto.getPaymentInterval()); // 支給間隔
		setParam(index++, dto.getLumpMonthlyType()); // 一括区分
		setParam(index++, dto.getPayStartMonth()); // 支給開始月
		setParam(index++, dto.getCommuteDistance()); // 片道距離
		setParam(index++, dto.getCommuteAmount()); // 通勤手当支給額
		setParam(index++, dto.getCommuteTaxed()); // 課税通勤費
		setParam(index++, dto.getDeleteFlag()); // 削除フラグ
		setCommonParams(isInsert);
	}
}
