
package jp.co.sint.beans.mallmgr;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import jp.co.sint.basic.SIBasic;
import jp.co.sint.basic.SIStorage;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDBUtil;
import jp.co.sint.database.SITableCondition;
import jp.co.sint.database.SITableConditionManager;
import jp.co.sint.tools.SICheckDataConf;
import jp.co.sint.tools.SICheckValid;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIUtil;
import jp.co.sint.tools.SIURLParameter;

import org.apache.log4j.Category;


public class UIStorageListCond extends SIBasic {
  // ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);
  
  public UIStorageListCond() {
  }
  
  //検索用項目
  private String storageCodeTxt = "";
  private String storageNameTxt = "";
  
  //修正用項目
  private String storageCode = "";
  
  //検索条件
  private String conditionSQL = "";
  
  public String getStorageCode() {
    return storageCode;
  }
  
  public void setStorageCode(String storageCode) {
    if (SIUtil.isNull(storageCode)) storageCode = "";
    this.storageCode = storageCode;
  }
  
  public String getStorageCodeTxt() {
    return storageCodeTxt;
  }
  
  public void setStorageCodeTxt(String storageCodeTxt) {
    if (SIUtil.isNull(storageCodeTxt)) storageCodeTxt = "";
    this.storageCodeTxt = storageCodeTxt;
  }
  
  public String getStorageNameTxt() {
    return storageNameTxt;
  }
  
  public void setStorageNameTxt(String storageNameTxt) {
    if (SIUtil.isNull(storageNameTxt)) storageNameTxt = "";
    this.storageNameTxt = storageNameTxt;
  }
  
  public String getConditionSQL() {
    return conditionSQL;
  }
  
  public void setConditionSQL(String conditionSQL) {
    if (SIUtil.isNull(conditionSQL)) conditionSQL = "";
    this.conditionSQL = conditionSQL;
  }
  
  /**
   * init 入力したデータから、このbeansを設定します。
   * 
   * @param HttpServletRequest
   * @param SIURLParameter
   * @return なし
   * @throws なし
   */
  public void init(HttpServletRequest lRequest, SIURLParameter lUrlParam) {
    super.init(lRequest, lUrlParam);
    this.setStorageCode((String) lUrlParam.getParam("storageCode"));
    this.setStorageCodeTxt((String) lUrlParam.getParam("storageCodeTxt"));
    this.setStorageNameTxt((String) lUrlParam.getParam("storageNameTxt"));
  }
  
  
  /**
   * validate
   * 入力したデータをチェックします。
   * 不正なデータがある場合、エラーをオブジェクトに格納します。
   * そのオブジェクトは、エラーメッセージとして画面に表示されます。
   * @param HttpServletRequest ，Connection , SIURLParameter
   * @return true:エラーがない false:エラーが１つ以上ある
   * @throws なし
   */
  public boolean validate(HttpServletRequest lRequest) {
    SITableConditionManager lConditionMan = new SITableConditionManager();
    SICustomErrors errors = new SICustomErrors();
    
    // 預け先コード
    if (SIUtil.isNotNull(this.getStorageCodeTxt()) && SICheckValid.checkValid(errors, "預け先コード", this.getStorageCodeTxt(), SICheckDataConf.SICHECK_DATA_DIGIT_TYPE)) {
      lConditionMan.add(new SITableCondition("s", "StorageCode", this.getStorageCodeTxt(), SIConfig.SICONDITION_TYPE_EQUAL, SIConfig.SICONDITION_TYPE_AND));
    }
    
    // 預け先名称
    if (SIUtil.isNotNull(this.getStorageNameTxt()) && SICheckValid.checkValid(errors, "預け先名称", this.getStorageNameTxt(), SICheckDataConf.SICHECK_DATA_CMDTYNAME_TYPE)) {
      lConditionMan.add(new SITableCondition("s", "StorageName", this.getStorageNameTxt(), SIConfig.SICONDITION_TYPE_LIKE, SIConfig.SICONDITION_TYPE_AND));
    }
    
    this.setConditionSQL(lConditionMan.getCondtionSQL());
    if (!errors.isEmpty()) lRequest.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
    
    return errors.isEmpty();
  }
  
  /**
   * getCollection
   * 条件に合ったレコードを検索して、結果のリストを作成して、戻します。
   * @param Connection , String , String , SILogin
   * @return Collection
   * @throws SIDBAccessException
   */
  public Collection getCollection(Connection lConnection) throws SIDBAccessException {
    Statement lStatement = null;
    ResultSet lResultSet = null;
    SIStorage lStorage = new SIStorage();
    StringBuffer lSqlBuf = new StringBuffer();
    StringBuffer lCountBuf = new StringBuffer();
    Collection lResultColl = new ArrayList();
    
    // 基本のSQL
    lSqlBuf.append("SELECT s.*,coalesce(c.count,0) AS count FROM storagetbl s ");
    lSqlBuf.append("LEFT OUTER JOIN (SELECT storagecode,count(*) AS count FROM cmdtymtbl GROUP BY storagecode) c ON s.storagecode = c.storagecode ");
    lSqlBuf.append("WHERE 1=1 ").append(this.getConditionSQL());
    lSqlBuf.append("ORDER BY s.storagecode DESC");
    
    lCountBuf.append("SELECT count(*) FROM storagetbl s ");
    lCountBuf.append("WHERE 1=1 ").append(this.getConditionSQL());
    
    log.debug("lSqlBuf=" + lSqlBuf.toString());
    
    try {
      String rowCnt = SIDBUtil.getFirstData(lConnection, lCountBuf.toString());
      if (rowCnt.equals("") || rowCnt == null) {
        rowCnt = "0";
      }
      int lRecordCount = Integer.parseInt(rowCnt);// レコード数の取得
      
      int lPageSize = this.getPageSize();// ページサイズ
      int lPageNumber = this.getPageNumer();// ページ番号
      
      int lMaxPage = lRecordCount / lPageSize;
      if (lRecordCount % lPageSize > 0) {
        lMaxPage++;
      }
      if (lPageNumber > lMaxPage) lPageNumber = lMaxPage;
      
      // 開始レコードの番号の設定
      int lFromInx = (lPageNumber - 1) * lPageSize;
      // 終止のレコード番号の設定
      int lToInx = lFromInx + lPageSize - 1;
      if (lFromInx < 0) lFromInx = 0;
      if (lToInx < 0) lToInx = 0;
      
      log.debug("getCollection:lFromInx=" + lFromInx + ",lToInx=" + lToInx + ",lRecordCount=" + lRecordCount);
      
      lStatement = lConnection.createStatement();
      lSqlBuf.append(" LIMIT ").append(lPageSize);
      if(lFromInx>0) lSqlBuf.append(" OFFSET ").append(lFromInx);
      log.debug("getCollection:lStorageBuf=" + lSqlBuf.toString());
      lResultSet = lStatement.executeQuery(lSqlBuf.toString());
      
      for (int jj = 0; jj < lFromInx; jj++) lResultColl.add(null);
      int lIndex = 0;
      
      // レコードのセットの作成
      while (lResultSet.next() && lIndex < lPageSize) {
        lStorage = new SIStorage();
        lStorage.setStorageCode(lResultSet.getString("StorageCode"));
        lStorage.setStorageName(lResultSet.getString("StorageName"));
        lStorage.setEmail(lResultSet.getString("Email"));
        lStorage.setComment(lResultSet.getString("Comment"));
        lStorage.setDelFlg(lResultSet.getString("count").equals("0"));
        lResultColl.add(lStorage);
        lIndex++;
      }
      for (int jj = lFromInx + lPageSize; jj < lRecordCount; jj++) lResultColl.add(null);
    } catch (Exception ex) {
      throw new SIDBAccessException(ex);
    } finally {
      SIDBUtil.close(lResultSet, lStatement);
    }
    return lResultColl;
  }
}
