/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * Copyright (C) 2004-2008 Aimluck,Inc.
 * http://aipostyle.com/
 * 
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */
package com.aimluck.eip.juchu;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;

import org.apache.cayenne.DataRow;
import org.apache.cayenne.ObjectId;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SQLTemplate;
import org.apache.cayenne.query.SelectQuery;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.eip.juchu.util.JuchuUtils;
import com.aimluck.eip.cayenne.om.account.EipMUserPosition;
import com.aimluck.eip.cayenne.om.security.TurbineGroup;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.cayenne.om.security.TurbineUserGroupRole;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALBaseUser;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALEipManager;
import com.aimluck.eip.common.ALEipPosition;
import com.aimluck.eip.common.ALEipPost;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.common.ALPermissionException;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.services.accessctl.ALAccessControlConstants;
import com.aimluck.eip.util.ALEipUtils;

import com.aimluck.eip.cayenne.om.portlet.ImwTJobOrder;

/**
 * ユーザーアカウントの検索データを管理するためのクラスです。 <br />
 * 
 */
public class JuchuUserSelectData extends ALAbstractSelectData {

	/** logger */
	private static final JetspeedLogger logger = JetspeedLogFactoryService
			.getLogger(JuchuUserSelectData.class.getName());

	/** 現在表示している部署 */
	private String currentPost;

	private int registeredUserNum = 0;

	/** 一覧データ */
	private ArrayList list;

	/** 完了区分 */
	private String kanryoKBN;

	private String KBNOrderBy;

	// ソートの名前
	private String loginSort;

	// ソートのタイプ
	private String loginSortType;

	/* Add 2011/01/19 キョク Start--- */
	private String isKBNOrderBy;

	public String getIsKBNOrderBy() {
		return isKBNOrderBy;
	}

	public void setIsKBNOrderBy(String isKBNOrderBy) {
		this.isKBNOrderBy = isKBNOrderBy;
	}

	/* Add 2011/01/19 キョク End--- */
	/**
	 * 初期化します。
	 * 
	 * @see com.aimluck.eip.common.ALAbstractSelectData#init(com.aimluck.eip.modules.actions.common.ALAction,
	 *      org.apache.turbine.util.RunData,
	 *      org.apache.velocity.context.Context)
	 */
	public void init(ALAction action, RunData rundata, Context context)
			throws ALPageNotFoundException, ALDBErrorException {
		String sort = ALEipUtils.getTemp(rundata, context, LIST_SORT_STR);
		if (sort == null || sort.equals("")) {
			ALEipUtils.setTemp(rundata, context, LIST_SORT_STR, "userposition");
		}

		/** Update 2010/08/25 チョウコウ Start */
		/* Update 2010/8/27 tou Start--- */
		// String kanryoKBN = rundata.getParameters().getString("kanryoFlag");
		//
		// if ("true".equals(kanryoKBN)) {
		String kanryoKBNtemp = rundata.getParameters().getString("kanryoFlag");
		if ("true".equals(kanryoKBNtemp)) {
			/* Update 2010/8/27 tou End--- */
			kanryoKBN = "1";
		}
		/* Add 2010/8/27 tou Start--- */
		else {
			kanryoKBN = "0";
		}
		/* Add 2011/01/19 キョク Start--- */
		if (kanryoKBNtemp == null) {
			kanryoKBNtemp = rundata.getParameters().getString("isKBNOrderBy");
			if ("true".equals(kanryoKBNtemp)) {
				kanryoKBN = "1";
			} else {
				kanryoKBN = "0";
			}
		}
		/* Add 2011/01/19 キョク End--- */
		/* Add 2010/8/27 tou End--- */
		/** Update 2010/08/25 チョウコウ End */
		/* Update 2010/8/27 tou Start--- */
		// KBNOrderBy = rundata.getParameters().getString("KBNOrderBy");
		if ("true".equals(kanryoKBNtemp)) {
			KBNOrderBy = "1";
			/* Add 2011/01/19 キョク Start--- */
			this.setIsKBNOrderBy("true");
			/* Add 2011/01/19 キョク End--- */
		} else {
			KBNOrderBy = "0";
			/* Add 2011/01/19 キョク Start--- */
			this.setIsKBNOrderBy("false");
			/* Add 2011/01/19 キョク End--- */
		}
		/* Update 2010/8/27 tou End--- */
		// Boolean kbnCheck= rundata.getParameters().containsKey("kanryouflg");
		// kanryoKBN= rundata.getParameters().getString("kanryouflg");
		// String kanryoKBN3 = rundata.getParameters().getString("kanryoFlag");
		// String kanryoKBN5 = rundata.getParameters().getString("test1");
		// Boolean kanryoKBN4 =
		// rundata.getParameters().getBoolean("kanryoFlag");
		String sort_type = ALEipUtils.getTemp(rundata, context,
				LIST_SORT_TYPE_STR);
		String sort2 = rundata.getParameters().getString("sort");
		if (sort2 != null && !sort2.equals("")) {
			loginSort = sort2;
		} else {
			String sort1 = ALEipUtils.getTemp(rundata, context, LIST_SORT_STR);
			if (sort1 != null && !sort1.equals("")) {
				loginSort = sort1;
			}
		}
		String sortType = rundata.getParameters().getString("sorttype");
		if (sortType != null && !sortType.equals("")) {
			loginSortType = sortType;
		} else {
			if (sort_type != null && !sort_type.equals("")) {
				loginSortType = sort_type;
			}
		}
		super.init(action, rundata, context);
	}

	/**
	 * 一覧表示します。
	 * 
	 * @param action
	 * @param rundata
	 * @param context
	 * @return TRUE 成功 FASLE 失敗
	 */
	public boolean doViewListSearch(ALAction action, RunData rundata,
			Context context) {
		try {
			init(action, rundata, context);
			doCheckAclPermission(rundata, context,
					ALAccessControlConstants.VALUE_ACL_LIST);
			action.setMode(ALEipConstants.MODE_LIST);
			List aList = selectListSearch(rundata, context);
			if (aList != null) {
				list = new ArrayList();
				Object obj = null;
				int size = aList.size();
				for (int i = 0; i < size; i++) {
					obj = getResultData(aList.get(i));
					if (obj != null) {
						list.add(obj);
					}
				}
			}
			action.setResultData(this);
			action.putData(rundata, context);
			ALEipUtils.removeTemp(rundata, context, ALEipConstants.ENTITY_ID);
			return (list != null);
		} catch (ALPermissionException e) {
			ALEipUtils.redirectPermissionError(rundata);
			return false;
		} catch (ALPageNotFoundException e) {
			ALEipUtils.redirectPageNotFound(rundata);
			return false;
		} catch (ALDBErrorException e) {
			ALEipUtils.redirectDBError(rundata);
			return false;
		}

	}

	/**
	 * アカウント一覧を取得します。 ただし、論理削除されているアカウントは取得しません。
	 * 
	 * @param rundata
	 * @param context
	 * @return
	 * @see com.aimluck.eip.common.ALAbstractSelectData#selectList(org.apache.turbine.util.RunData,
	 *      org.apache.velocity.context.Context)
	 */
	protected List selectList(RunData rundata, Context context) {
		try {
			// 登録済みのユーザ数をデータベースから取得
			DataContext dataContext = DatabaseOrmService.getInstance()
					.getDataContext();

			SelectQuery query = getSelectQuery(rundata, context);
			List list;

			if (loginSort != null && !loginSort.equals("")) {
				if (loginSort.equals("client_id")) {
					buildSelectQueryForListViewSort(query, rundata, context);
					list = getClientOrderByUserName(query, rundata, context,
							loginSortType);
				} else {
					buildSelectQueryForListView(query);
					buildSelectQueryForListViewSort(query, rundata, context);
					query.addOrdering(ImwTJobOrder.PERIOD_PROPERTY, true);
					query.addOrdering(ImwTJobOrder.JOB_ORDER_NUMBER_PROPERTY,
							true);
					list = dataContext.performQuery(query);

				}

			} else {
				buildSelectQueryForListView(query);
				buildSelectQueryForListViewSort(query, rundata, context);
				query.addOrdering(ImwTJobOrder.PERIOD_PROPERTY, true);
				query.addOrdering(ImwTJobOrder.JOB_ORDER_NUMBER_PROPERTY, true);
				list = dataContext.performQuery(query);

			}

			// buildSelectQueryForListView(query);
			// buildSelectQueryForListViewSort(query, rundata, context);

			// List list = dataContext.performQuery(query);
			registeredUserNum = list.size();
			return buildPaginatedList(list);
		} catch (Exception ex) {
			logger.error("Exception", ex);
			return null;
		}
	}

	private List getClientOrderByUserName(SelectQuery query, RunData rundata,
			Context context, String sortType) {
		if (sortType == null) {
			sortType = "asc";
		}
		String sql = "select c.job_order_id,c.job_order_number,c.receipt_date,c.job_order_name,"
				+ "c.receipt_user_id,c.juchukubun,c.hiyokubun,c.client_id,c.system_class1,"
				+ "c.system_class2,c.charge_name,c.worker_user_id01,c.worker_user_id02,"
				+ "c.period,c.price,c.yoteikosu,c.installmen_class,c.completion_class,"
				+ "c.disabled,c.create_user_id,c.update_user_id,c.create_date,c.update_date "
				+ "from imw_t_job_order as c,imw_m_client as u "
				+ "where c.disabled<>'T' and c.client_id=u.client_id ";
		/* Update 2010/8/27 tou Start--- */
		// if ("2".equals(KBNOrderBy)) {
		// sql = sql + " and c.completion_class='2' ";
		// }
		if ("1".equals(KBNOrderBy)) {
			/* Delete 2011/01/19 キョク Start--- */
			// sql = sql + " and c.completion_class='1' ";
			/* Delete 2011/01/19 キョク End--- */
		} else {
			sql = sql + " and c.completion_class='0' ";
		}
		/* Update 2010/8/27 tou End--- */
		sql = sql + "order by u.client_name " + sortType;
		List userlist = new ArrayList();
		try {
			DataContext dataContext = DatabaseOrmService.getInstance()
					.getDataContext();
			SQLTemplate rawSelect = new SQLTemplate(ImwTJobOrder.class, sql,
					true);
			rawSelect.setFetchingDataRows(true);
			List list = dataContext.performQuery(rawSelect);
			if (userlist == null || userlist.size() < 0) {
				return null;
			}

			int recordNum = list.size();
			DataRow dataRow;

			for (int i = 0; i < recordNum; i++) {
				dataRow = (DataRow) list.get(i);
				ImwTJobOrder jobOrder = new ImwTJobOrder();
				jobOrder.setJuchuId((Integer) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.JOB_ORDER_ID_PK_COLUMN));
				jobOrder.setJobOrderNumber((String) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.JOB_ORDER_NUMBER_COLUMN));
				jobOrder.setReceiptDate((Date) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.RECEIPT_DATE_COLUMN));
				jobOrder.setJobOrderName((String) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.JOB_ORDER_NAME_COLUMN));
				jobOrder.setReceiptUserId((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.RECEIPT_USER_ID_COLUMN));
				jobOrder.setJuchukubun((String) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.JUCHUKUBUN_COLUMN));
				jobOrder.setHiyokubun((String) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.HIYOKUBUN_COLUMN));
				jobOrder.setClientId((Integer) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.CLIENT_ID_COLUMN));
				jobOrder.setSystemClass1((String) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.SYSTEM_CLASS1_COLUMN));
				jobOrder.setSystemClass2((String) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.SYSTEM_CLASS2_COLUMN));
				jobOrder.setChargeName((String) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.CHARGE_NAME_COLUMN));
				jobOrder.setWorkerUserId01((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.WORKER_USER_ID01_COLUMN));
				jobOrder.setWorkerUserId02((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.WORKER_USER_ID02_COLUMN));
				jobOrder.setPeriod((Date) ALEipUtils.getObjFromDataRow(dataRow,
						ImwTJobOrder.PERIOD_COLUMN));
				jobOrder.setYoteikosu((java.math.BigDecimal) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.YOTEIKOSU_COLUMN));
				jobOrder.setInstallmenClass((String) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.INSTALLMEN_CLASS_COLUMN));
				jobOrder.setCompletionClass((String) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.COMPLETION_CLASS_COLUMN));
				jobOrder.setDisabled((String) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.DISABLED_COLUMN));
				jobOrder.setCreateUserId((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.CREATE_USER_ID_COLUMN));
				jobOrder.setUpdateUserId((Integer) ALEipUtils
						.getObjFromDataRow(dataRow,
								ImwTJobOrder.UPDATE_USER_ID_COLUMN));
				jobOrder.setCreateDate((Date) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.CREATE_DATE_COLUMN));
				jobOrder.setUpdateDate((Date) ALEipUtils.getObjFromDataRow(
						dataRow, ImwTJobOrder.UPDATE_DATE_COLUMN));

				userlist.add(jobOrder);
			}
		} catch (Exception ex) {
			logger.error("Exception", ex);
			return null;
		}
		return userlist;

	}

	/**
	 * アカウント一覧を取得します。 ただし、論理削除されているアカウントは取得しません。
	 * 
	 * @param rundata
	 * @param context
	 * @return
	 * @see com.aimluck.eip.common.ALAbstractSelectData#selectList(org.apache.turbine.util.RunData,
	 *      org.apache.velocity.context.Context)
	 */
	protected List selectListSearch(RunData rundata, Context context) {
		try {
			// 登録済みのユーザ数をデータベースから取得
			DataContext dataContext = DatabaseOrmService.getInstance()
					.getDataContext();

			SelectQuery query = getSelectQuerySearch(rundata, context);

			query.addOrdering(ImwTJobOrder.PERIOD_PROPERTY, true);
			query.addOrdering(ImwTJobOrder.JOB_ORDER_NUMBER_PROPERTY, true);
			List list = dataContext.performQuery(query);
			registeredUserNum = list.size();
			return buildPaginatedList(list);
		} catch (Exception ex) {
			logger.error("Exception", ex);
			return null;
		}
	}

	/**
	 * 検索条件を設定した SelectQuery を返します。 <BR>
	 * 
	 * @param rundata
	 * @param context
	 * @return
	 */
	private SelectQuery getSelectQuerySearch(RunData rundata, Context context) {
		SelectQuery query = new SelectQuery(ImwTJobOrder.class);
		// Expression exp3 =ExpressionFactory.matchExp(
		// ImwTJobOrder.DISABLED_PROPERTY, "F");
		//    
		// Expression exp4 =ExpressionFactory.matchExp(
		// ImwTJobOrder.COMPLETION_CLASS_PROPERTY, "2");
		//    
		// query.andQualifier(exp3);
		// query.andQualifier(exp4);

		return query;

	}

	/**
	 * 検索条件を設定した SelectQuery を返します。 <BR>
	 * 
	 * @param rundata
	 * @param context
	 * @return
	 */
	private SelectQuery getSelectQuery(RunData rundata, Context context) {
		SelectQuery query = new SelectQuery(ImwTJobOrder.class);

		// ObjectId oid = new ObjectId("ImwTJobOrder",
		// ImwTJobOrder.JOB_ORDER_ID_PK_COLUMN,3);
		// Expression exp1 =
		// ExpressionFactory.matchAllDbExp(oid.getIdSnapshot(),
		// Expression.GREATER_THAN);
		// Expression exp2 = ExpressionFactory.matchExp(
		// TurbineUser.COMPANY_ID_PROPERTY, Integer.valueOf(1));
		// // Expression exp3 =
		// // ExpressionFactory.matchExp(TurbineUser.DISABLED_PROPERTY,
		// // "F");

		// ExpressionFactory.matchExp(ImwTJobOrder.DISABLED_PROPERTY,"F");
		// ExpressionFactory.matchExp(ImwTJobOrder.JUCHUKUBUN_PROPERTY,"1");
		Expression exp3 = ExpressionFactory.matchExp(
				ImwTJobOrder.DISABLED_PROPERTY, "F");
		query.andQualifier(exp3);
		/** Update 2010/08/25 チョウコウ Start */
		if ("1".equals(kanryoKBN)) {
			/* Delete 2011/01/19 曲 Start */
			/*
			 * Expression exp4 = ExpressionFactory.matchExp(
			 * ImwTJobOrder.COMPLETION_CLASS_PROPERTY, "1");
			 * query.andQualifier(exp4);
			 */
			/* Delete 2011/01/19 曲 End */
		}
		/** Update 2010/08/25 チョウコウ Start */
		/** Delete 2010/08/25 チョウコウ Start */
		/* Update 2010/8/27 tou Start--- */
		// else {
		// Expression exp4 =ExpressionFactory.matchExp(
		// ImwTJobOrder.COMPLETION_CLASS_PROPERTY, "0");
		// query.andQualifier(exp4);
		// }
		else {
			Expression exp4 = ExpressionFactory.matchExp(
					ImwTJobOrder.COMPLETION_CLASS_PROPERTY, "0");
			query.andQualifier(exp4);
		}
		/* Update 2010/8/27 tou End--- */
		/** Delete 2010/08/25 チョウコウ Start */

		// Expression exp3 = ExpressionFactory.noMatchExp(
		// TurbineUser.DISABLED_PROPERTY, "T");
		// query.setQualifier(exp1);
		// query.andQualifier(exp2);
		//    
		// // String filter = ALEipUtils.getTemp(rundata, context,
		// LIST_FILTER_STR);
		// // current_filter = filter;
		//
		// Map gMap = ALEipManager.getInstance().getPostMap();
		// if (filter == null || "".equals(filter)
		// || !gMap.containsKey(Integer.valueOf(filter))) {
		// query.andQualifier(exp4);
		// return query;
		// }
		//  
		// Expression exp5 =ExpressionFactory.matchExp(
		// ImwTJobOrder.COMPLETION_CLASS_PROPERTY, "2");
		// query.andQualifier(exp5);
		//
		// String filter = ALEipUtils.getTemp(rundata, context,
		// LIST_FILTER_STR);
		// current_filter = filter;
		//
		// Map gMap = ALEipManager.getInstance().getPostMap();
		// if (filter == null || "".equals(filter)
		// || !gMap.containsKey(Integer.valueOf(filter))) {
		// return query;
		// }
		// String groupName = ((ALEipPost)
		// ALEipManager.getInstance().getPostMap()
		// .get(Integer.valueOf(filter))).getGroupName().getValue();
		// Expression exp4 = ExpressionFactory.matchExp(
		// TurbineUser.TURBINE_USER_GROUP_ROLE_PROPERTY + "."
		// + TurbineUserGroupRole.TURBINE_GROUP_PROPERTY + "."
		// + TurbineGroup.GROUP_NAME_PROPERTY, groupName);
		// query.andQualifier(exp4);
		// return query;
		return buildSelectQueryForFilter(query, rundata, context);
	}

	/**
	 * フィルタ用の <code>Criteria</code> を構築します。
	 * 
	 * @param crt
	 * @param rundata
	 * @param context
	 * @return
	 */
	protected SelectQuery buildSelectQueryForFilter(SelectQuery query,
			RunData rundata, Context context) {
		// // // 指定部署IDの取得
		// String filter = ALEipUtils.getTemp(rundata, context,
		// LIST_FILTER_STR);
		// //
		// // // 指定部署が存在しているかを確認し、存在していなければ値を削除する
		// // Map gMap = ALEipManager.getInstance().getPostMap();
		// // if (filter != null && filter.trim().length() != 0
		// // && !gMap.containsKey(Integer.valueOf(filter))) {
		// // filter = null;
		// // }
		//
		// String filter_type = ALEipUtils.getTemp(rundata, context,
		// LIST_FILTER_TYPE_STR);
		// String crt_key = null;
		// Attributes map = getColumnMap();
		// // if (filter == null || filter_type == null || filter.equals(""))
		// // return query;
		// crt_key = map.getValue(filter_type);
		// if (crt_key == null)
		// return query;
		//
		// Expression exp = ExpressionFactory.matchDbExp(crt_key, filter);
		// query.andQualifier(exp);
		// current_filter = filter;
		// current_filter_type = filter_type;

		// String sort = ALEipUtils.getTemp(rundata, context, LIST_SORT_STR);
		// String sort_type = ALEipUtils.getTemp(rundata, context,
		// LIST_SORT_TYPE_STR);
		// String crt_key = null;
		//
		// Attributes map = getColumnMap();
		// if (sort == null)
		// return query;
		// crt_key = map.getValue(sort);
		// if (crt_key == null)
		// return query;
		// if (sort_type != null
		// && ALEipConstants.LIST_SORT_TYPE_DESC.equals(sort_type)) {
		// query.addOrdering(crt_key, true);
		// } else {
		// query.addOrdering(crt_key, false);
		// sort_type = ALEipConstants.LIST_SORT_TYPE_ASC;
		// }

		String filter = ALEipUtils.getTemp(rundata, context, LIST_FILTER_STR);

		Map gMap = ALEipManager.getInstance().getPostMap();
		if (filter != null && filter.trim().length() != 0
				&& !gMap.containsKey(Integer.valueOf(filter))) {
			filter = null;
		}

		String filter_type = ALEipUtils.getTemp(rundata, context,
				LIST_FILTER_TYPE_STR);
		String crt_key = null;
		Attributes map = getColumnMap();
		if (filter == null || filter_type == null || filter.equals(""))
			return query;
		crt_key = map.getValue(filter_type);
		if (crt_key == null)
			return query;

		Expression exp = ExpressionFactory.matchDbExp(crt_key, filter);
		query.andQualifier(exp);
		current_filter = filter;
		current_filter_type = filter_type;
		return query;
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	private String getPostName(int id) {
		if (ALEipManager.getInstance().getPostMap().containsKey(
				Integer.valueOf(id))) {
			return ((ALEipPost) ALEipManager.getInstance().getPostMap().get(
					Integer.valueOf(id))).getPostName().getValue();
		}
		return null;
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	private String getPositionName(int id) {
		if (ALEipManager.getInstance().getPositionMap().containsKey(
				Integer.valueOf(id))) {
			return ((ALEipPosition) ALEipManager.getInstance().getPositionMap()
					.get(Integer.valueOf(id))).getPositionName().getValue();
		}
		return null;
	}

	/**
	 * @param rundata
	 * @param context
	 * @return
	 * @see com.aimluck.eip.common.ALAbstractSelectData#selectDetail(org.apache.turbine.util.RunData,
	 *      org.apache.velocity.context.Context)
	 */
	protected Object selectDetail(RunData rundata, Context context) {
		return JuchuUtils.getEipMJuchu(rundata, context);
	}

	/**
	 * @param obj
	 * @return
	 * @see com.aimluck.eip.common.ALAbstractSelectData#getResultData(java.lang.Object)
	 */
	protected Object getResultData(Object obj) {
		try {
			// TurbineUser record = (TurbineUser) obj;
			//
			// JuchuResultData rd = new JuchuResultData();
			// rd.initField();
			// rd.setUserId(record.getUserId().intValue());
			// rd.setUserName(record.getLoginName());
			// rd.setName(new
			// StringBuffer().append(record.getLastName()).append(" ")
			// .append(record.getFirstName()).toString());
			// rd.setPostNameList(ALEipUtils.getPostNameList(record.getUserId()));
			// rd.setPositionName(ALEipUtils.getPositionName(record.getPositionId()
			// .intValue()));
			// rd.setDisabled(record.getDisabled());
			SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
			ImwTJobOrder record = (ImwTJobOrder) obj;

			JuchuResultData rd = new JuchuResultData();
			rd.initField();
			rd.setDisabled(record.getDisabled());
			rd.setJobOrderNumber(record.getJobOrderNumber());
			rd.setJobOrderName(record.getJobOrderName());
			rd.setClientId(getClientName(record.getClientId().toString()));
			String tempPeriod;
			try {
				tempPeriod = sf.format(record.getPeriod()).toString();
			} catch (Exception ex) {
				tempPeriod = "";
			}
			rd.setPeriod(tempPeriod);
			rd
					.setCompletionClass(getHanyoName(record
							.getCompletionClass(), "6"));
			rd.setJobOrderId(record.getJuchuId().toString());
			return rd;
		} catch (Exception ex) {
			logger.error("Exception", ex);
			return null;
		}
	}

	/**
	 * @param obj
	 * @return 顧客名を取得する
	 */
	protected String getClientName(String id) {
		String ClientName = "";

		String query = "SELECT CLIENT_NAME FROM IMW_M_CLIENT WHERE CLIENT_ID = '"
				+ id + "'";
		DataContext dataContext = DatabaseOrmService.getInstance()
				.getDataContext();
		SQLTemplate rawSelect = new SQLTemplate(TurbineUser.class, query, true);
		rawSelect.setFetchingDataRows(true);
		List list = dataContext.performQuery(rawSelect);
		org.apache.cayenne.DataRow currentDataRow;
		currentDataRow = (org.apache.cayenne.DataRow) list.get(0);
		ClientName = ALEipUtils
				.getObjFromDataRow(currentDataRow, "CLIENT_NAME").toString();

		return ClientName;
	}

	/**
	 * @param obj
	 * @return ユーザ名を取得する
	 */
	protected String getUserName(String id) {
		String name = "";
		if (id == "") {
			return name;
		}
		String query = "SELECT (LAST_NAME || ' ' || FIRST_NAME) AS NM FROM TURBINE_USER WHERE USER_ID = '"
				+ id + "'";
		DataContext dataContext = DatabaseOrmService.getInstance()
				.getDataContext();
		SQLTemplate rawSelect = new SQLTemplate(TurbineUser.class, query, true);
		rawSelect.setFetchingDataRows(true);
		List list = dataContext.performQuery(rawSelect);
		org.apache.cayenne.DataRow currentDataRow;
		currentDataRow = (org.apache.cayenne.DataRow) list.get(0);
		name = ALEipUtils.getObjFromDataRow(currentDataRow, "NM").toString();

		return name;
	}

	/**
	 * @param obj
	 * @return 汎用名を取得する
	 */
	protected String getHanyoName(String id, String parent_hanyo_id) {
		String CompletionClassName = "";
		if (id == "") {
			return CompletionClassName;
		}
		if (parent_hanyo_id == "") {
			return CompletionClassName;
		}
		String query = "SELECT HANYOKUBUNNM FROM IMW_M_HANYO WHERE PARENT_HANYO_ID = ' "
				+ parent_hanyo_id + "' AND DISABLED='F' AND VALUE='" + id + "'";
		DataContext dataContext = DatabaseOrmService.getInstance()
				.getDataContext();
		SQLTemplate rawSelect = new SQLTemplate(TurbineUser.class, query, true);
		rawSelect.setFetchingDataRows(true);
		List list = dataContext.performQuery(rawSelect);
		org.apache.cayenne.DataRow currentDataRow;
		currentDataRow = (org.apache.cayenne.DataRow) list.get(0);
		CompletionClassName = ALEipUtils.getObjFromDataRow(currentDataRow,
				"HANYOKUBUNNM").toString();

		return CompletionClassName;
	}

	/**
	 * @param obj
	 * @return
	 * @see com.aimluck.eip.common.ALAbstractSelectData#getResultDataDetail(java.lang.Object)
	 */
	protected Object getResultDataDetail(Object obj) {
		try {
			// ALBaseUser record = (ALBaseUser) obj;
			// Integer id = new Integer(record.getUserId());
			//
			// JuchuResultData rd = new JuchuResultData();
			// rd.initField();
			// rd.setUserId(Integer.valueOf(record.getUserId()).intValue());
			// rd.setUserName(record.getUserName());
			// rd.setName(new
			// StringBuffer().append(record.getLastName()).append(" ")
			// .append(record.getFirstName()).toString());
			// rd.setNameKana(new
			// StringBuffer().append(record.getLastNameKana())
			// .append(" ").append(record.getFirstNameKana()).toString());
			// rd.setEmail(record.getEmail());
			// rd.setOutTelephone(record.getOutTelephone());
			// rd.setInTelephone(record.getInTelephone());
			// rd.setCellularPhone(record.getCellularPhone());
			// rd.setCellularMail(record.getCellularMail());
			// rd.setPostNameList(ALEipUtils.getPostNameList(id.intValue()));
			// rd.setPositionName(ALEipUtils.getPositionName(record.getPositionId()));
			// rd.setDisabled(record.getDisabled());
			// if (record.getPhoto() != null) {
			// rd.setHasPhoto(true);
			// } else {
			// rd.setHasPhoto(false);
			// }

			ImwTJobOrder record = (ImwTJobOrder) obj;
			SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
			JuchuResultData rd = new JuchuResultData();
			rd.initField();
			rd.setDisabled(record.getDisabled());
			rd.setJobOrderId(record.getJuchuId().toString());
			rd.setJobOrderNumber(record.getJobOrderNumber());
			rd.setJobOrderName(record.getJobOrderName());
			rd.setClientId(getClientName(record.getClientId().toString()));
			String tempPeriod;
			try {
				tempPeriod = sf.format(record.getPeriod()).toString();
			} catch (Exception ex) {
				tempPeriod = "";
			}
			rd.setPeriod(tempPeriod);
			rd
					.setCompletionClass(getHanyoName(record
							.getCompletionClass(), "6"));

			rd.setReceiptDate(sf.format(record.getReceiptDate()));
			rd.setReceiptUserId(getUserName(record.getReceiptUserId()
					.toString()));
			rd.setJuchukubun(getHanyoName(record.getJuchukubun(), "2"));
			rd.setHiyokubun(getHanyoName(record.getHiyokubun(), "8"));
			rd.setSystemClass1(getHanyoName(record.getSystemClass1(), "3"));
			rd.setSystemClass2(getHanyoName(record.getSystemClass2(), "4"));
			rd.setChargeName(record.getChargeName());
			//Upd 20110707 小濵 Start ---
//			rd.setWorkerUserId01(getUserName(record.getWorkerUserId01()
//					.toString())
//					+ "、" + getUserName(record.getWorkerUserId02().toString()));
            rd.setWorkerUserId01(getUserName(record.getWorkerUserId01().toString()));
            if(record.getWorkerUserId02() != null && record.getWorkerUserId02() != 0){
              rd.setWorkerUserId01(rd.getWorkerUserId01() + "、" 
                  + getUserName(record.getWorkerUserId02().toString()));
            }
            //Upd 20110707 小濵 End -----
			// rd.setWorkerUserId02(getUserName(record.getWorkerUserId02().toString()));
			rd.setPrice(record.getPrice().toString() + "円");
			rd.setYoteikosu(record.getYoteikosu().toString() + "人日");
			/* Update 2010/8/27 tou Start--- */
			// rd.setInstallmenClass(getHanyoName(record.getInstallmenClass(),
			// "6"));
			rd
					.setInstallmenClass(getHanyoName(record
							.getInstallmenClass(), "5"));
			/* Update 2010/8/27 tou End--- */

			return rd;
		} catch (Exception ex) {
			logger.error("Exception", ex);
			return null;
		}
	}

	/**
	 * @return
	 * @see com.aimluck.eip.common.ALAbstractSelectData#getColumnMap()
	 */
	protected Attributes getColumnMap() {
		Attributes map = new Attributes();
		// map.putValue("post", "POST_ID");
		/* Update 2011/01/17 wangchao Start--- */
		/*
		 * map.putValue("job_order_number",
		 * ImwTJobOrder.JOB_ORDER_NAME_PROPERTY);
		 */
		map
				.putValue("job_order_number",
						ImwTJobOrder.JOB_ORDER_NUMBER_PROPERTY);
		/* Update 2011/01/17 wangchao End--- */
		map.putValue("client_id", ImwTJobOrder.CLIENT_ID_PROPERTY);
		map.putValue("job_order_name", ImwTJobOrder.JOB_ORDER_NAME_PROPERTY);
		map.putValue("period", ImwTJobOrder.PERIOD_PROPERTY);

		// map.putValue("completion_class",
		// ImwTJobOrder.COMPLETION_CLASS_PROPERTY);

		// map.putValue("userposition", TurbineUser.EIP_MUSER_POSITION_PROPERTY
		// +
		// "."
		// + EipMUserPosition.POSITION_PROPERTY); // ユーザの順番
		return map;
	}

	/**
	 * 
	 * @return
	 */
	public String getCurrentPost() {
		return currentPost;
	}

	/**
	 * 
	 * @return
	 */
	public Map getPostMap() {
		return ALEipManager.getInstance().getPostMap();
	}

	/**
	 * 登録ユーザー数を取得する．
	 * 
	 * @return
	 */
	public int getRegisteredUserNum() {
		return registeredUserNum;
	}

	public int getRandomNum() {
		SecureRandom random = new SecureRandom();
		return (random.nextInt() * 100);
	}

	public String getLoginSort() {
		return loginSort;
	}

	public void setLoginSort(String loginSort) {
		this.loginSort = loginSort;
	}

	public String getLoginSortType() {
		return loginSortType;
	}

	public void setLoginSortType(String loginSortType) {
		this.loginSortType = loginSortType;
	}
}
