package jp.mosp.payroll.bonus.dao;

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

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

public class PmUserDao extends PayrollDao {
	
	// テーブル名及びキー列名
	public static final String TABLE  = "UM_USER";
	public static final String KEY_01 = "USER_ID";
	
	// 列名
	public static final String COL_USER_ID     = "USER_ID";
	public static final String COL_PASSWORD    = "PASSWORD";
	public static final String COL_K_CODE      = "K_CODE";
	public static final String COL_USER_NAME   = "USER_NAME";
	public static final String COL_AUTHORITY   = "AUTHORITY";
	public static final String COL_DATA_LEVEL  = "DATA_LEVEL";
	public static final String COL_CHANGE_PASS = "CHANGE_PASS";
	public static final String COL_DELETE_FLAG = "DELETE_FLAG";
	
	/**
	 * コンストラクタ
	 */
	public PmUserDao() {
		super();
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return 検索リスト
	 * @throws SQLException
	 */
	private List mappingAll() throws SQLException {
		List<PmUserDto> all = new ArrayList<PmUserDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return
	 * @throws SQLException
	 */
	private PmUserDto mapping() throws SQLException {
		PmUserDto dto = new PmUserDto();
		dto.setUserId(rs.getString(COL_USER_ID));
		dto.setPassword(rs.getString(COL_PASSWORD));
		dto.setKCode(rs.getString(COL_K_CODE));
		dto.setUserName(rs.getString(COL_USER_NAME));
		dto.setAuthority(rs.getString(COL_AUTHORITY));
		dto.setDataLevel(rs.getInt(COL_DATA_LEVEL));
		dto.setChangePass(rs.getDate(COL_CHANGE_PASS));
		dto.setDeleteFlag(rs.getInt(COL_DELETE_FLAG));
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 全データ取得
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List findAllCmUser() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List allCmUser = mappingAll();
			return allCmUser;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param userId ユーザーID(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PmUserDto findForKey(String userId) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, userId);
			executeQuery();
			PmUserDto pmUserDto = null;
			if (rs.next()) {
				pmUserDto = mapping();
			}
			return pmUserDto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによる行ロック取得
	 * @param userId ユーザーID(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public PmUserDto findForUpdate(String userId) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, userId);
			executeQuery();
			PmUserDto pmUserDto = null;
			if (rs.next()) {
				pmUserDto = mapping();
			}
			return pmUserDto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得
	 * @param userId 検索ユーザーID
	 * @param userName 検索ユーザー名
	 * @param mospAuthority 検索MosP利用権限
	 * @param deleteFlag 検索削除フラグ
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List findForCondition(
			String userId,
			String userName,
			String mospAuthority,
			String deleteFlag
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_USER_ID);
		sb.append(" <> 'admin' AND ");
		sb.append(COL_USER_ID);
		sb.append(" LIKE ? AND ");
		sb.append(COL_USER_NAME);
		sb.append(" LIKE ? ");
		if (!mospAuthority.equals("")) {
			sb.append("AND ");
			sb.append(COL_AUTHORITY);
			sb.append(" = ? ");
		}
		if (!deleteFlag.equals("")) {
			sb.append("AND ");
			sb.append(COL_DELETE_FLAG);
			sb.append(" = ? ");
		}
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, userId + "%");
			setParam(index++, "%" + userName + "%");
			if (!mospAuthority.equals("")) {
				setParam(index++, mospAuthority);
			}
			if (!deleteFlag.equals("")) {
				setParam(index++, Integer.parseInt(deleteFlag));
			}
			executeQuery();
			List listCmUser = mappingAll();
			return listCmUser;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * データ挿入
	 * @param dto 挿入対象DTO
	 * @return 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(PmUserDto 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 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(PmUserDto dto, boolean needLog) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getUserId());
			executeUpdate(needLog);
			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
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(PmUserDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getUserId());
		setParam(index++, dto.getPassword());
		setParam(index++, dto.getKCode());
		setParam(index++, dto.getUserName());
		setParam(index++, dto.getAuthority());
		setParam(index++, dto.getDataLevel());
		setParam(index++, dto.getChangePass());
		setParam(index++, dto.getDeleteFlag());
		setCommonParams(isInsert);
	}
	
	/**
	 * 担当営業所管理用サブクエリ
	 * @return プログラム権限による社員コード検索SQL文字列
	 */
	public String getSelectForSubQuery() {
		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(TABLE + ".");
		sb.append(COL_AUTHORITY);
		sb.append(" >= ? ");
		return sb.toString();
	}
}
