/*
 * 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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import jp.cloudzero.mosp.exception.CloudzeroUnsupportedException;
import jp.getset.gae.bigtable.Statement.Mode;
import jp.mosp.common.common.MospException;
import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.dto.CmIncomeTaxDto;

public class CmIncomeTaxDao extends PayrollDao {
	
	// テーブル名及びキー列名
	public static final String	TABLE					= "CM_INCOME_TAX";
	public static final String	KEY_1					= "K_CODE";			// 社員コード
	public static final String	KEY_2					= "INC_EXPECTED_DATE";	// 所得税適用年
																				
	// 列名
	public static final String	COL_K_CODE				= "K_CODE";			// 社員コード
	public static final String	COL_INC_EXPECTED_DATE	= "INC_EXPECTED_DATE";	// 所得税適用年
	public static final String	COL_INCOME_TAX_TYPE		= "INCOME_TAX_TYPE";	// 課税区分
	public static final String	COL_ADJUSTMENT_TYPE		= "ADJUSTMENT_TYPE";	// 年末調整区分
	public static final String	COL_SELF_WIDOW_TYPE		= "SELF_WIDOW_TYPE";	// 本人寡婦区分
	public static final String	COL_SELF_HANDICAP_TYPE	= "SELF_HANDICAP_TYPE"; // 本人障害区分
	public static final String	COL_SELF_STUDENT_TYPE	= "SELF_STUDENT_TYPE";	// 本人学生区分
	public static final String	COL_SPOUSE_INTEND_TYPE	= "SPOUSE_INTEND_TYPE"; // 配偶者区分
	public static final String	COL_GENERAL_DEPENDENT	= "GENERAL_DEPENDENT";	// 一般扶養親族
	public static final String	COL_SPECIFIC_DEPENDENT	= "SPECIFIC_DEPENDENT"; // 特定扶養親族
	public static final String	COL_ELDERLY_DEPENDENT	= "ELDERLY_DEPENDENT";	// 老人扶養親族
	public static final String	COL_LIVE_WITH_ELD_REL	= "LIVE_WITH_ELD_REL";	// 同居老親等
	public static final String	COL_LIVE_WITH_HANDI_GE	= "LIVE_WITH_HANDI_GE"; // 同居特障一般
	public static final String	COL_LIVE_WITH_HANDI_SP	= "LIVE_WITH_HANDI_SP"; // 同居特障特定
	public static final String	COL_LIVE_WITH_HANDI_EL	= "LIVE_WITH_HANDI_EL"; // 同居特障老人
	public static final String	COL_LIVE_WITH_HANDI_ER	= "LIVE_WITH_HANDI_ER"; // 同居特障老親
	public static final String	COL_GENERAL_HANDICAP	= "GENERAL_HANDICAP";	// 一般障害者
	public static final String	COL_SPECIFIC_HANDICAP	= "SPECIFIC_HANDICAP";	// 特別障害者
	public static final String	COL_DEPENDENT_COUNT		= "DEPENDENT_COUNT";	// 扶養等の数
																				
	
	/**
	 * コンストラクタ
	 */
	public CmIncomeTaxDao() {
		super();
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<CmIncomeTaxDto> mappingAll() throws SQLException {
		List<CmIncomeTaxDto> all = new ArrayList<CmIncomeTaxDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return CmIncomeTaxDto レコード
	 * @throws SQLException
	 */
	private CmIncomeTaxDto mapping() throws SQLException {
		CmIncomeTaxDto dto = new CmIncomeTaxDto();
		dto.setKCode(rs.getString(COL_K_CODE)); // 社員コード
		dto.setIncExpectedDate(rs.getDate(COL_INC_EXPECTED_DATE)); // 所得税適用年
		dto.setIncomeTaxType(rs.getString(COL_INCOME_TAX_TYPE)); // 課税区分
		dto.setAdjustmentType(rs.getString(COL_ADJUSTMENT_TYPE)); // 年末調整区分
		dto.setSelfWidowType(rs.getString(COL_SELF_WIDOW_TYPE)); // 本人寡婦区分
		dto.setSelfHandicapType(rs.getString(COL_SELF_HANDICAP_TYPE)); // 本人障害区分
		dto.setSelfStudentType(rs.getString(COL_SELF_STUDENT_TYPE)); // 本人学生区分
		dto.setSpouseIntendType(rs.getString(COL_SPOUSE_INTEND_TYPE)); // 配偶者区分
		dto.setGeneralDependent(rs.getInt(COL_GENERAL_DEPENDENT)); // 一般扶養親族
		dto.setSpecificDependent(rs.getInt(COL_SPECIFIC_DEPENDENT)); // 特定扶養親族
		dto.setElderlyDependent(rs.getInt(COL_ELDERLY_DEPENDENT)); // 老人扶養親族
		dto.setLiveWithEldRel(rs.getInt(COL_LIVE_WITH_ELD_REL)); // 同居老親等
		dto.setLiveWithHandiGe(rs.getInt(COL_LIVE_WITH_HANDI_GE)); // 同居特障一般
		dto.setLiveWithHandiSp(rs.getInt(COL_LIVE_WITH_HANDI_SP)); // 同居特障特定
		dto.setLiveWithHandiEl(rs.getInt(COL_LIVE_WITH_HANDI_EL)); // 同居特障老人
		dto.setLiveWithHandiEr(rs.getInt(COL_LIVE_WITH_HANDI_ER)); // 同居特障老親
		dto.setGeneralHandicap(rs.getInt(COL_GENERAL_HANDICAP)); // 一般障害者
		dto.setSpecificHandicap(rs.getInt(COL_SPECIFIC_HANDICAP)); // 特別障害者
		dto.setDependentCount(rs.getInt(COL_DEPENDENT_COUNT)); // 扶養等の数
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 検索結果取得(DTOのMap)
	 * @return Map 検索マップ
	 * @throws SQLException
	 */
	private Map<String, CmIncomeTaxDto> mappingAllMap() throws SQLException {
		Map<String, CmIncomeTaxDto> all = new HashMap<String, CmIncomeTaxDto>();
		while (rs.next()) {
			CmIncomeTaxDto dto = mapping();
			all.put(dto.getKCode(), dto);
		}
		return all;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmIncomeTaxDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<CmIncomeTaxDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param kCode           社員コード(検索キー)
	 * @param incExpectedDate 所得税適用年(検索キー)
	 * @return CmIncomeTaxDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmIncomeTaxDto findForKey(String kCode, Date incExpectedDate) throws SQLException, IllegalAccessException,
			NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, kCode);
			setParam(index++, incExpectedDate);
			executeQuery();
			CmIncomeTaxDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員によるデータ取得
	 * @param kCode           社員コード(検索キー)
	 * @param incExpectedDate 適用年月  (検索キー)
	 * @return CmIncomeTaxDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 */
	public CmIncomeTaxDto findForEmployeeDate(String kCode, Date incExpectedDate) throws SQLException,
			IllegalAccessException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append(getSelectStatement(getClass()) + " ");
			sb.append("FROM ");
			sb.append(getHistoryTableForDate() + " ");
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL);
			
			prepareStatement(sb.toString());
			setParam(index++, incExpectedDate);
			setParam(index++, kCode);
			executeQuery();
			CmIncomeTaxDto 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
	 */
	public CmIncomeTaxDto findForEmployee(String kCode) throws SQLException, IllegalAccessException {
		try {
//			index = 1;
//			prepareStatement(getHistoryTable());
//			setParam(index++, kCode);
//			executeQuery();
//			CmIncomeTaxDto dto = null;
//			if (rs.next()) {
//				dto = mapping();
//			}
//			return dto;
			
			// サブクエリの取得
			this.setPreparedStatement(Mode.SELECT, TABLE);
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL, kCode);
			this.pob.appendGroupBy(COL_K_CODE);
			this.pob.appendOperationMax(COL_INC_EXPECTED_DATE);
			prepareStatement(null);
			executeQuery();
			List<Object> hKCodes = new ArrayList<Object>();
			List<Object> hEepectedDates = new ArrayList<Object>();
			while (rs.next()) {
				Object hKCode = rs.getObject(COL_K_CODE);
				if (!hKCodes.contains(hKCode)) {
					hKCodes.add(hKCode);
				}
				Object hEepectedDate = rs.getObject(COL_INC_EXPECTED_DATE);
				if (!hEepectedDates.contains(hEepectedDate)) {
					hEepectedDates.add(hEepectedDate);
				}
			}
			// 本文の取得
			this.setPreparedStatement(Mode.SELECT, TABLE);
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.IN, hKCodes);
			this.pob.appendWhere(COL_INC_EXPECTED_DATE, Query.FilterOperator.IN, hEepectedDates);
			prepareStatement(null);
			executeQuery();
			CmIncomeTaxDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
			
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員による配列データ取得
	 * @param kCode 社員コード(検索キー)
	 * @return CmIncomeTaxDto 検索結果(DTO)
	 * @throws SQLException
	 */
	public List<CmIncomeTaxDto> findForEmployeeList(String kCode) throws SQLException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("SELECT * FROM " + TABLE + " ");
			sb.append("WHERE ");
			sb.append(COL_K_CODE + " = ? ");
			
			this.setPreparedStatement(Mode.SELECT, TABLE);
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL);
			
			prepareStatement(sb.toString());
			setParam(index++, kCode);
			executeQuery();
			List<CmIncomeTaxDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 社員による行ロック取得
	 * @param kCode 社員コード(検索キー)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 */
	public CmIncomeTaxDto 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() + getForUpdate());
			setParam(index++, kCode);
			executeQuery();
			CmIncomeTaxDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによる行ロック取得
	 * @param kCode           社員コード(検索キー)
	 * @param incExpectedDate 所得税適用年(検索キー)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmIncomeTaxDto findForUpdate(String kCode, Date incExpectedDate) throws SQLException,
			IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, kCode);
			setParam(index++, incExpectedDate);
			executeQuery();
			CmIncomeTaxDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データ挿入
	 * @param dto 挿入対象DTO
	 * @return int 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(CmIncomeTaxDto 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(CmIncomeTaxDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getIncExpectedDate());
			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(CmIncomeTaxDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException,
			MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getKCode());
			setParam(index++, dto.getIncExpectedDate());
			executeUpdate();
			chkDelete(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(人事情報出力用)
	 * @param incExpectedDate 所得税適用年(検索キー)
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 */
	public Map<String, CmIncomeTaxDto> findForHumanData(Date incExpectedDate) throws SQLException,
			IllegalAccessException {
		try {
			index = 1;
			prepareStatement(getHistoryTableForHumanData());
			setParam(index++, incExpectedDate);
			executeQuery();
			return mappingAllMap();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
//	/**
//	 * 履歴データSQL取得
//	 * @return 履歴データ取得SQL文字列
//	 * @throws IllegalAccessException 
//	 */
//	private String getHistoryTable() throws IllegalAccessException {
//		StringBuffer sb = new StringBuffer();
//		sb.append(getSelectStatement(getClass()));
//		sb.append("FROM ");
//		sb.append(TABLE + ", ");
//		sb.append("(");
//		sb.append("SELECT ");
//		sb.append(COL_K_CODE + " AS H_K_CODE, ");
//		sb.append("MAX(" + COL_INC_EXPECTED_DATE + ") AS H_EXPECTED_DATE ");
//		sb.append("FROM " + TABLE + " ");
//		sb.append("WHERE ");
//		sb.append(COL_K_CODE + " = ? ");
//		sb.append("GROUP BY " + COL_K_CODE + " ");
//		sb.append(") HISTORY ");
//		sb.append("WHERE ");
//		sb.append(COL_K_CODE + " = HISTORY.H_K_CODE ");
//		sb.append("AND ");
//		sb.append(COL_INC_EXPECTED_DATE + " = HISTORY.H_EXPECTED_DATE ");
//		return sb.toString();
//	}
	
	/**
	 * 履歴データSQL取得
	 * @return 履歴データ取得SQL文字列
	 * @throws IllegalAccessException 
	 */
	private String getHistoryTableForHumanData() throws IllegalAccessException {
		throw new CloudzeroUnsupportedException();
/*		StringBuffer sb = new StringBuffer();
		sb.append(getSelectStatement(getClass()));
		sb.append("FROM ");
		sb.append(TABLE + ", ");
		sb.append("(");
		sb.append("SELECT ");
		sb.append(COL_K_CODE + " AS H_K_CODE, ");
		sb.append("MAX(" + COL_INC_EXPECTED_DATE + ") AS H_EXPECTED_DATE ");
		sb.append("FROM " + TABLE + " ");
		sb.append("WHERE " + COL_INC_EXPECTED_DATE + " <= ? ");
		sb.append("GROUP BY " + COL_K_CODE + " ");
		sb.append(") HISTORY ");
		sb.append("WHERE ");
		sb.append(COL_K_CODE + " = HISTORY.H_K_CODE ");
		sb.append("AND ");
		sb.append(COL_INC_EXPECTED_DATE + " = HISTORY.H_EXPECTED_DATE ");
		return sb.toString();*/
	}
	
	/**
	 * 履歴データSQL取得
	 * @return 履歴データ取得SQL文字列
	 * @throws IllegalAccessException 
	 */
	public String getHistoryTableForDate() throws IllegalAccessException {
		StringBuffer sb = new StringBuffer();
		sb.append("(");
		sb.append(getHistoryTableForHumanData());
		sb.append(") " + TABLE + " ");
		return sb.toString();
	}
	
	/**
	 * パラメータ設定
	 * @param dto 更新対象DTO
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(CmIncomeTaxDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getKCode()); // 社員コード
		setParam(index++, dto.getIncExpectedDate()); // 所得税適用年
		setParam(index++, dto.getIncomeTaxType()); // 課税区分
		setParam(index++, dto.getAdjustmentType()); // 年末調整区分
		setParam(index++, dto.getSelfWidowType()); // 本人寡婦区分
		setParam(index++, dto.getSelfHandicapType()); // 本人障害区分
		setParam(index++, dto.getSelfStudentType()); // 本人学生区分
		setParam(index++, dto.getSpouseIntendType()); // 配偶者区分
		setParam(index++, dto.getGeneralDependent()); // 一般扶養親族
		setParam(index++, dto.getSpecificDependent()); // 特定扶養親族
		setParam(index++, dto.getElderlyDependent()); // 老人扶養親族
		setParam(index++, dto.getLiveWithEldRel()); // 同居老親等
		setParam(index++, dto.getLiveWithHandiGe()); // 同居特障一般
		setParam(index++, dto.getLiveWithHandiSp()); // 同居特障特定
		setParam(index++, dto.getLiveWithHandiEl()); // 同居特障老人
		setParam(index++, dto.getLiveWithHandiEr()); // 同居特障老親
		setParam(index++, dto.getGeneralHandicap()); // 一般障害者
		setParam(index++, dto.getSpecificHandicap()); // 特別障害者
		setParam(index++, dto.getDependentCount()); // 扶養等の数
		setCommonParams(isInsert);
	}
}
