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

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jp.co.sint.basic.SICartDetail;
import jp.co.sint.basic.SICartManager;
import jp.co.sint.basic.SIReserveCartManager;
import jp.co.sint.basic.SIUserInfo;
import jp.co.sint.beans.front.UICasher;
import jp.co.sint.beans.front.UICatalogCmdty;
import jp.co.sint.beans.mobile.vod.UIVCart;
import jp.co.sint.beans.mobile.vod.UIVCasher;
import jp.co.sint.beans.mobile.vod.UIVOrderCounter;
import jp.co.sint.beans.mobile.vod.UIVCasher;
import jp.co.sint.beans.mobile.vod.UIVOrderCounter;
import jp.co.sint.bscvsmdk.SIBSCVSMDKException;//7.2.0 ST0300 追加
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.database.SIDuplicateKeyException;
import jp.co.sint.mdk.SIMDKAction3G;
//import jp.co.sint.mdk.SIMDKAction;//7.2.0 ST0300 追加
import jp.co.sint.servlet.SIServlet;
import jp.co.sint.servlet.front.SICartSrv;
import jp.co.sint.tools.SICustomError;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIDebtPointException;//7.2.0 ST0296
import jp.co.sint.tools.SIErrorException;
import jp.co.sint.tools.SIFatalException;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIMismatchException;
import jp.co.sint.tools.SIURLMap;
import jp.co.sint.tools.SIUtil;

import org.apache.log4j.Category;
import jp.co.sint.tools.SIURLParameter;//7.1.1 ST0236 追加

/**
 * @version $Id: SIVCartSrv.java,v 1.0 2003/12/25 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/12/25 14:25:29  Original
 */
public class SIVCartSrv extends SIServlet{
  //ログ用のインスタンスの生成
  private static Category log=Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);

  /**
   * <b>doUpdate</b>
   * HTTP リクエストの処理
   * @param  request リクエスト
   * @param  response
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void doUpdate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
      HttpSession session=request.getSession(true);//セッションの取得
      SIDatabaseConnection databaseConnection=new SIDatabaseConnection();//DBへのコネクションの作成
      SIURLParameter urlParam = new SIURLParameter(request);//7.1.1 ST0236 追加
      
      try {
        String actionName=this.getActionName(urlParam);//画面からのアクション //7.1.1 ST0236 修正
        String editMode=this.getEditMode(urlParam);//DBへの編集モード  //7.1.1 ST0236 修正
        
        if (this.getServletPath(request).equals("/mobile/v/cart")){//カート
          if (SIConfig.SIACTION_DELETE.equals(actionName)){//カートから全商品の削除
            try{
              SIReserveCartManager.cancel(request,databaseConnection.getConnection());
              databaseConnection.getConnection().commit();
              SIReserveCartManager.clear(request);
            }catch(Exception e){
              e.printStackTrace();
            }
            SICartManager.clear(request);
          } else if (SIConfig.SIACTION_MODIFY.equals(actionName)) {
            UIVCart cart=new UIVCart();
            cart.init(request, urlParam);
            cart.validate(request, databaseConnection.getConnection());
            session.setAttribute(SIConfig.SISESSION_CART_EDIT_NAME, cart);
          }
          forwardKey(request,response,"webshop.jsp.front.vod.cart");
        }else if (this.getServletPath(request).equals("/mobile/v/counter")){//レジ（配送先・支払方法）
          if (SIUtil.isNull(actionName)){//レジ（配送先・支払方法）
            //7.1.1 ST0204 修正 ここから
            UIVOrderCounter orderCounter=new UIVOrderCounter();
            
            SIUserInfo lUserInfo=SIHTMLUtil.getUserInfo(request);
            if (lUserInfo.isNotLogin(request)){//ログインしなければ、ログインへ
              orderCounter.setShopCode((String)urlParam.getParam("shc"));//7.1.1 ST0236 修正
              String lUrl=SIURLMap.getUrl("webshop.servlet.front.vod.login")+"?nid="+SIHTMLUtil.URLEncode(SIURLMap.getUrl("webshop.servlet.front.vod.counter"));
              if (SIUtil.isNotNull(orderCounter.getShopCode())){
                lUrl=lUrl+"?shc="+orderCounter.getShopCode();
              }
              redirectHttps(request,response,lUrl);
            }else{
              SICartDetail.reset(request,databaseConnection.getConnection());
              orderCounter.init(request,databaseConnection.getConnection(),urlParam);//決済のショップコードの取得
              //7.1.1 ST0204 修正 ここまで
              session.setAttribute(SIConfig.SISESSION_V_ORDER_COUNTER_NAME,orderCounter);
              forwardKey(request,response,"webshop.jsp.front.vod.counter");
            }
          }else if (SIConfig.SIACTION_BACK.equals(actionName)){//戻る
            redirectHttpsKey(request,response,"webshop.jsp.front.vod.counter");//7.2.0 ST0274 修正
          }
        }else if (this.getServletPath(request).equals("/mobile/v/casher")||this.getServletPath(request).equals("/mobile/v/thanks")){//レジ
          if (SIUtil.isNull(actionName)){//配送先の選択から
            UIVCasher lCasher=new UIVCasher();
            lCasher.initAddress(request,urlParam);//7.1.1 ST0236 修正
            if (lCasher.validateAddress(request,databaseConnection.getConnection(),urlParam)){//7.1.1 ST0236 修正
              session.setAttribute(SIConfig.SISESSION_CASHER_NAME,lCasher);
              forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
            }else{
              forwardKey(request,response,"webshop.jsp.front.vod.counter");
            }
          }else if (SIConfig.SIACTION_CONFIRM.equals(actionName)){//確認画面 或いは、再計算
            UIVCasher lCasher=new UIVCasher();
            String pressed=this.getParameter(urlParam,"actionBtn");//7.1.1 ST0236 修正
            lCasher.init(request,databaseConnection.getConnection(),urlParam);//7.1.1 ST0236 修正
            //lCasher.setOrderRoute("6");//受注経路:携帯 BG-MOBILEテスト 追加
            SICartDetail.resetDelivery(request,databaseConnection.getConnection(),request.getParameter("addressNo"),true);
            
            if (pressed.equals("再計算")){
              lCasher.validateRedo(request);
              session.setAttribute(SIConfig.SISESSION_CASHER_NAME,lCasher);
              forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
            }else if (lCasher.validate(request,databaseConnection.getConnection(),true)){//7.1.1 ST0154 修正
              lCasher.setChecked(true);//7.1.2 ST0287 追加
              session.setAttribute(SIConfig.SISESSION_CASHER_NAME,lCasher);
              forwardKey(request,response,"webshop.jsp.front.vod.casher.confirm");
            }else {
              lCasher.setChecked(false);//7.1.2 ST0287 追加
              session.setAttribute(SIConfig.SISESSION_CASHER_NAME,lCasher);
              forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
            }
          }else if (SIConfig.SIACTION_BACK.equals(actionName)){//戻る
            forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
          }else if (SIConfig.SIACTION_REGIST.equals(actionName)){//DBへの登録
            //7.2.0 ST0287 追加 ここから
            UICasher lCasherID=(UICasher)session.getAttribute(SIConfig.SISESSION_CASHER_NAME);
            if (lCasherID==null||SICartDetail.isEmpty(request,lCasherID.getShopCode())){
              redirect(request,response,SIURLMap.getUrl("webshop.servlet.front.vod.main"));
            }else if (lCasherID.getChecked()==false){
              SICustomErrors errors=new SICustomErrors();
              errors.addError(new SICustomError("input.casher.confirm"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
              forwardKey(request,response,"webshop.jsp.front.vod.casher.main");//編集画面へ
            }else if (lCasherID.validate(request,databaseConnection.getConnection(),true)==false){
              forwardKey(request,response,"webshop.jsp.front.vod.casher.main");//編集画面へ
            }else{
            //7.2.0 ST0287 追加 ここまで
              //7.2.0 ST0296 追加ここから
              String lPointManCode ="";
              try {
                lPointManCode = SICartSrv.insertPointTableData(request, databaseConnection.getConnection());
                try {databaseConnection.getConnection().commit();}catch(SQLException sqle){}
              } catch (SIDuplicateKeyException e1) {
                e1.printStackTrace();
              } catch (SIDBAccessException e1) {
                e1.printStackTrace();
              }
              //7.2.0 ST0296 追加ここまで
              try {
                SICartSrv.RLockForOrderStock(request, databaseConnection.getConnection());//7.2.0 ST0297追加
                SICartSrv.insertOrderTableData(request,databaseConnection.getConnection(),lPointManCode);//7.2.0 ST0296修正
                //顧客ポイントの更新
                SIUserInfo lUserInfo=SIHTMLUtil.getUserInfo(request);
                lUserInfo.reset(databaseConnection.getConnection(),lUserInfo.getEmail());
                session.setAttribute(SIConfig.SISESSION_USERINFO_NAME,lUserInfo);
                try {databaseConnection.getConnection().commit();}catch(SQLException sqle){}
                if (SIConfig.SIRUNNING_MODE_CURRENT==SIConfig.SIRUNNING_MODE_TOGETHER){
                  SIReserveCartManager.clear(request);
                  SICartManager.clear(request);
                }else{
                  UICasher lCasher=(UICasher)session.getAttribute(SIConfig.SISESSION_CASHER_NAME);
                  if (lCasher==null)lCasher=new UICasher();
                  SICartManager.clear(request,lCasher.getCasherShopCode());
                  SIReserveCartManager.clear(request,lCasher.getCasherShopCode());
                }
                forwardKey(request,response,"webshop.jsp.front.vod.casher.result");
              }catch(SIDuplicateKeyException sqle){
                try {databaseConnection.getConnection().rollback();}catch(SQLException ee){}
                //7.2.0 ST0296 追加ここから
                SICartSrv.deletePointTableData(request,databaseConnection.getConnection(),lPointManCode);
                try {databaseConnection.getConnection().commit();}catch(SQLException ee){}
                //7.2.0 ST0296 追加ここまで
                SICustomErrors errors=new SICustomErrors();
                errors.addError(new SICustomError("database.insert.duplicate"));
                request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
                SIMDKAction3G.cancelByFailuer(request);//7.1.1 ST0211 追加
                //SIMDKAction.cancelByFailuer(request);//7.1.1 ST0211 追加
                forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
              }catch(SIDBAccessException sqle){
                try {databaseConnection.getConnection().rollback();}catch(SQLException ee){}
                //7.2.0 ST0296 追加ここから
                SICartSrv.deletePointTableData(request,databaseConnection.getConnection(),lPointManCode);
                try {databaseConnection.getConnection().commit();}catch(SQLException ee){}
                //7.2.0 ST0296 追加ここまで
                SICustomErrors errors=new SICustomErrors();
                errors.addError(new SICustomError("database.execute.error"));
                request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
                SIMDKAction3G.cancelByFailuer(request);//7.1.1 ST0211 追加
                //SIMDKAction.cancelByFailuer(request);//7.1.1 ST0211 追加
                forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
              }catch(SIMismatchException e){
                e.printStackTrace();
                try {databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
                //7.2.0 ST0296 追加ここから
                SICartSrv.deletePointTableData(request,databaseConnection.getConnection(),lPointManCode);
                try {databaseConnection.getConnection().commit();}catch(SQLException ee){}
                //7.2.0 ST0296 追加ここまで
                SICustomErrors errors=new SICustomErrors();
                errors.addError(new SICustomError("manager.app.price.mismatch"));
                request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
                SIMDKAction3G.cancelByFailuer(request);//7.1.1 ST0211 追加
                //SIMDKAction.cancelByFailuer(request);//7.1.1 ST0211 追加
                forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
              }catch(SIErrorException e){
                e.printStackTrace();
                try {databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
                //7.2.0 ST0296 追加ここから
                SICartSrv.deletePointTableData(request,databaseConnection.getConnection(),lPointManCode);
                try {databaseConnection.getConnection().commit();}catch(SQLException ee){}
                //7.2.0 ST0296 追加ここまで
                SICustomErrors errors=new SICustomErrors();
                errors.addError(new SICustomError("manager.app.card.error"));
                request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
                SIMDKAction3G.cancelByFailuer(request);//7.1.1 ST0211 追加
                //SIMDKAction.cancelByFailuer(request);//7.1.1 ST0211 追加
                forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
              }catch(SIFatalException e){
                e.printStackTrace();
                try {databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
                //7.2.0 ST0296 追加ここから
                SICartSrv.deletePointTableData(request,databaseConnection.getConnection(),lPointManCode);
                try {databaseConnection.getConnection().commit();}catch(SQLException ee){}
                //7.2.0 ST0296 追加ここまで
                //7.1.1 ST0211 修正 ここから
                SIMDKAction3G.cancelByFailuer(request);
                //SIMDKAction.cancelByFailuer(request);
                forwardKey(request,response,"webshop.jsp.front.vod.cart");
                //7.1.1 ST0211 修正 ここまで
                //7.2.0 ST0296 追加ここから
              }catch(SIDebtPointException e){
                e.printStackTrace();
                try {databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
                SICartSrv.deletePointTableData(request,databaseConnection.getConnection(),lPointManCode);
                try {databaseConnection.getConnection().commit();}catch(SQLException sqle){}
                SICustomErrors errors=new SICustomErrors();
                errors.addError(new SICustomError("input.data.less","ポイント使用額","ポイント残高"));
                request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
                forwardKey(request,response,"webshop.jsp.front.vod.casher.main");
                //7.2.0 ST0296 追加ここまで
              }
              //7.2.0 ST0300 追加 ここから
              catch (SIBSCVSMDKException e) {
                e.printStackTrace();
                try {databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
                SICartSrv.deletePointTableData(request,databaseConnection.getConnection(),lPointManCode);
                try {databaseConnection.getConnection().commit();}catch(SQLException ee){}
                SICustomErrors errors=new SICustomErrors();
                errors.addError(new SICustomError("manager.app.cvs.error"));
                request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
                SIMDKAction3G.cancelByFailuer(request);
                //SIMDKAction.cancelByFailuer(request);
                forwardKey(request, response, "webshop.jsp.front.vod.casher.main");
              }
              //7.2.0 ST0300 追加 ここまで
            }//7.2.0 ST0287 追加
          }
        } else if (this.getServletPath(request).equals("/mobile/v/catalog")) {
          if (SIUtil.isNull(actionName)) {
            UICatalogCmdty cmdtys = new UICatalogCmdty(true);
            session.setAttribute(SIConfig.SISESSION_V_CATALOG_CARTIN_NAME, cmdtys);
            forwardKey(request, response, "webshop.jsp.front.vod.catalog.cartin");
          } else if (actionName.equals(SIConfig.SIACTION_CART)) {
            UICatalogCmdty cmdtys = new UICatalogCmdty(true);
            cmdtys.init(request);
            
            if (cmdtys.validate(request, databaseConnection.getConnection())) {
              cmdtys.addCart(request, databaseConnection.getConnection());
              session.setAttribute(SIConfig.SISESSION_V_CATALOG_CARTIN_NAME, new UICatalogCmdty(true));
              forwardKey(request, response, "webshop.jsp.front.vod.cart");
            } else {
              session.setAttribute(SIConfig.SISESSION_V_CATALOG_CARTIN_NAME, cmdtys);
              forwardKey(request, response, "webshop.jsp.front.vod.catalog.cartin");
            }
          }
        }
      }catch (SQLException e){
        e.printStackTrace();
        throw new ServletException();
      }catch (NamingException e){
        e.printStackTrace();
        throw new ServletException();
      }finally{
        databaseConnection.close();
      }
    }
}
