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

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jp.co.sint.basic.SICart;
import jp.co.sint.basic.SICartCmdty;
import jp.co.sint.basic.SICartManager;
import jp.co.sint.basic.SIFrontBasic;
import jp.co.sint.basic.SIMallShop;
import jp.co.sint.basic.SIReserveCartManager;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIModifyRec;
import jp.co.sint.tools.SIBGUtil;
import jp.co.sint.tools.SICheckDataConf;
import jp.co.sint.tools.SICheckUtil;
import jp.co.sint.tools.SICheckValid;
import jp.co.sint.tools.SICustomError;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIStringUtil;
import jp.co.sint.tools.SIUtil;
import jp.co.sint.tools.SIURLParameter;//7.1.1 ST0236 追加

import org.apache.log4j.Category;

/**
 * @version $Id: UICart.java,v 1.0 2003/11/17 Exp $
 * @author  Jinwang Chen
 * <br>Description:
 * <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>
 * Jinwang Chen   2003/11/17 17:10:42  Original
 */
public class UICart extends SIFrontBasic{
  //ログ用のインスタンスの生成
  private static Category log=Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);
  
  //ショップコード
  private String shopCode="";
  
  private HashMap amountMap=new HashMap();
  
  public UICart(){}
  
  public void setShopCode(String lShopCode){
    if (SIUtil.isNull(lShopCode)) lShopCode="";
    this.shopCode=SIUtil.changeTo(lShopCode.trim(),this.encode);
  }
  
  private void setAmount(String lName,String lValue){
    lValue=SIUtil.str2Int(lValue);//7.1.1 ST0177 修正
    if (SIUtil.isNull(lName)) return;
    if (SIUtil.isNull(lValue)) lValue="";
    else lValue=SIUtil.changeTo(lValue.trim(),this.encode);
    amountMap.put(lName,lValue);
  }
  
  // EDBTG003-00 nagayoshi add start
//  public void setAmount(HttpServletRequest lRequest,SIURLParameter lUrlParam) {
//    setAmount(lRequest, lUrlParam, false);
//  }
  // EDBTG003-00 nagayoshi add end
  
  //7.1.1 ST0236 修正 ここから
  // EDBTG003-00 nagayoshi mod start
//  public void setAmount(HttpServletRequest lRequest,SIURLParameter lUrlParam) {
  public void setAmount(HttpServletRequest lRequest,SIURLParameter lUrlParam, String lModifyRow) {
  // EDBTG003-00 nagayoshi mod end
    amountMap=new HashMap();
    Enumeration lAmountNameEnum=lRequest.getParameterNames();
    String lAmountName="";
    String lAmountValue="";
    
    while (lAmountNameEnum.hasMoreElements()){
      lAmountName=(String)lAmountNameEnum.nextElement();
      // EDBTG003-00 nagayoshi mod start
//      if (lAmountName.startsWith(shopCode+SIConfig.SIWEBSHOPPING_TOKEN)){
//        lAmountValue=(String)lUrlParam.getParam(lAmountName);
//        setAmount(lAmountName,lAmountValue);
//      }
      if (SIUtil.isNull(lModifyRow)) {
        if (lAmountName.startsWith(shopCode+SIConfig.SIWEBSHOPPING_TOKEN)){
          lAmountValue=(String)lUrlParam.getParam(lAmountName);
          setAmount(lAmountName,lAmountValue);
        }
      } else {
        if (lAmountName.startsWith(shopCode+SIConfig.SIWEBSHOPPING_TOKEN)
            && lModifyRow.equals(lAmountName)){
          lAmountValue=(String)lUrlParam.getParam(lAmountName);
          setAmount(lAmountName,lAmountValue);
        }
      }
      // EDBTG003-00 nagayoshi mod end
    }
  }
  //7.1.1 ST0236 修正 ここまで
  
  public void setAmount0(String lName,String lValue){
    lValue=SIUtil.str2Int(lValue);//7.1.1 ST0177 修正
    if (SIUtil.isNull(lName)) return;
    if (SIUtil.isNull(lValue)) lValue="";
    else lValue=SIUtil.changeTo(lValue.trim(),this.encode);
    amountMap.put(lName,lValue);
  }
  
  public String getShopCode(){
    return this.shopCode;
  }
  
  /**
   *
   * @param lAmountName
   * @return
   */
  public String getAmount(String lAmountName){
    if (amountMap==null) return "";
    String lAmount=(String)amountMap.get(lAmountName);
    if (SIUtil.isNull(lAmount)) return "";
    else return lAmount;
  }
  
  // EDBTG003-00 nagayoshi add start
  public void init(HttpServletRequest lRequest,SIURLParameter lUrlParam) {
    init(lRequest, lUrlParam, "");
  }
  //EDBTG003-00 nagayoshi add end
  
  /**
   *
   */
  //7.1.1 ST0236 修正 ここから
  // EDBTG003-00 nagayoshi mod start
//  public void init(HttpServletRequest lRequest,SIURLParameter lUrlParam){
  public void init(HttpServletRequest lRequest,SIURLParameter lUrlParam, String lModifyRow){
  // EDBTG003-00 nagayoshi mod end
    this.setEncode(SIConfig.SIENCODE_SHIFT_JIS);
    super.init(lRequest,lUrlParam);
    setShopCode((String)lUrlParam.getParam("shopCode"));
// EDBTG003-00 nagayoshi mod start
//    setAmount(lRequest, lUrlParam);
    setAmount(lRequest, lUrlParam, lModifyRow);
// EDBTG003-00 nagayoshi mod end
  }
  //7.1.1 ST0236 修正 ここまで
  
  /**
   *
   * @param lRequest
   * @param lConnection
   * @return boolean
   */
  public boolean validate(HttpServletRequest lRequest, Connection lConnection){
    HttpSession session=lRequest.getSession(true);//セッションの取得
    SICartManager cartMan=(SICartManager)session.getAttribute(SIConfig.SISESSION_CART_INFO_NAME);
    if (cartMan==null)cartMan=new SICartManager();
    SICartCmdty lCartCmdty=new SICartCmdty();
    
    SIReserveCartManager lRsrCartManager=(SIReserveCartManager)session.getAttribute(SIConfig.SISESSION_RESERVE_CART_INFO_NAME);
    if (lRsrCartManager==null)lRsrCartManager=new SIReserveCartManager();
    Iterator lRsrIta=lRsrCartManager.getReserveCodes().keySet().iterator();
    int hCount=lRsrCartManager.getReserveCodes().size();
    int dCount=0;
    String lCode="";
    String[][] cmdtyList =new String[hCount][2];
    while (lRsrIta.hasNext()){
      lCode=(String)lRsrIta.next();
      cmdtyList[dCount][0]=lCode;
      try{cmdtyList[dCount][1]=SIBGUtil.getReserveCmdty(lCode,lConnection);}
      catch(Exception e){e.printStackTrace();}
      dCount++;
    }
    
    SICustomErrors errors = new SICustomErrors();
    Iterator amountIta=amountMap.keySet().iterator();
    String lAmountName="";
    String lAmountValue="";
    String lReserveAmountValue="";
    String[] lShopCmdtyCode={"",""};
    String lResValid="";
    boolean[] lRes={false,false};//7.1.1 ST0185 追加
    
    // EDBTG003-00 nagayoshi mod start
    // 現在のセット品の各構成品在庫数をサマリ
    LinkedHashMap amountCmdtyMap = new LinkedHashMap();
    // EDBTG003-00 nagayoshi mod end
    
    while (amountIta.hasNext()){
      lAmountName=(String)amountIta.next();
      lAmountValue=(String)amountMap.get(lAmountName);
      
      lResValid=SICheckValid.checkValid("数量",lAmountValue,SICheckDataConf.SICHECK_DATA_EMPTY_TYPE+SICheckDataConf.SICHECK_DATA_DIGIT_TYPE);//7.1.1 ST0185 修正
      if (SIUtil.isNull(lResValid)){
        lShopCmdtyCode=SIStringUtil.split(lAmountName,SIConfig.SIWEBSHOPPING_TOKEN);
        // EDBTG003-00 nagayoshi mod start
//        if (lShopCmdtyCode.length==7){
        if (lShopCmdtyCode.length==8){
        // EDBTG003-00 nagayoshi mod end
          lCartCmdty=new SICartCmdty();
          lCartCmdty.setEncode(SIConfig.SIENCODE_NONE);
          lCartCmdty.setShopCode(lShopCmdtyCode[0]);
          lCartCmdty.setCmdtyCode(lShopCmdtyCode[1]);
          lCartCmdty.setIndividualCode(lShopCmdtyCode[2]);
          lCartCmdty.setStndrdCode1(lShopCmdtyCode[3]);
          lCartCmdty.setElementCode1(lShopCmdtyCode[4]);
          lCartCmdty.setStndrdCode2(lShopCmdtyCode[5]);
          lCartCmdty.setElementCode2(lShopCmdtyCode[6]);
          //7.1.1 ST0211 修正 ここから
          if (!lCartCmdty.reset(lConnection,true)){
            errors.addError(new SICustomError("manager.app.sale.expired"));
            continue;
          }
          //7.1.1 ST0211 修正 ここまで
          
          lReserveAmountValue=SIReserveCartManager.getAmount(lRequest,
                                                             lCartCmdty.getShopCode(),
                                                             lCartCmdty.getCmdtyCode(),
                                                             lCartCmdty.getIndividualCode(),
                                                             lCartCmdty.getStndrdCode1(),
                                                             lCartCmdty.getElementCode1(),
                                                             lCartCmdty.getStndrdCode2(),
                                                             lCartCmdty.getElementCode2());
          log.debug("lCartCmdty.getCmdtyCode()="+lCartCmdty.getCmdtyCode()+",lCartCmdty.getAmountFlg()="+lCartCmdty.getAmountFlg());
          if (SICheckUtil.isLess(lAmountValue,lReserveAmountValue)&&!lAmountValue.equals("0")&&!lReserveAmountValue.equals("0")&&!lAmountValue.equals(lReserveAmountValue)){
            errors.addError(new SICustomError("input.data.greater",lCartCmdty.getCartCmdtyName()+"に対して変更後の数量","予約商品の数量("+lReserveAmountValue+")"));
          }else if (lCartCmdty.getAmountFlg().equals("1")&&lCartCmdty.isExceedAmount(SIUtil.sub_LD(lAmountValue,lReserveAmountValue))) {
            //7.1.1 ST0211 修正 ここから
            if (Integer.parseInt(lReserveAmountValue)>0)errors.addError(new SICustomError("manager.app.exceed.amount.with.reserve",lCartCmdty.getCartCmdtyName()));
            else if (Integer.parseInt(lCartCmdty.getAmount())<=0) errors.addError(new SICustomError("manager.app.exceed.amount.no.reserve",lCartCmdty.getCartCmdtyName()));
            else errors.addError(new SICustomError("manager.app.exceed.amount.with.cancel",lCartCmdty.getCartCmdtyName()));
            //7.1.1 ST0211 修正 ここまで
            // EDBTG003-00 nagayoshi mod start
//          }else cartMan.update(lCartCmdty,lAmountValue);
          } else {
            if (lCartCmdty.isCmdtyComposition()) {
              SICustomErrors errorsAmount = this.checkModSetAmount(lConnection, cartMan, lShopCmdtyCode, amountCmdtyMap, lAmountValue);
              // EDBTG003-00 [不具合管理票-No25] 2013/03/14 nagayoshi mod start
              if (errorsAmount.getErrorList() != null) {
                Iterator ite = errorsAmount.getErrorList().iterator();
                while(ite.hasNext()) {
                  SICustomError map = (SICustomError)ite.next();
                  errors.addError(new SICustomError(map.getErrorKey(),map.getParamList()));
                }
              }
              // EDBTG003-00 [不具合管理票-No25] 2013/03/14 nagayoshi mod end
            } else {
              // 通常品の場合
              cartMan.update(lCartCmdty,lAmountValue);
            }
            // EDBTG003-00 nagayoshi mod end
          }
          //
          if(lAmountValue.equals("0")&&!lReserveAmountValue.equals("0")){
              SIModifyRec lRec = new SIModifyRec();
              String lReserveCode="";
              String lReserveCmdty="0~"+lCartCmdty.getCmdtyCode()+"~"+lCartCmdty.getIndividualCode()+"~~~~";
              try{
                for(int i=0;i<dCount;i++){
                  if(cmdtyList[i][1].equals(lReserveCmdty)){ 
                    lReserveCode=cmdtyList[i][0];
                    log.debug("cancel:lReserveCode="+lReserveCode);
                    lRec=new SIModifyRec("ReserveOrderTbl");
                    lRec.addCondition("ReserveCode",lReserveCode);
                    lRec.add("ReserveFlg","1");
                    lRsrCartManager.delete(lRequest,lReserveCmdty,lReserveCode);
                  }
                  lRec.execute(lConnection);
                }
                lConnection.commit();
              }catch(Exception e){
                e.printStackTrace();
              }
            }
        }
      //7.1.1 ST0185 修正 ここから
      }else if ((errors.isEmpty()||!lRes[0])&&SIUtil.isNull(lAmountValue)){
        lRes[0]=true;
        errors.addError(new SICustomError("input.data.require","数量"));
      }else if (errors.isEmpty()||!lRes[1]){
        lRes[1]=true;
      //7.1.1 ST0185 修正 ここまで
        errors.addError(new SICustomError("input.data.digit","数量"));
      }
    }
    session.setAttribute(SIConfig.SISESSION_CART_INFO_NAME,cartMan);
    SICartManager.clearCasher(lRequest);//7.1.1 ST0154 追加
    if (!errors.isEmpty())lRequest.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
    else lRequest.removeAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY);
    return errors.isEmpty();
  }
}