/*
 * MosP - Mind Open Source Project         http://www.mosp.jp/
 * Copyright (C) 1987-2009 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.workflow.dao;

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

import jp.mosp.common.CommonConst;
import jp.mosp.common.common.BaseDao;
import jp.mosp.common.common.MospException;

import jp.mosp.human.dao.MKihonDao;

import jp.mosp.workflow.dto.AmUnitDto;

public class AmUnitDao extends BaseDao {

	// テーブル名及びキー列名
	public static final String TABLE  			= "AM_UNIT"			;
	public static final String KEY_1 			= "UNITCODE"		;	//ユニットコード
	public static final String KEY_2 			= "STARTDATE"		;	//権限開始日

	// 列名
	public static final String COL_UNIT_CODE 		= "UNITCODE"	;	//ユニットコード
	public static final String COL_START_DATE 		= "STARTDATE"	;	//権限開始日
	public static final String COL_MAIN 			= "MAIN"		;	//承認者
	public static final String COL_AGENT 			= "AGENT"		;	//代理
	public static final String COL_DELETE_FLAG 	= "DELETEFLAG"	;	//削除フラグ

	public static final String TMP_UNIT_TABLE		= "TMP_UNIT"; //仮想のテーブル

	/**
	 * コンストラクタ
	 */
	public AmUnitDao() {
		super();
	}

	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<AmUnitDto> mappingAll() throws SQLException {
		List<AmUnitDto> all = new ArrayList<AmUnitDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}

	/**
	 * 検索結果取得(DTO)
	 * @return AmUnitDto am_unitレコード
	 * @throws SQLException
	 */
	private AmUnitDto mapping() throws SQLException {
		AmUnitDto dto = new AmUnitDto();
		dto.setUnitCode		(rs.getString (COL_UNIT_CODE)	);	//ユニットコード
		dto.setStartDate	(rs.getString (COL_START_DATE)	);	//権限開始日
		dto.setMain			(rs.getString (COL_MAIN)		);	//承認者
		dto.setAgent		(rs.getString (COL_AGENT)		);	//代理
		dto.setDeleteFlag	(rs.getInt    (COL_DELETE_FLAG)	);	//削除フラグ
		return dto;
	}

	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * キーによるデータ取得
	 * @param unitcode ユニットコード(検索キー)
	 * @param startdate 権限開始日(検索キー)
	 * @return AmUnitDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public AmUnitDto findForKey(
			String unitcode,
			String startdate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, unitcode);
			setParam(index++, Date.valueOf(startdate));
			executeQuery();
			AmUnitDto dto = null;
			if (rs.next()) {
				dto = mapping();
				mappingCommonInfo(dto);
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * キーによる行ロック取得
	 * @param unitcode ユニットコード(検索キー)
	 * @param startdate 権限開始日(検索キー)
	 * @return AmUnitDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public AmUnitDto findForUpdate(
			String unitcode,
			String startdate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, unitcode);
			setParam(index++, Date.valueOf(startdate));
			executeQuery();
			AmUnitDto dto = null;
			if (rs.next()) {
				dto = mapping();
				mappingCommonInfo(dto);
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得
	 * @param unitcode 検索ユニットコード
	 * @param startdate 検索権限開始日
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List findForCondition(
			String unitcode,
			String startdate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append(" WHERE ");
		sb.append(COL_UNIT_CODE);
		sb.append(" LIKE ? AND ");
		sb.append(COL_START_DATE);
		sb.append(" LIKE ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++,   unitcode  );
			setParam(index++,   startdate   + "%");
			executeQuery();
			List list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得
	 * @param unitCode 検索ユニットコード
	 * @param kCode 検索社員コード
	 * @param kName 検索社員氏名
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List findForCondition(
			String unitCode,
			String kCode,
			String kName
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(COL_UNIT_CODE);
		sb.append(" LIKE ? ");
		if (!kCode.equals("")) {
			sb.append(" AND ");
			sb.append(" ( ");
			sb.append(COL_MAIN + " IN (" + MKihonDao.getSearchKCodeSubQuery() + ") ");			
			sb.append(" OR ");
			sb.append(COL_AGENT + " IN (" + MKihonDao.getSearchKCodeSubQuery() + ") ");			
			sb.append(" ) ");
		}
		if (!kName.equals("")) {
			sb.append(" AND ");
			sb.append(" ( ");
			sb.append(COL_MAIN + " IN (" + MKihonDao.getSearchKNameSubQuery() + ") ");			
			sb.append(" OR ");
			sb.append(COL_AGENT + " IN (" + MKihonDao.getSearchKNameSubQuery() + ") ");			
			sb.append(" ) ");
		}
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++,		unitCode + "%");
			if (!kCode.equals("")) {
				setParam(index++,	kCode + "%");				
				setParam(index++,	kCode + "%");				
			}
			if (!kName.equals("")) {
				setParam(index++,	"%" + kName + "%");				
				setParam(index++,	"%" + kName + "%");				
			}
			executeQuery();
			List list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 選択可能ユニットコード一覧取得
	 * @return list 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<AmUnitDto> findForSelectableUnitArray(
			String startDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(COL_START_DATE + " = (" + getSearchUnitCodeSubQueryDescLimit() + " ) ");
		sb.append(" OR ");
		sb.append(COL_START_DATE);
		sb.append(" > ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, Date.valueOf(startDate));				
			setParam(index++, Date.valueOf(startDate));				
			executeQuery();
			List<AmUnitDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 指定開始日によるユニットコード一覧取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<AmUnitDto> findForCurrentUnitArray(String startDate) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(COL_START_DATE + " = (" + getSearchUnitCodeSubQueryDescLimit() + " ) ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, Date.valueOf(startDate));				
			executeQuery();
			List<AmUnitDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得
	 * @param kCode			検索社員コード
	 * @param startDate		検索権限開始日
	 * @return	list		検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<AmUnitDto> findForUnitArray(
			String kCode,
			String startDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(" ( ");
		sb.append(COL_MAIN + " IN (" + MKihonDao.getSearchKCodeEqualSubQuery() + ") ");			
		sb.append(" OR ");
		sb.append(COL_AGENT + " IN (" + MKihonDao.getSearchKCodeEqualSubQuery() + ") ");			
		sb.append(" ) ");
		sb.append(" AND ");
		sb.append(COL_START_DATE + " = (" + getSearchUnitCodeSubQueryDescLimit() + " ) ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++,	kCode);
			setParam(index++,	kCode);
			setParam(index++,	startDate);				
			executeQuery();
			List<AmUnitDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 指定開始日によるユニットコード取得
	 * @return DTOt 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public AmUnitDto findForCurrentUnit(
			String unitcode,
			String startDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(COL_UNIT_CODE);
		sb.append(" = ? ");
		sb.append(" AND ");
		sb.append(COL_START_DATE + " = (" + getSearchUnitCodeSubQueryDescLimit() + " ) ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, unitcode);
			setParam(index++, startDate);
			executeQuery();
			AmUnitDto dto = null;
			if (rs.next()) {
				dto = mapping();
				mappingCommonInfo(dto);
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 指定開始日によるユニットコード取得
	 * @return DTOt 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public AmUnitDto findForCurrentUnit(
			String unitcode,
			String kCode,
			String startDate
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(COL_UNIT_CODE);
		sb.append(" = ? ");
		sb.append(" AND ");
		sb.append(" ( ");
		sb.append(		COL_MAIN + " IN (" + MKihonDao.getSearchKCodeEqualSubQuery() + ") ");			
		sb.append(		" OR ");
		sb.append(		COL_AGENT + " IN (" + MKihonDao.getSearchKCodeEqualSubQuery() + ") ");			
		sb.append(" ) ");
		sb.append(" AND ");
		sb.append(COL_START_DATE + " = (" + getSearchUnitCodeSubQueryDescLimit() + " ) ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, unitcode);
			setParam(index++,	kCode);
			setParam(index++,	kCode);
			setParam(index++, Date.valueOf(startDate));
			executeQuery();
			AmUnitDto dto = null;
			if (rs.next()) {
				dto = mapping();
				mappingCommonInfo(dto);
			}
			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(AmUnitDto 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(AmUnitDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getUnitCode());
			setParam(index++, Date.valueOf(dto.getStartDate()));
			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(AmUnitDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getUnitCode());
			setParam(index++, dto.getStartDate());
			executeUpdate();
			chkDelete(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * パラメータ設定
	 * @param dto 更新対象DTO
	 * @throws SQLException
	 */
	private void setParams(AmUnitDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getUnitCode());	//ユニットコード
		setParam(index++, Date.valueOf(dto.getStartDate()));	//権限開始日
		setParam(index++, dto.getMain());		//承認者
		setParam(index++, dto.getAgent());		//代理
		setParam(index++, dto.getDeleteFlag());	//削除フラグ
		setCommonParams(isInsert);
	}

	/**
	 * 社員コード検索用サブクエリー
	 * @return		sb	生成サブクエリ
	 */
	public static String getSearchKCodeSubQuery() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_UNIT_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(" ( ");
		sb.append(		COL_MAIN 	+ " IN (" + MKihonDao.getSearchKCodeSubQuery() + ") ");			
		sb.append(		" OR ");
		sb.append(		COL_AGENT 	+ " IN (" + MKihonDao.getSearchKCodeSubQuery() + ") ");			
		sb.append(" ) ");
		return sb.toString();
	}

	/**
	 * 社員名検索用サブクエリー
	 * @return		sb	生成サブクエリ
	 */
	public static String getSearchKNameSubQuery() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_UNIT_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(" ( ");
		sb.append(		COL_MAIN	+ " IN (" + MKihonDao.getSearchKNameSubQuery() + ") ");			
		sb.append(		" OR ");
		sb.append(		COL_AGENT 	+ " IN (" + MKihonDao.getSearchKNameSubQuery() + ") ");
		sb.append(" ) ");
		return sb.toString();
	}

	/**
	 * 有効社員コード検索日用サブクエリー
	 * @return		sb	生成サブクエリ
	 */
	public static String getSearchKCodeSubQueryByStartDate() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_UNIT_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(" ( ");
		sb.append(		COL_MAIN + " IN (" + MKihonDao.getSearchKCodeEqualSubQuery() + ") ");			
		sb.append(	" OR ");
		sb.append(		COL_AGENT + " IN (" + MKihonDao.getSearchKCodeEqualSubQuery() + ") ");			
		sb.append(" ) ");
		sb.append(" AND ");
		sb.append(COL_START_DATE + " = (" + getSearchUnitCodeSubQueryDescLimit() + " ) ");
		return sb.toString();
	}

	/**
	 * 有効ユニットコード検索日用サブクエリー
	 * @return		sb	生成サブクエリ
	 */
	public static String getSearchSubQueryByStartDate() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_UNIT_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(COL_START_DATE + " = (" + getSearchUnitCodeSubQueryDescLimit() + " ) ");
		return sb.toString();
	}

	/**
	 * 指定開始日有効コード検索用サブクエリー
	 * @return	sb
	 */
	public static String getSearchUnitCodeSubQueryDescLimit() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(TMP_UNIT_TABLE + "." + COL_START_DATE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" AS ");
		sb.append(TMP_UNIT_TABLE);
		sb.append(" WHERE ");
		sb.append(TABLE + "." + COL_UNIT_CODE);
		sb.append(" = ");
		sb.append(TMP_UNIT_TABLE + "." + COL_UNIT_CODE);
		sb.append(" AND ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = " + CommonConst.DEFAULT_FLAG_OFF);
		sb.append(" AND ");
		sb.append(COL_START_DATE);
		sb.append(" <= ? ");
		sb.append("ORDER BY ");
		sb.append(COL_START_DATE);
		sb.append(" DESC ");
		sb.append(" LIMIT 1");
		return sb.toString();
	}

}
