/*
 * 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.exttimecard;

import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
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.commons.utils.ALDateUtil;
import com.aimluck.eip.cayenne.om.portlet.ImwTJobOrder;
import com.aimluck.eip.cayenne.om.portlet.ImwMClient;
import com.aimluck.eip.cayenne.om.portlet.ImwTDocumentFileMap;
import com.aimluck.eip.cayenne.om.portlet.ImwMHanyo;
import com.aimluck.eip.cayenne.om.security.TurbineUserGroupRole;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALPageNotFoundException;
//import com.aimluck.eip.document.util.DocumentUtils;
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;

/**
 * 文書管理のファイル検索用データ．
 *
 */
public class ExtTimecardJobOrderListSelectData extends ALAbstractSelectData {
  /** logger */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(ExtTimecardJobOrderListSelectData.class.getName());

  /** 検索結果件数 */
  private int searchSum = 0;

  private RunData rundata;

  /**
   * @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 {

    this.rundata = rundata;
    
    

    super.init(action, rundata, context);
  }

  /**
   *
   * @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);
      buildSelectQueryForListView(query);
      buildSelectQueryForListViewSort(query, rundata, context);
      List list = dataContext.performQuery(query);
      
      // 総数をセットする．
      if (list != null) {
        searchSum = list.size();
        return list;
        //return buildPaginatedList(list);
      } else {
        logger.info("documentRev list > result is null");
        return new ArrayList();
      }
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * 未使用。
   *
   * @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 null;
  }

  /**
   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultData(java.lang.Object)
   */
  protected Object getResultData(Object obj) {
    try {
      ImwTJobOrder record = (ImwTJobOrder) obj;

      ExtTimecardJobOrderListResultData rd = new ExtTimecardJobOrderListResultData();
      rd.initField();
      rd.setJob_order_id(record.getJobOrderId());
      rd.setJob_order_number(record.getJobOrderNumber());
      rd.setJob_order_name(record.getJobOrderName());
      rd.setClient_id(record.getClientId());
      rd.setPeriod(ALDateUtil.format(record.getPeriod(), "yyyy年M月d日"));
//      rd.setCompletion_class(record.getCompletionClass());
      rd.setDisabled(record.getDisabled());
      
      DataContext dataContext = DatabaseOrmService.getInstance()
      .getDataContext();
      //顧客名の取得
      SelectQuery query = new SelectQuery(ImwMClient.class);
      Expression exp = ExpressionFactory.matchDbExp(
          ImwMClient.CLIENT_ID_PK_COLUMN, record.getClientId());
      query.setQualifier(exp);
      List clientList = dataContext.performQuery(query);
      ImwMClient client = (ImwMClient) clientList.get(0);
      rd.setClient_name(client.getClientName());
      //完了区分の取得
      SelectQuery query1 = new SelectQuery(ImwMHanyo.class);
      Expression exp1 = ExpressionFactory.matchExp(
          ImwMHanyo.PARENT_HANYO_ID_PROPERTY,"6");
      query1.setQualifier(exp1);
      Expression exp2 = ExpressionFactory.matchExp(
          ImwMHanyo.VALUE_PROPERTY, record.getCompletionClass());
      query1.andQualifier(exp2);
      List completionList = dataContext.performQuery(query1);
      ImwMHanyo completion = (ImwMHanyo) completionList.get(0);
      rd.setCompletion_class(completion.getHanyokubunnm());
        
//      rd.setFileId(record.getFileId().longValue());
//      rd.setFileTitle(record.getFileTitle());
//      rd.setFileName(record.getFileName());
//      rd.setFileRevMj(record.getFileRevMj());
//      rd.setFileRevMn(record.getFileRevMn());
//      rd.setFileSize(record.getFileSize());
//      rd.setCheckinComment(record.getCheckinComment());
//      
//      //更新者名設定
//      String updateUserName = "";
//      if (record.getUpdateUserId() != null) {
//        ALEipUser updateUser = ALEipUtils.getALEipUser(record.getUpdateUserId()
//            .intValue());
//        if (updateUser != null) {
//          updateUserName = updateUser.getAliasName().getValue();
//        }
//      }
//      rd.setUpdateUser(updateUserName);
//      //更新日書式設定
//      rd.setUpdateDate(ALDateUtil.format(record.getUpdateDate(), "yyyy年M月d日"));

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

  /**
   * 未使用。
   *
   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultDataDetail(java.lang.Object)
   */
  protected Object getResultDataDetail(Object obj) {
    return null;
  }

  /**
   * @see com.aimluck.eip.common.ALAbstractSelectData#getColumnMap()
   */
  protected Attributes getColumnMap() {
    Attributes map = new Attributes();
    return map;
  }

  /**
   * 検索条件を設定した SelectQuery を返します。 <BR>
   *
   * @param rundata
   * @param context
   * @return
   */
  private SelectQuery getSelectQuery(RunData rundata, Context context) {
    Integer docid;
    DataContext dataContext = DatabaseOrmService.getInstance()
        .getDataContext();
    //受注一覧の取得
    SelectQuery mapquery = new SelectQuery(ImwTJobOrder.class);
    
    /** Add 2010/10/08 金廣 Start--- */
    //  課題23:作業入力検索画面の実装
    // 有効なデータのみ表示する。
    Expression exp = ExpressionFactory.matchExp(
        ImwTJobOrder.DISABLED_PROPERTY, "F");
    mapquery.andQualifier(exp);
    /** Add 2010/10/08 金廣 End----- */
    
    /** Add 2010/10/13 金廣 Start--- */
    //  課題23:作業入力検索画面の実装
    // 完了区分が残件
    Expression exp2 = ExpressionFactory.matchExp(
        ImwTJobOrder.COMPLETION_CLASS_PROPERTY, 0);
    mapquery.andQualifier(exp2);  
    // 納期の昇順でソート
    mapquery.addOrdering(ImwTJobOrder.PERIOD_PROPERTY, true);
    // 受注番号の昇順でソート
    mapquery.addOrdering(ImwTJobOrder.JOB_ORDER_NUMBER_PROPERTY, true);
    /** Add 2010/10/13 金廣 End----- */
    
/*    List maplist = dataContext.performQuery(mapquery);

    if(maplist.size() > 0){
      ImwTJobOrder map = (ImwTJobOrder) maplist.get(0);
      docid = map.getDocId();
    } else {
      docid = null;
    }

    //DOC_IDの一致するファイルの一覧を取得
    SelectQuery query = new SelectQuery(ImwTDocumentFile.class);
    Expression exp = ExpressionFactory.matchExp(
        ImwTDocumentFile.DOC_ID_PROPERTY, docid);
    //文書管理システム管理者は全ファイル閲覧可能
    Expression exp1;
    if (getVisibleDocId().size() == 0) {
      exp1 = ExpressionFactory.matchExp(
          ImwTDocumentFile.DOC_ID_PROPERTY, null);
    } else {
      exp1 = ExpressionFactory.inExp(
          ImwTDocumentFile.DOC_ID_PROPERTY, getVisibleDocId());
    }
    query.setQualifier(exp);
    
    boolean isDocAdmin = DocumentUtils.isDocAdmin(rundata);
    if (!isDocAdmin) {
      //一般ユーザなら参照可能ファイルのみ取得
      query.andQualifier(exp1);
    }
    
    //申請中のファイルは改版履歴に表示しない
    Expression exp2 = ExpressionFactory.matchExp(
        ImwTDocumentFile.STATUS_PROPERTY, 3);
    
    query.andQualifier(exp2.notExp());
      
    //バージョンの降順でソート
    query.addOrdering(ImwTDocumentFile.FILE_REV_MJ_PROPERTY, false);
    query.addOrdering(ImwTDocumentFile.FILE_REV_MN_PROPERTY, false);
*/
    return buildSelectQueryForFilter(mapquery, rundata, context);
  }

  /**
   * ログインユーザが所属するグループの一覧を返します。 <BR>
   *
   * @return grouplist
   */
  private List getUserGroupId() {
    List grouplist = new ArrayList();
    DataContext dataContext = DatabaseOrmService.getInstance()
        .getDataContext();
    SelectQuery query = new SelectQuery(TurbineUserGroupRole.class);
    Expression exp1 = ExpressionFactory.matchExp(
        TurbineUserGroupRole.TURBINE_USER_PROPERTY,
        ALEipUtils.getALEipUser(rundata).getUserId().getValue());
    query.setQualifier(exp1);
    List maplist = dataContext.performQuery(query);

    for(int i = 0; i < maplist.size(); i++){
      TurbineUserGroupRole map = (TurbineUserGroupRole) maplist.get(i);
      grouplist.add(map.getTurbineGroup());
    }
    return grouplist;
  }
  
  /**
   * ユーザが参照可能な文書ファイルのDOC_IDを返します。\<BR>
   * （参照権限が複数指定されている場合、同じDOC_IDが取得されます）\<BR>
   *
   * @param 
   * @return docid
   */
  private List getVisibleDocId() {
    List docidlist = new ArrayList();
    DataContext dataContext = DatabaseOrmService.getInstance()
        .getDataContext();
    SelectQuery query = new SelectQuery(ImwTDocumentFileMap.class);
    Expression exp1 = ExpressionFactory.matchExp(
        ImwTDocumentFileMap.USER_ID_PROPERTY,
        ALEipUtils.getALEipUser(rundata).getUserId().getValue());
    Expression exp2 = ExpressionFactory.inExp(
        ImwTDocumentFileMap.GROUP_ID_PROPERTY, getUserGroupId());
    Expression exp3 = ExpressionFactory.matchExp(
        ImwTDocumentFileMap.GROUP_ID_PROPERTY, -1);
    query.setQualifier(exp1.orExp(exp2).orExp(exp3));
    List maplist = dataContext.performQuery(query);

    for(int i = 0; i < maplist.size(); i++){
      ImwTDocumentFileMap map = (ImwTDocumentFileMap) maplist.get(i);
      docidlist.add(map.getDocId());
    }
    return docidlist;
  }

  public int getSearchSum() {
    return searchSum;
  }

  public int getDocFileId() {
    return rundata.getParameters().getInteger("fileid");
  }

  /**
   * アクセス権限チェック用メソッド。<br />
   * アクセス権限の機能名を返します。
   *
   * @return
   */
  public String getAclPortletFeature() {
    return ALAccessControlConstants.POERTLET_FEATURE_DOCUMENT_FILE;
  }
  
  public List getCompletionClassList() {
    List completionClasslist = new ArrayList();
    DataContext dataContext = DatabaseOrmService.getInstance()
        .getDataContext();
    SelectQuery query = new SelectQuery(ImwMHanyo.class);
    Expression exp1 = ExpressionFactory.matchExp(
        ImwMHanyo.PARENT_HANYO_ID_PROPERTY,"6");
    query.setQualifier(exp1);
    List completionlist = dataContext.performQuery(query);

    for(int i = 0; i < completionlist.size(); i++){
      ImwMHanyo completion = (ImwMHanyo) completionlist.get(i);
      completionClasslist.add(completion);
    }
    return completionClasslist;
    
  }
}
