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.PtCurrentDto;

/**
 * 計算年月テーブルを操作をする機能を提供する。<br><br>
 * {@link PtCurrentDto}を用いて、DBとJavaプログラム間でレコードを共有する。<br>
 */
public class PtCurrentDao extends PayrollDao {
	
	/**
	 *  テーブル名。<br>
	 */
	public static final String TABLE = "PT_CURRENT";
	
	/**
	 *  主キー1。<br>
	 */
	public static final String KEY_01 = "OFFICE_CDOE";
	
	/**
	 *  主キー2。<br>
	 */
	public static final String KEY_02 = "CALC_TYPE";
	
	/**
	 *  主キー3。<br>
	 */
	public static final String KEY_03 = "CALC_DATE";
	
	public static final String COL_OFFICE_CDOE    = "OFFICE_CDOE"   ;
	public static final String COL_CALC_TYPE      = "CALC_TYPE"     ;
	public static final String COL_CALC_DATE      = "CALC_DATE"     ;
	public static final String COL_CURRENT_STATUS = "CURRENT_STATUS";
	
	/**
	 * {@link PayrollDao#PayrollDao(Properties, String, CmAspUserDto, CmUserDto, Connection)}
	 * を行う。<br>
	 * @param cfg     設定ファイル
	 * @param cmd     コマンド
	 * @param aspUser ASPユーザー
	 * @param user    ユーザー
	 * @param conn    DBコネクション
	 */
	public PtCurrentDao(
			Properties   cfg,
			String       cmd,
			CmAspUserDto aspUser,
			CmUserDto    user,
			Connection   conn
	) {
		super(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果をDTOとして取得する。<br>
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private PtCurrentDto mapping() throws SQLException {
		PtCurrentDto dto = new PtCurrentDto();
		dto.setOfficeCode   (rs.getString(COL_OFFICE_CDOE   ));
		dto.setCalcType     (rs.getByte  (COL_CALC_TYPE     ));
		dto.setCalcDate     (rs.getDate  (COL_CALC_DATE     ));
		dto.setCurrentStatus(rs.getByte  (COL_CURRENT_STATUS));
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 検索結果をDTOのListとして取得する。<br>
	 * @return 検索結果リスト
	 * @throws SQLException
	 */
	private List<PtCurrentDto> mappingAll() throws SQLException {
		List<PtCurrentDto> all = new ArrayList<PtCurrentDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * キーによりデータを取得する。<br>
	 * @param officeCode 事業所コード
	 * @param calcType   計算区分
	 * @param calcDate   計算年月
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PtCurrentDto findForKey(
			String officeCode,
			byte   calcType  ,
			Date   calcDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam    (index++, officeCode);
			setParam    (index++, calcType  );
			setDateParam(index++, calcDate  );
			executeQuery();
			if (rs.next()) {
				return mapping();
			}
			return null;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーにより行ロックを取得する。<br>
	 * @param officeCode 事業所コード
	 * @param calcType   計算区分
	 * @param calcDate   計算年月
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PtCurrentDto findForUpdate(
			String officeCode,
			byte   calcType  ,
			Date   calcDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam    (index++, officeCode);
			setParam    (index++, calcType  );
			setDateParam(index++, calcDate  );
			executeQuery();
			if (rs.next()) {
				return mapping();
			}
			return null;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件によりデータを取得する。<br>
	 * @param officeCode   事業所コード
	 * @param calcType     計算区分
	 * @param currentState 計算状態
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PtCurrentDto> findForState(
			String officeCode  ,
			byte   calcType    ,
			byte   currentState
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_OFFICE_CDOE + " = ? ");
			sb.append("AND ");
			sb.append(COL_CALC_TYPE + " = ? ");
			sb.append("AND ");
			sb.append(COL_CURRENT_STATUS + " = ? ");
			prepareStatement(getSelectQuery(getClass()) + sb.toString());
			setParam(index++, officeCode  );
			setParam(index++, calcType    );
			setParam(index++, currentState);
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件によりデータを取得する。<br>
	 * @param officeCode   事業所コード
	 * @param calcType     計算区分
	 * @param currentState 計算状態
	 * @return 検索結果(DTO)
	 * @throws IllegalAccessException 
	 * @throws SQLException 
	 */
	public PtCurrentDto findLatest(
			String officeCode  ,
			byte   calcType    ,
			byte   currentState
	) throws IllegalAccessException, SQLException {
		try {
			index = 1;
			prepareStatement(getSelectStatement(getClass()) + getMaxCalcDateTable());
			setParam(index++, officeCode  );
			setParam(index++, calcType    );
			setParam(index++, currentState);
			executeQuery();
			if (rs.next()) {
				return mapping();
			}
			return null;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 計算年月テーブルSQLを取得する。<br>
	 * @return 計算年月テーブルSQL文字列
	 * @throws IllegalAccessException 
	 */
	public String getMaxCalcDateTable() throws IllegalAccessException {
		StringBuffer sb = new StringBuffer();
		sb.append("FROM ");
		sb.append("(");
		sb.append(getSelectStatement(getClass()));
		sb.append("FROM ");
		sb.append(TABLE + ", ");
		sb.append("(");
		sb.append(	"SELECT ");
		sb.append(	COL_OFFICE_CDOE    + " AS M_OFFICE_CODE, "   );
		sb.append(	COL_CALC_TYPE      + " AS M_CALC_TYPE, "     );
		sb.append(	COL_CURRENT_STATUS + " AS M_CURRENT_STATUS, ");
		sb.append(	"MAX(" + COL_CALC_DATE + ") AS M_CALC_DATE " );
		sb.append(	"FROM " + TABLE + " ");
		sb.append(	"WHERE ");
		sb.append(	COL_OFFICE_CDOE    + " = ? AND ");
		sb.append(	COL_CALC_TYPE      + " = ? AND ");
		sb.append(	COL_CURRENT_STATUS + " = ? "    );
		sb.append(	"GROUP BY ");
		sb.append(  COL_OFFICE_CDOE    + ", ");
		sb.append(  COL_CALC_TYPE      + ", ");
		sb.append(  COL_CURRENT_STATUS       );
		sb.append(") TEMPVIEW ");
		sb.append("WHERE ");
		sb.append(COL_OFFICE_CDOE    + " = TEMPVIEW.M_OFFICE_CODE AND ");
		sb.append(COL_CALC_TYPE      + " = TEMPVIEW.M_CALC_TYPE AND "  );
		sb.append(COL_CALC_DATE      + " = TEMPVIEW.M_CALC_DATE AND "  );
		sb.append(COL_CURRENT_STATUS + " = TEMPVIEW.M_CURRENT_STATUS " );
		sb.append(") " + TABLE +" ");
		return sb.toString();
	}
	
	/**
	 * データを挿入する。<br>
	 * @param dto 挿入対象DTO
	 * @return 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(
			PtCurrentDto 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();
		}
	}
	
	/**
	 * データを更新する。<br>
	 * @param dto 更新対象DTO
	 * @return 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(
			PtCurrentDto dto
	) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
		
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam    (index++, dto.getOfficeCode());
			setParam    (index++, dto.getCalcType  ());
			setDateParam(index++, dto.getCalcDate  ());
			executeUpdate();
			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(PtCurrentDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getOfficeCode   ());
		setParam(index++, dto.getCalcType     ());
		setParam(index++, dto.getCalcDate     ());
		setParam(index++, dto.getCurrentStatus());
		setCommonParams(isInsert);
	}

	/**
	 * キーによるデータ取得
	 * @param stationCode 所属コード(検索キー)
	 * @return UtCurrentDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 * @throws NoSuchFieldException
	 */
	public PtCurrentDto findForKey(
			String officeCode
	) throws IllegalAccessException, SQLException, NoSuchFieldException {
		try {

			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_OFFICE_CDOE);
			sb.append(" = ? ");
			prepareStatement(getSelectQuery(getClass()) + sb.toString());
			setParam(index++, officeCode);
			
//			index = 1;
//			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
//			prepareStatement(getSelectStatement(getClass()));
//			setParam(index++, officeCode  );
			executeQuery();
			if (rs.next()) {
				return mapping();
			}
			return null;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
}
