package jp.mosp.payroll.bonus.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jp.mosp.payroll.bonus.BonusConst;
import jp.mosp.payroll.base.PayrollDao;
import jp.mosp.payroll.bonus.dto.PmBasisDto;
import jp.mosp.common.common.MospException;

public class PmBasisDao extends PayrollDao {
	
	// テーブル名及びキー列名
	public static final String TABLE = "UM_BASIS";
	public static final String KEY_1 = "K_CODE";	// 社員コード
	
	// 列名
	public static final String COL_K_CODE           = "K_CODE"          ;	// 社員コード
	public static final String COL_K_NAME           = "K_NAME"          ;	// 社員氏名
	public static final String COL_K_KANA           = "K_KANA"          ;	// 社員ﾌﾘｶﾞﾅ
	public static final String COL_STATION_CODE     = "STATION_CODE"    ;	// 所属コード
	public static final String COL_POSITION_CODE    = "POSITION_CODE"   ;	// 職位コード
	public static final String COL_EMPLOYMENT_TYPE  = "EMPLOYMENT_TYPE" ;	// 雇用区分
	public static final String COL_ENTRANCE_DATE    = "ENTRANCE_DATE"   ;	// 入社日
	public static final String COL_APPOINTMENT_DATE = "APPOINTMENT_DATE";	// 登用日
	public static final String COL_RETIREMENT_DATE  = "RETIREMENT_DATE" ;	// 退社日
	
	/**
	 * コンストラクタ
	 */
	public PmBasisDao() {
		super();
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<PmBasisDto> mappingAll() throws SQLException {
		List<PmBasisDto> all = new ArrayList<PmBasisDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return PmBasisDto UmBasisレコード
	 * @throws SQLException
	 */
	private PmBasisDto mapping() throws SQLException {
		PmBasisDto dto = new PmBasisDto();
		dto.setKCode          (rs.getString(COL_K_CODE          ));	// 社員コード
		dto.setKName          (rs.getString(COL_K_NAME          ));	// 社員氏名
		dto.setKKana          (rs.getString(COL_K_KANA          ));	// 社員ﾌﾘｶﾞﾅ
		dto.setStationCode    (rs.getString(COL_STATION_CODE    ));	// 所属コード
		dto.setPositionCode   (rs.getString(COL_POSITION_CODE   ));	// 職位コード
		dto.setEmploymentType (rs.getString(COL_EMPLOYMENT_TYPE ));	// 雇用区分
		dto.setEntranceDate   (rs.getDate  (COL_ENTRANCE_DATE   ));	// 入社日
		dto.setAppointmentDate(rs.getDate  (COL_APPOINTMENT_DATE));	// 登用日
		dto.setRetirementDate (rs.getDate  (COL_RETIREMENT_DATE ));	// 退社日
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PmBasisDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<PmBasisDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param kCode 社員コード(検索キー)
	 * @return PmBasisDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PmBasisDto findForKey(
			String  kCode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, kCode);
			executeQuery();
			PmBasisDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによる行ロック取得
	 * @param kCode 社員コード(検索キー)
	 * @return PmBasisDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PmBasisDto findForUpdate(
			String kCode
			) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, kCode);
			executeQuery();
			PmBasisDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(勤怠入力-社員一覧用)
	 * @param kCode       検索社員コード
	 * @param kName       検索社員名
	 * @param stationCode 検索所属コード
	 * @param selfKCode   操作社員コード
	 * @param datalevel   操作社員データレベル
	 * @param startDate   操作社員所属集計月開始日
	 * @param endDate     操作社員所属集計月終了日
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 */
	public List<PmBasisDto> findForCondition(
			String kCode,
			String kName,
			String stationCode,
			String selfKCode,
			int    dataLevel,
			Date   startDate,
			Date   endDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		//UhBasisDao uhBasisDao = new UhBasisDao();
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append("(");
		sb.append(	COL_K_CODE + " LIKE ? ");
		sb.append(	"AND ");
		sb.append(	COL_K_NAME + " LIKE ? ");
		sb.append(	"AND ");
		sb.append(	"(");
		sb.append(		"(");	// 自分
		sb.append(			COL_K_CODE + " = ? ");
		sb.append(			"AND ");
		sb.append(			COL_STATION_CODE + " IN (" + PmStationDao.getStationQuery() + ") ");
		sb.append(		") ");
		sb.append(		"OR ");
		sb.append(		"(");	// 所属+低データレベル
		sb.append(			COL_STATION_CODE + " IN (" + PmStationDao.getStationQuery() + ") ");
		sb.append(			"AND ");
		sb.append(			COL_POSITION_CODE + " IN (" + PmPositionDao.getQueryForLowerLevel() + ") ");
		sb.append(		") ");
		sb.append(		"OR ");
		sb.append(		"(");	// 所属+部下(Superior)
		sb.append(			COL_STATION_CODE + " IN (" + PmStationDao.getStationQuery() + ") ");
		sb.append(			"AND ");
		sb.append(			COL_K_CODE + " IN (" + PtSuperiorDao.getSuperiorQuery() + ") ");
		sb.append(		") ");
		sb.append(		"OR ");
		sb.append(		"(");	// 支援+低データレベル
		sb.append(			COL_K_CODE + " IN (" + PtSupportDao.getTermSupportQuery() + ") ");
		sb.append(			"AND ");
		sb.append(			COL_POSITION_CODE + " IN (" + PmPositionDao.getQueryForLowerLevel() + ") ");
		sb.append(		")");
		sb.append(	") ");
		sb.append(	"AND ");
		sb.append(	getSearchEmployeeStatement());
		sb.append(") ");
		/*
		sb.append("OR ");
		sb.append("(");
		sb.append(	COL_K_CODE + " IN ");	// 履歴テーブル
		sb.append(	"(");
		sb.append(		uhBasisDao.getQueryForEmployeeSelect());
		sb.append(	")");
		sb.append(") ");
		*/
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			// UM_BASIS部
			setParam(index++, kCode + "%");
			setParam(index++, "%" + kName + "%");
			setParam(index++, selfKCode);
			setParam(index++, stationCode);
			setParam(index++, stationCode);
			setParam(index++, dataLevel);
			setParam(index++, stationCode);
			setParam(index++, selfKCode);
			setParam(index++, stationCode);
			setParam(index++, startDate);
			setParam(index++, endDate);
			setParam(index++, startDate);
			setParam(index++, endDate);
			setParam(index++, dataLevel);
			setParam(index++, startDate);
			/*
			// UH_BASIS検索用日付
			setParam(index++, endDate);
			// UH_BASIS部
			setParam(index++, kCode + "%");
			setParam(index++, "%" + kName + "%");
			setParam(index++, selfKCode);
			setParam(index++, stationCode);
			setParam(index++, stationCode);
			setParam(index++, dataLevel);
			setParam(index++, stationCode);
			setParam(index++, selfKCode);
			setParam(index++, stationCode);
			setParam(index++, startDate);
			setParam(index++, endDate);
			setParam(index++, startDate);
			setParam(index++, endDate);
			setParam(index++, dataLevel);
			setParam(index++, startDate);
			*/
			// 実行
			executeQuery();
			List<PmBasisDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(人事マスタ保守-社員一覧用)
	 * @param kCode          検索社員コード
	 * @param kName          検索社員名
	 * @param kKana          検索ﾌﾘｶﾞﾅ
	 * @param stationCode    検索所属コード
	 * @param positionCode   検索職位コード
	 * @param retirementFlag 検索退職フラグ
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 */
	public List<PmBasisDto> findForHumanList(
			String kCode,
			String kName,
			String kKana,
			String stationCode,
			String positionCode,
			String retirementFlag
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_K_CODE + " LIKE ? ");
		sb.append("AND ");
		sb.append(COL_K_NAME + " LIKE ? ");
		sb.append("AND ");
		sb.append(COL_K_KANA + " LIKE ? ");
		if (stationCode != null && !stationCode.equals("")) {
			sb.append("AND ");
			sb.append(COL_STATION_CODE + " =  ? ");
		}
		if (positionCode != null && !positionCode.equals("")) {
			sb.append("AND ");
			sb.append(COL_POSITION_CODE + " = ? ");
		}
		if (retirementFlag != null && retirementFlag.equals(String.valueOf(BonusConst.RETIREMENT_FLAG_OFF))) {
			sb.append("AND ");
			sb.append(COL_RETIREMENT_DATE + " IS NULL ");
		} else if (retirementFlag != null && retirementFlag.equals(String.valueOf(BonusConst.RETIREMENT_FLAG_ON))) {
			sb.append("AND ");
			sb.append(COL_RETIREMENT_DATE + " IS NOT NULL ");
		}
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, kCode + "%");
			setParam(index++, "%" + kName + "%");
			setParam(index++, "%" + kKana + "%");
			if (stationCode != null && !stationCode.equals("")) {
				setParam(index++, stationCode);
			}
			if (positionCode != null && !positionCode.equals("")) {
				setParam(index++, positionCode);
			}
			// 実行
			executeQuery();
			List<PmBasisDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(担当営業所管理-社員一覧用)
	 * @param positionCode   検索職位コード
	 * @param retirementFlag 検索退職フラグ
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 */
	public List<PmBasisDto> findForTrainerList(
			int authority
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		PmUserDao pmUserDao = new PmUserDao();
		sb.append("WHERE ");
			sb.append(COL_K_CODE);
			sb.append(" IN ");
			sb.append("(");
			sb.append(pmUserDao.getSelectForSubQuery());
			sb.append(") ");
			sb.append(" AND ");
			sb.append(COL_RETIREMENT_DATE + " IS NULL ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, authority);
			// 実行
			executeQuery();
			List<PmBasisDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(所属コード)
	 * @param stationCode    検索所属コード
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<PmBasisDto> findForStation(
			String stationCode,
			Date   date
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_STATION_CODE + " IN (");
		sb.append(PmStationDao.getStationQuery());
		sb.append(") ");
		sb.append("AND ");
		sb.append(getSearchEmployeeStatement());
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForPosition());
			setParam(index++, stationCode);
			setParam(index++, date       );
			executeQuery();
			List<PmBasisDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ存在チェック
	 * @param  targetMode 存在確認処理モード
	 * @param  targetCode チェックコード(検索キー)
	 * @return PmBasisDto 検索結果(DTO)
	 * @throws SQLException
	 */
	public int findForExist(
			String   targetMode ,
			String   targetCode
	) throws SQLException {
		int count = 0;
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT COUNT(*) FROM " + TABLE );
		sb.append(" WHERE ");
		if (targetMode.equals("station") ){
			sb.append(COL_STATION_CODE + " = ? ");
			
		} else if (targetMode.equals("position")){
			sb.append(COL_POSITION_CODE + " = ? ");
			
		} else if (targetMode.equals("employment")){
			sb.append(COL_EMPLOYMENT_TYPE + " = ? ");
		}
		try {
			index = 1;
			prepareStatement(sb.toString());
			setParam(index++, targetCode);
			executeQuery();
			rs.next();
			count = rs.getInt(1);
		return 	count;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * データ挿入
	 * @param dto 挿入対象DTO
	 * @return int 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(PmBasisDto 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(PmBasisDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getKCode());
			executeUpdate();
			chkUpdate(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 delete(PmBasisDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getKCode());
			executeUpdate();
			chkDelete(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * パラメータ設定
	 * @param dto 更新対象DTO
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(PmBasisDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getKCode          ());	// 社員コード
		setParam(index++, dto.getKName          ());	// 社員氏名
		setParam(index++, dto.getKKana          ());	// 社員ﾌﾘｶﾞﾅ
		setParam(index++, dto.getStationCode    ());	// 所属コード
		setParam(index++, dto.getPositionCode   ());	// 職位コード
		setParam(index++, dto.getEmploymentType ());	// 雇用区分
		setParam(index++, dto.getEntranceDate   ());	// 入社日
		setParam(index++, dto.getAppointmentDate());	// 入社日
		setParam(index++, dto.getRetirementDate ());	// 退社日
		setCommonParams(isInsert);
	}

	/**
	 * 在職者取得用検索SQL取得
	 * @return 在職者取得用検索SQL文字列
	 */
	private String getSearchEmployeeStatement() {
		StringBuffer sb = new StringBuffer();
		sb.append("(");
		sb.append(COL_RETIREMENT_DATE + " IS NULL ");
		sb.append("OR ");
		sb.append(COL_RETIREMENT_DATE + " >= ?");
		sb.append(") ");
		return sb.toString();
	}
	
	/**
	 * 在職社員コード取得用取得SQL取得
	 * @return 在職社員取得用検索SQL文字列
	 */
	public String getSearchEmployeeStatementCode() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(TABLE + ".");
		sb.append(COL_K_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(getSearchEmployeeStatement());
		return sb.toString();
	}
	
	/**
	 * 職位による並べ替えSQL取得
	 * @return 職位による並べ替えSQL文字列
	 */
	private String getOrderForPosition() {
		StringBuffer sb = new StringBuffer();
		sb.append("ORDER BY ");
		sb.append(COL_POSITION_CODE + ", ");
		sb.append(COL_EMPLOYMENT_TYPE + ", ");
		sb.append(COL_STATION_CODE + ", ");
		sb.append(COL_K_CODE + " ");
		return sb.toString();
	}
	
	/**
	 * 社員コード検索用サブクエリー
	 * @return 社員コード検索サブクエリー文字列
	 */
	public static String getSelectForSubQuery() {
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT ");
		sb.append(COL_K_CODE + " ");
		sb.append("FROM ");
		sb.append(TABLE + " ");
		sb.append("WHERE ");
		sb.append(COL_K_CODE + " LIKE ? ");
		sb.append("AND ");
		sb.append(COL_K_NAME + " LIKE ? ");
		sb.append("AND ");
		sb.append(COL_K_KANA + " LIKE ? ");
		return sb.toString();
	}
	
	/**
	 * 条件文によるデータ取得(人事追加情報出力用)
	 * @param stationCode    検索所属コード
	 * @param positionCode   検索職位コード
	 * @param retirementFlag 検索退職フラグ
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException 
	 */
	public  String getForAddHumanListSubQuery(
			String stationCode,
			String positionCode,
			String retirementFlag
	) throws IllegalAccessException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT ");
		sb.append(COL_K_CODE + " ");
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_K_CODE + " LIKE ? ");
		sb.append("AND ");
		sb.append(COL_K_NAME + " LIKE ? ");
		sb.append("AND ");
		sb.append(COL_K_KANA + " LIKE ? ");
		if (stationCode != null && !stationCode.equals("")) {
			sb.append("AND ");
			sb.append(COL_STATION_CODE + " =  ? ");
		}
		if (positionCode != null && !positionCode.equals("")) {
			sb.append("AND ");
			sb.append(COL_POSITION_CODE + " = ? ");
		}
		if (retirementFlag != null && retirementFlag.equals(String.valueOf(BonusConst.RETIREMENT_FLAG_OFF))) {
			sb.append("AND ");
			sb.append(COL_RETIREMENT_DATE + " IS NULL ");
		} else if (retirementFlag != null && retirementFlag.equals(String.valueOf(BonusConst.RETIREMENT_FLAG_ON))) {
			sb.append("AND ");
			sb.append(COL_RETIREMENT_DATE + " IS NOT NULL ");
		}
		sb.append(getOrderForKey(getClass()));
		return sb.toString();
	}

}
