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

import java.security.SecureRandom;
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.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.mclient.util.MClientUtils;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.cayenne.om.portlet.ImwMClient;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipManager;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.util.ALEipUtils;

/**
 * 顧客の検索データを管理するためのクラスです。 <br />
 * 
 */
public class MClientUserSelectData extends ALAbstractSelectData {

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

  private int registeredUserNum = 0;

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

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

  /**
   * 初期化します。
   * 
   * @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");
    }

    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 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();
      List list;
      SelectQuery query = getSelectQuery(rundata, context);
      if (loginSort != null && !loginSort.equals("")) {
        if (loginSort.equals("login_name")) {
          buildSelectQueryForListViewSort(query, rundata, context);
          list = getClientOrderByUserName(query, rundata, context,
              loginSortType);

        } else {
          buildSelectQueryForListView(query);
          buildSelectQueryForListViewSort(query, rundata, context);
          list = dataContext.performQuery(query);
        }

      } else {
        buildSelectQueryForListView(query);
        buildSelectQueryForListViewSort(query, rundata, context);
        list = dataContext.performQuery(query);
      }
      registeredUserNum = list.size();
      return buildPaginatedList(list);
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * (IMTT) 殿 
   * サブシステム名 
   * 担当ユーザーのソートについて
   * 機能名(顧客)
   * 作成:アイエムシンクタンク株式会社 
   * 初版:年月日 by IMTT 
   * 改版:2010年08月14日 by キョク
   */
  private List getClientOrderByUserName(SelectQuery query, RunData rundata,
      Context context, String sortType) {
    if (sortType == null) {
      sortType = "asc";
    }
    String sql = "select c.client_id,c.client_name,c.client_names,"
        + "c.user_id,c.demand_client_id,c.pay_date,c.pay_day,c.pay_class,"
        + "c.pay_deadline,c.receipt_date,c.receipt_day,c.receipt_class,"
        + "c.receipt_deadline,c.disabled,c.create_user_id,c.update_user_id,"
        + "c.create_date,c.update_date "
        + "from imw_m_client as c,turbine_user as u "
        + "where c.disabled<>'T' and c.user_id=u.user_id "
        + "order by u.first_name " + sortType;
    List userlist = new ArrayList();
    try {
      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      SQLTemplate rawSelect = new SQLTemplate(ImwMClient.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);
        ImwMClient client = new ImwMClient();
        client.setClientId((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.CLIENT_ID_PK_COLUMN));
        client.setClientName((String) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.CLIENT_NAME_COLUMN));
        client.setClientNames((String) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.CLIENT_NAMES_COLUMN));
        client.setUserId((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.USER_ID_COLUMN));
        client.setDemandClientId((Integer) ALEipUtils.getObjFromDataRow(
            dataRow, ImwMClient.DEMAND_CLIENT_ID_COLUMN));
        client.setPayDate((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.PAY_DATE_COLUMN));
        client.setPayDay((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.PAY_DAY_COLUMN));
        client.setPayClass((String) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.PAY_CLASS_COLUMN));
        client.setPayDeadline((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.PAY_DEADLINE_COLUMN));
        client.setReceiptDate((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.RECEIPT_DATE_COLUMN));
        client.setReceiptDay((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.RECEIPT_DAY_COLUMN));
        client.setReceiptClass((String) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.RECEIPT_CLASS_COLUMN));
        client.setReceiptDeadline((Integer) ALEipUtils.getObjFromDataRow(
            dataRow, ImwMClient.RECEIPT_DEADLINE_COLUMN));
        client.setDisabled((String) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.DISABLED_COLUMN));
        client.setCreateUserId((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.CREATE_USER_ID_COLUMN));
        client.setUpdateUserId((Integer) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.UPDATE_USER_ID_COLUMN));
        client.setCreateDate((Date) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.CREATE_DATE_COLUMN));
        client.setUpdateDate((Date) ALEipUtils.getObjFromDataRow(dataRow,
            ImwMClient.UPDATE_DATE_COLUMN));

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

  }

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

    query.andQualifier(exp3);
    return buildSelectQueryForFilter(query, rundata, context);
  }

  /**
   * フィルタ用の <code>Criteria</code> を構築します。
   * 
   * @param crt
   * @param rundata
   * @param context
   * @return
   */
  protected SelectQuery buildSelectQueryForFilter(SelectQuery query,
      RunData rundata, Context context) {

    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 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 MClientUtils.getImwMClient(rundata, context);
  }

  /**
   * @param obj
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultData(java.lang.Object)
   */
  protected Object getResultData(Object obj) {
    try {

      ImwMClient record = (ImwMClient) obj;
      MClientResultData rd = new MClientResultData();
      rd.initField();
      rd.setClientId(record.getClientId().intValue());
      // 有効/無効
      rd.setDisabled(record.getDisabled());
      // 顧客名
      rd.setClientName(record.getClientName());
      // 顧客略称
      rd.setClientNames(record.getClientNames());

      rd.setUserId(record.getUserId().intValue());
      // 担当ユーザ
      rd
          .setLoginName(MClientUtils.getTLoginName(record.getUserId()
              .intValue()));

      return rd;

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

  /**
   * @param obj
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultDataDetail(java.lang.Object)
   */
  protected Object getResultDataDetail(Object obj) {
    try {

      ImwMClient record = (ImwMClient) obj;

      MClientResultData rd = new MClientResultData();
      rd.initField();
      rd.setClientId(record.getClientId().intValue());
      // 顧客名
      rd.setClientName(record.getClientName());
      // 顧客略称
      rd.setClientNames(record.getClientNames());
      // 支払区分
      String payClass = MClientUtils.getPayClass(record.getClientId(), 1);
      rd.setPayClass(payClass);
      // 支払月
      rd.setpaydate(record.getPayDate());
      // 支払日
      rd.setPayDay(record.getPayDay());
      // 入金区分
      String receiptClass = MClientUtils.getReceiptClass(record.getClientId(),
          7);

      rd.setReceiptClass(receiptClass);

      rd.setUserId(record.getUserId().intValue());
      // 担当ユーザ
      if (MClientUtils.getTLoginName(record.getUserId().intValue()) != null) {
        rd.setLoginName(MClientUtils.getTLoginName(record.getUserId()
            .intValue()));
      }
      rd.setDemandClientId(record.getDemandClientId().intValue());
      // 請求先名
      rd.setDemandClientName(MClientUtils.getMDemandClientName(record
          .getDemandClientId()));
      // 入金締日
      if (record.getPayDeadline() != null) {
        rd.setPayDeadline(record.getPayDeadline());
      }
      // 入金予定月
      if (record.getReceiptDate() != null) {
        rd.setReceiptDate(record.getReceiptDate());
      }
      // 入金予定日
      if (record.getReceiptDay() != null) {
        rd.setReceiptDay(record.getReceiptDay());
      }
      // 入金締日
      if (record.getReceiptDeadline() != null) {
        rd.setReceiptDeadline(record.getReceiptDeadline());
      }
      // 無効/有効
      if (record.getDisabled() != null) {
        rd.setDisabled(record.getDisabled());
      }

      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("client_name", ImwMClient.CLIENT_NAME_PROPERTY);
    map.putValue("client_names", ImwMClient.CLIENT_NAMES_PROPERTY);
    map
        .putValue(
            "login_name",
            (ImwMClient.TURBINE_USER_PROPERTY + "." + TurbineUser.LAST_NAME_PROPERTY));
    return map;
  }

  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;
  }
}
