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

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedHashMap;

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.SICartManager;
import jp.co.sint.basic.SILogin;
import jp.co.sint.basic.SIOrderDetail;
import jp.co.sint.beans.mallmgr.UIRegOrderShipment;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.servlet.SIServlet;
import jp.co.sint.tools.SICustomError;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIURLParameter;

import org.apache.log4j.Category;

/**
 * @version $Id: SIRegOrderShipmentSrv,v 1.0 2004/09/24 Exp $
 * @author  Yagi Tsuyoshi
 * <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>
 * Yagi Tsuyoshi    2005/09/07   Original
 */
public class SIRegOrderShipmentSrv 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 {
    //ログイン情報の取得・チェック
    SILogin manLogin = SIHTMLUtil.getLogin(request);
    if (!manLogin.isLogin()) {
      forwardKey(request, response, "webshop.jsp.manager.login");
      return;
    }

    HttpSession    session  = request.getSession(true);                   //セッションの取得
    SIURLParameter urlParam = new SIURLParameter(request);                //URLパラメータ
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection(); //DBへのコネクションの作成

    try {
      Connection connection = databaseConnection.getConnection();

      String actionName = this.getActionName(urlParam); //画面からのアクション
      String editMode   = this.getEditMode(urlParam);   //DBへの編集モード
      
      LinkedHashMap allocateMap = (LinkedHashMap)session.getAttribute(SIConfig.SISESSION_MAN_ORDER_ALLOCATION);
      if(allocateMap==null){
        allocateMap=new LinkedHashMap();
      }
      
      log.debug("doUpdate:actionName="+actionName);
      if(SIConfig.SIACTION_MODIFY.equals(actionName)){
        UIRegOrderShipment shipment = new UIRegOrderShipment();
        shipment.init(request,urlParam);
        shipment.validate(request,connection);
        session.setAttribute(SIConfig.SISESSION_MAN_ORDER_SHIPMENT,shipment);
        forwardKey(request, response, "webshop.jsp.manager.order.shipment");
      }else if(SIConfig.SIACTION_REGIST.equals(actionName)){
        UIRegOrderShipment shipment = new UIRegOrderShipment();
        shipment.init(request,urlParam);
        shipment.validate(request,connection);
        session.setAttribute(SIConfig.SISESSION_MAN_ORDER_SHIPMENT,shipment);
        if(request.getAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY)==null){
          LinkedHashMap map=shipment.setMap();
          // EDBTG003-00 elecs-matsushima mod start
//          allocateMap.put(shipment.getOrderCode()+"_"+shipment.getCmdtyCode()+"_"+shipment.getIndividualCode(),map);
          allocateMap.put(shipment.getOrderCode()+"_"+shipment.getCmdtyCode()+"_"+shipment.getIndividualCode()+"_"+shipment.getSetCode()+"_"+shipment.getSetDetailFlg(),map);
          setSessionAllocationDataTest(request, connection, allocateMap, shipment);
          // EDBTG003-00 elecs-matsushima mod end
          session.setAttribute(SIConfig.SISESSION_MAN_ORDER_ALLOCATION,allocateMap);
          SICustomErrors errors = new SICustomErrors();
          errors.addError((new SICustomError("manager.message.success.allocation")));
          request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
        }
        session.setAttribute(SIConfig.SISESSION_MAN_ORDER_SHIPMENT,shipment);
        forwardKey(request, response, "webshop.jsp.manager.order.shipment");
      }
    } catch (SQLException e) {
      e.printStackTrace();
      throw new ServletException();
    } catch (NamingException e) {
      e.printStackTrace();
      throw new ServletException();
    } finally {
      databaseConnection.close();
    }
  }

  //EDBTG003-00 elecs-matsushima add start
  private void setSessionAllocationDataTest(HttpServletRequest request, Connection lConnection, LinkedHashMap allocateMap, UIRegOrderShipment shipment){
    
    HttpSession session = request.getSession(true);
    
    if (allocateMap != null){
      for (Iterator iteAllocateMap = allocateMap.keySet().iterator(); iteAllocateMap.hasNext();){
        String mapKeyName = (String) iteAllocateMap.next();
        LinkedHashMap map = (LinkedHashMap) allocateMap.get(mapKeyName);
        
        if (map != null) {
          String[] mapKey = mapKeyName.split("_");
          
          LinkedHashMap cartDetailMap = (LinkedHashMap) session.getAttribute(SIConfig.SISESSION_CART_DETAIL_NAME);
          SIOrderDetail lOrderDetail = new SIOrderDetail();
          LinkedHashMap newDetailMap = new LinkedHashMap();
          
          for (Iterator iteCartDetailMap = cartDetailMap.keySet().iterator();iteCartDetailMap.hasNext(); ){
            String cartDetailKey = (String) iteCartDetailMap.next();
            lOrderDetail = (SIOrderDetail) cartDetailMap.get(cartDetailKey);
            
            // 同一情報であれば
            if (shipment.getOrderCode().equals(mapKey[0]) &&
                lOrderDetail.getCmdtyCode().equals(mapKey[1]) &&
                lOrderDetail.getIndividualCode().equals(mapKey[2]) &&
                lOrderDetail.getSetCode().equals(mapKey[3]) &&
                lOrderDetail.getSetDetailFlg().equals(mapKey[4])
            ){
              lOrderDetail.setAllocationMap(map);
            }
            newDetailMap.put(cartDetailKey, lOrderDetail);
          }
          session.setAttribute(SIConfig.SISESSION_CART_DETAIL_NAME, newDetailMap);
        }
      }
      if (allocateMap.size() > 0) {
        SICartManager cartMan=new SICartManager();
        cartMan.adjustAmount(request,lConnection);
        session.setAttribute(SIConfig.SISESSION_CART_INFO_NAME,cartMan);
      }
    }
  }
  
  private LinkedHashMap getAllocationData(String lOrderCode, HttpSession session){
    LinkedHashMap cartDetailMap = (LinkedHashMap) session.getAttribute(SIConfig.SISESSION_CART_DETAIL_NAME);
    LinkedHashMap allocationMap = new LinkedHashMap();
    
    if (cartDetailMap != null){
      SIOrderDetail lOrderDetail = new SIOrderDetail();
      
      for (Iterator iteCartDetailMap = cartDetailMap.keySet().iterator();iteCartDetailMap.hasNext(); ){
        String cartDetailKey = (String) iteCartDetailMap.next();
        lOrderDetail = (SIOrderDetail) cartDetailMap.get(cartDetailKey);
        
        if (lOrderDetail.getAllocationMap() != null && lOrderDetail.getAllocationMap().size() > 0){
          allocationMap.put(lOrderCode+"_"+lOrderDetail.getCmdtyCode()+"_"+lOrderDetail.getIndividualCode()+"_"+lOrderDetail.getSetCode()+"_"+lOrderDetail.getSetDetailFlg(), lOrderDetail.getAllocationMap());
        }
      }
    }
    return allocationMap;
  }
  //EDBTG003-00 elecs-matsushima add end
}
