/**
 * Copyright (c) 2003-2004 System Integrator Corporation.
 *                 All Rights Reserved.
 */
package jp.co.sint.beans.mallmgr;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.http.*;

import jp.co.sint.tools.*;
import jp.co.sint.config.*;
import jp.co.sint.basic.*;
import jp.co.sint.database.SIDBUtil;

import java.text.ParseException;

import org.apache.log4j.Category;

/**
 * @version $Id : UIRegCmdty.java,v 1.0 2003/08/14 Exp $
 * @author      : Jinwang Chen
 * <br>Description : 商品管理のプレビュー画面に管理beans
 * <p>History</p>
 * <p>Author&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reason</p>
 * ============&nbsp;&nbsp;&nbsp;==========&nbsp;&nbsp;===========================<br>
 * yamauchi   2004/01/21  Original
 */

public class UIRegCmdtyPreview extends SICmdty{
  
  //ログ用のインスタンスの生成
  private static Category log=Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);
  
  /**
   * UIRegCmdtyPreview
   * コンストラクタ
   * @param なし
   * @return なし
   * @throws なし
   */
  public UIRegCmdtyPreview() {}
  
  /**
   * UIRegCmdtyPreview
   * コンストラクタ
   * @param
   * @return なし
   * @throws なし
   */
  public UIRegCmdtyPreview(String lShopCode,String lCmdtyCode) {
    super(lShopCode,lCmdtyCode);
  }
  
  public UIRegCmdtyPreview(String lShopCode,String lCmdtyCode,String lIndividualCode) {
    super(lShopCode,lCmdtyCode);
    this.setIndividualCode(lIndividualCode);
  }
  
  /**
   * <b>init</b>
   * 入力したデータを基づいて、このbeansを設定します。
   * @param request データベースへのコネクション
   * @param lUrlParam
   * @return
   * @throws なし
   */
  public void init(HttpServletRequest lRequest,SIURLParameter lUrlParam){
    this.setUnitPrice((String)lUrlParam.getParam("bgPrice"));//BG特価
    this.setDescription((String)lUrlParam.getParam("commodityExplanation"));//商品説明
    this.setDiscountFlg((String)lUrlParam.getParam("DISCOUNTFLG"));//一括値引フラグ
    this.setSellFromDateYear((String)lUrlParam.getParam("sellFromDateYear"));//販売開始日の年
    this.setSellFromDateMonth((String)lUrlParam.getParam("sellFromDateMonth"));//販売開始日の月
    this.setSellFromDateDay((String)lUrlParam.getParam("sellFromDateDay"));//販売開始日の日
    this.setSellToDateYear((String)lUrlParam.getParam("sellToDateYear"));//販売終了日の年
    this.setSellToDateMonth((String)lUrlParam.getParam("sellToDateMonth"));//販売終了日の月
    this.setSellToDateDay((String)lUrlParam.getParam("sellToDateDay"));//販売終了日の日
    this.setRsrvEnableFlg((String)lUrlParam.getParam("rsrvEnableFlg"));//予約販売
    this.setAmountFlg((String)lUrlParam.getParam("amountFlg"));//在庫数管理
    this.setRsrvAmount((String)lUrlParam.getParam("rsrvAmount"));//予約可能数
    this.setSalesSituationFlg((String)lUrlParam.getParam("salesSituationFlg"));//販売状況フラグ
    this.setInquiryFlg((String)lUrlParam.getParam("inquiryFlg"));//問合せ区分
    String tenureofuse = (String)lUrlParam.getParam("tenureofuse");
    String guaranteedterm = (String)lUrlParam.getParam("guaranteedTerm");
    if(SIUtil.isNotNull(tenureofuse) && SICheckUtil.isDigit(tenureofuse))//使用年数が半角数字なら反映する
      this.setTenureOfUse(Integer.parseInt(tenureofuse));
    else this.setTenureOfUse(0);
    if(SIUtil.isNotNull(guaranteedterm) && SICheckUtil.isDigit(guaranteedterm))//保証期間が半角数字なら反映する
      this.setGuaranteedTerm(Integer.parseInt(guaranteedterm));
    else this.setGuaranteedTerm(0);
    this.setBGPriceDispFlg((String)lUrlParam.getParam("bGPriceDispFlg"));
    this.setExpansionComment1Title((String)lUrlParam.getParam("expansionComment1Title"));
    this.setExpansionComment1Text((String)lUrlParam.getParam("expansionComment1Text"));
    this.setExpansionComment2Title((String)lUrlParam.getParam("expansionComment2Title"));
    this.setExpansionComment2Text((String)lUrlParam.getParam("expansionComment2Text"));
    this.setExpansionComment3Title((String)lUrlParam.getParam("expansionComment3Title"));
    this.setExpansionComment3Text((String)lUrlParam.getParam("expansionComment3Text"));
    this.setExpansionComment4Title((String)lUrlParam.getParam("expansionComment4Title"));
    this.setExpansionComment4Text((String)lUrlParam.getParam("expansionComment4Text"));
    // EDBTG005-00 kamata add start
    this.setExpansionComment5Title((String)lUrlParam.getParam("expansionComment5Title"));
    this.setExpansionComment5Text((String)lUrlParam.getParam("expansionComment5Text"));
    // EDBTG005-00 kamata add end
    this.setCatchcopy((String) lUrlParam.getParam("catchcopy"));                   // キャッチコピー
    this.setSpecification((String) lUrlParam.getParam("specification"));             // 仕様
    this.setActiveingredient((String) lUrlParam.getParam("activeingredient"));  // 有効成分
    this.setComponent((String) lUrlParam.getParam("component"));                // 全成分
    this.setPrecaution((String) lUrlParam.getParam("precaution"));                  // 注意事項
    this.setOthernotice((String) lUrlParam.getParam("othernotice"));               // その他
  }
  
  /**
   * <b>initSet</b>
   * 入力したデータを基づいて、このbeansを設定します。（商品構成マスタ用）
   * @param request データベースへのコネクション
   * @param lUrlParam
   * @return
   * @throws なし
   */
  public void initSet(HttpServletRequest lRequest,SIURLParameter lUrlParam){
    this.setUnitPrice((String)lUrlParam.getParam("bgPrice"));//BG特価
    this.setDescription((String)lUrlParam.getParam("commodityExplanation"));//商品説明
    this.setDiscountFlg((String)lUrlParam.getParam("DISCOUNTFLG"));//一括値引フラグ
    this.setSellFromDateYear((String)lUrlParam.getParam("sellFromDateYear"));//販売開始日の年
    this.setSellFromDateMonth((String)lUrlParam.getParam("sellFromDateMonth"));//販売開始日の月
    this.setSellFromDateDay((String)lUrlParam.getParam("sellFromDateDay"));//販売開始日の日
    this.setSellToDateYear((String)lUrlParam.getParam("sellToDateYear"));//販売終了日の年
    this.setSellToDateMonth((String)lUrlParam.getParam("sellToDateMonth"));//販売終了日の月
    this.setSellToDateDay((String)lUrlParam.getParam("sellToDateDay"));//販売終了日の日
    this.setRsrvEnableFlg((String)lUrlParam.getParam("rsrvEnableFlg"));//予約販売
    this.setAmountFlg((String)lUrlParam.getParam("amountFlg"));//在庫数管理
    this.setRsrvAmount((String)lUrlParam.getParam("rsrvAmount"));//予約可能数
    this.setSalesSituationFlg((String)lUrlParam.getParam("salesSituationFlg"));//販売状況フラグ
    this.setInquiryFlg((String)lUrlParam.getParam("inquiryFlg"));//問合せ区分
    String tenureofuse = (String)lUrlParam.getParam("tenureofuse");
    String guaranteedterm = (String)lUrlParam.getParam("guaranteedTerm");
    if(SIUtil.isNotNull(tenureofuse) && SICheckUtil.isDigit(tenureofuse))//使用年数が半角数字なら反映する
      this.setTenureOfUse(Integer.parseInt(tenureofuse));
    else this.setTenureOfUse(0);
    if(SIUtil.isNotNull(guaranteedterm) && SICheckUtil.isDigit(guaranteedterm))//保証期間が半角数字なら反映する
      this.setGuaranteedTerm(Integer.parseInt(guaranteedterm));
    else this.setGuaranteedTerm(0);
    this.setBGPriceDispFlg((String)lUrlParam.getParam("bGPriceDispFlg"));
    this.setExpansionComment1Title((String)lUrlParam.getParam("expansionComment1Title"));
    this.setExpansionComment1Text((String)lUrlParam.getParam("expansionComment1Text"));
    this.setExpansionComment2Title((String)lUrlParam.getParam("expansionComment2Title"));
    this.setExpansionComment2Text((String)lUrlParam.getParam("expansionComment2Text"));
    this.setExpansionComment3Title((String)lUrlParam.getParam("expansionComment3Title"));
    this.setExpansionComment3Text((String)lUrlParam.getParam("expansionComment3Text"));
    this.setExpansionComment4Title((String)lUrlParam.getParam("expansionComment4Title"));
    this.setExpansionComment4Text((String)lUrlParam.getParam("expansionComment4Text"));
    // EDBTG005-00 kamata add start
    this.setExpansionComment5Title((String)lUrlParam.getParam("expansionComment5Title"));
    this.setExpansionComment5Text((String)lUrlParam.getParam("expansionComment5Text"));
    // EDBTG005-00 kamata add end
    this.setMakerCode((String)lUrlParam.getParam("makerCode"));
    this.setCampaignPriceFlg((String)lUrlParam.getParam("campaignPriceFlg"));
  }
  
  /**
   * <b>setStockAmountTxt</b>
   * プレビュー用の在庫状況
   * @param UICmdtyStock
   * @return なし
   * @throws なし
  */
  public void setStockAmountTxt(UICmdtyStock regStock){
    int count = 0;
    for(int i=0;i<regStock.getAmountTxt().length;i++){
      count=count+Integer.parseInt(regStock.getAmountTxt()[i]);
    }
    this.setAmount(String.valueOf(count));
  }
  
  /**
   * <b>setBranchStockTxt</b>
   * プレビュー用の在庫状況
   * @param UICmdtyStock
   * @param String
   * @return なし
   * @throws なし
  */
  public void setBranchStockTxt(UICmdtyStock regStock,String unitName){
    int count = 0;
    int countd = 0;
    String[] txt1 = new String[20];
    String[] txt2 = new String[20];
    int[] order = new int[20];
    
    for(int i=0;i<regStock.getAmountTxt().length;i++){
      if (!regStock.getAmountTxt()[i].equals("0")){
        txt1[count]=regStock.getBranchNameTxt()[i]+" "+regStock.getAmountTxt()[i]+unitName;
        order[count]=Integer.parseInt(regStock.getPriorityTxt()[i]);
        count++;
      }
    }
    if (count==0) return;
    countd = count;
    LOOP2:
    while(countd>0){
      for (int j=0;j<count;j++){
        LOOP1:
        for (int k=0;k<count;k++){
          if (order[j]>order[k]) break LOOP1;
          if (k==count-1) {
              txt2[count-countd]=txt1[j];
              order[j]=27;
              countd--;
              if (countd==0) break LOOP2;
          }
        }
      }
    }
    String branchStockTxt = "";
    for (int l=0;l<count;l++){
      branchStockTxt = branchStockTxt + txt2[l];
      if (l<count-1) branchStockTxt = branchStockTxt + "<br>&nbsp;&nbsp;";
    }
    this.setBranchStockTxt(branchStockTxt);
  }
  
  /**
   * <b>setPreviewData</b>
   * プレビューでの表示の設定を行います。
   * @return void
   * @throws なし
   */
  public void setPreviewData(Connection lConnection){
    SIDateTime lDateTime=new SIDateTime();
    //特別価格であるかどうか
    try {
      if (!SICheckUtil.dateGreater(this.getSalesFromDate(),lDateTime.getFullDate())
          &&SICheckUtil.dateGreater(this.getSalesToDate(),lDateTime.getFullDate())){
        this.setCalcUnitPrice(this.getSalesUnitPrice());//勘定価格
        this.setSalesFlg("1");
      }else{
        this.setCalcUnitPrice(this.getUnitPrice()); //勘定価格
        this.setSalesFlg("0");
      }
    } catch (ParseException e) {
      e.printStackTrace();
    } catch (SIException e) {
      e.printStackTrace();
    }
    
    //商品数量によりコメントを変えます。
    Statement lStatement=null;
    ResultSet lResultSet=null;
    
    StringBuffer lSqlBuf=new StringBuffer();
    if (SIDBMultiConf.SIDB_CURRENT_INX ==SIDBMultiConf.SIDB_POSTGRESQL_INX){
      lSqlBuf.append("SELECT  CASE WHEN ((aa.subtotal + (").append(this.getAmount()).append(")::numeric ) = (0)::numeric )");
      lSqlBuf.append(" THEN bb.commentofnostock  ");
      lSqlBuf.append(" WHEN ((aa.subtotal +( ").append(this.getAmount()).append(")::numeric ) <= bb.amountoflessstock) ");
    }else{
      lSqlBuf.append("SELECT  CASE WHEN ((aa.subtotal + ").append(this.getAmount()).append(" ) = 0 )");
      lSqlBuf.append(" THEN bb.commentofnostock  ");
      lSqlBuf.append(" WHEN ((aa.subtotal + ").append(this.getAmount()).append(" ) <= bb.amountoflessstock) ");
    }
    lSqlBuf.append(" THEN bb.commentoflessstock ELSE bb.commentofmorestock END AS commentofstock ");
    lSqlBuf.append(" FROM cmdtyVW").append(SIDBMultiConf.SIALIAS_CURR_NAME).append("aa,");
    lSqlBuf.append("stockstatusmtbl").append(SIDBMultiConf.SIALIAS_CURR_NAME).append("bb ");
    lSqlBuf.append(" WHERE  bb.stockstatuscode =").append(SIDBUtil.SQL2Str(this.getStockStatusCode()," "));
    lSqlBuf.append(" AND aa.ShopCode=").append(SIDBUtil.SQL2Str(this.getShopCode()," "));
    lSqlBuf.append(" AND aa.CmdtyCode=").append(SIDBUtil.SQL2Str(this.getCmdtyCode()," "));
    log.debug("reset:lSqlBuf="+lSqlBuf.toString());
    try {
      lStatement=lConnection.createStatement();
      lResultSet=lStatement.executeQuery(lSqlBuf.toString());
      
      if (lResultSet.next()){
        this.setEncode(SIConfig.SIENCODE_NONE);
        this.setCommentOfStock(lResultSet.getString("commentOfStock"));//在庫状況コメント
      }else{
        log.error("not find record for cmdtyCode="+getCmdtyCode());
      }
    }catch(SQLException sqle){
      sqle.printStackTrace();
    }finally{
      SIDBUtil.close(lStatement,lResultSet);
    }
  }
}
