/**
 * Copyright (c) 2003-2006 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 javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Category;

import jp.co.sint.basic.SILogin;
import jp.co.sint.beans.mallmgr.UIInventoryDifference;
import jp.co.sint.beans.mallmgr.UIInventoryDiffListCond;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDBUtil;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.database.SIDuplicateKeyException;
import jp.co.sint.database.SIInsertRec;
import jp.co.sint.database.SIModifyRec;
import jp.co.sint.database.SISpcType;
import jp.co.sint.servlet.SIServlet;
import jp.co.sint.tools.SICustomError;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIDateTime;
import jp.co.sint.tools.SIErrorFactory;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIURLParameter;
import jp.co.sint.tools.SIUtil;

/**
 * @version $Id: SIInventorySrv.java,v 1.0 2006/05/29 Exp $
 * @author  Hong.M.J
 * <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>
 * Hong.M.J        2006/05/29 11:06:28  Original
 */
public class SIInventorySrv extends SIServlet {
//  ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);

  /**
   * <b>doUpdate</b> HTTP リクエストの処理
   * 
   * @param なし
   * @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);//セッションの取得
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection();//DBへのコネクションの作成
    SIURLParameter urlParam = new SIURLParameter(request);
    try{
      Connection conn = databaseConnection.getConnection();
      String actionName = this.getActionName(urlParam);//画面からのアクション
      
      if (actionName.equals(SIConfig.SIACTION_LIST)) {//棚卸差異データ検索
        UIInventoryDiffListCond inventoryDiffListID = new UIInventoryDiffListCond(request,urlParam);
        inventoryDiffListID.validate(request);
        session.setAttribute(SIConfig.SISESSION_INVENTORYDIFFERENCE_LIST_NAME,inventoryDiffListID);//検索項目
        forwardKey(request, response, "webshop.jsp.manager.cmdty.inventory.list");
      }else if(actionName.equals(SIConfig.SIACTION_NEW)){//棚卸差異新規登録
        UIInventoryDifference inventoryDifference = new UIInventoryDifference(request,urlParam);
        try {
          if(inventoryDifference.validate(request,conn)){
            try {
              insertInventoryDiffTableData(conn,inventoryDifference);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              try {conn.commit();} catch (SQLException sqle) {sqle.printStackTrace();}
            }catch (SIDuplicateKeyException e1) {
              try {conn.rollback();}catch(SQLException ee){ee.printStackTrace();}
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.insert.duplicate"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
              e1.printStackTrace();
            }catch (SIDBAccessException e1) {
              try {conn.rollback();}catch(SQLException ee){ee.printStackTrace();}
              SICustomErrors errors=new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK,errors);
              e1.printStackTrace();
            }
            session.removeAttribute(SIConfig.SISESSION_INVENTORYDIFFERENCE_NAME);
          }else{
            session.setAttribute(SIConfig.SISESSION_INVENTORYDIFFERENCE_NAME,inventoryDifference);
          }
        }catch (SIDBAccessException e1){
          e1.printStackTrace();
          throw new ServletException();
        } 
        forwardKey(request, response, "webshop.jsp.manager.cmdty.inventory.list");
      }else if(actionName.equals(SIConfig.SIACTION_REGIST)){//棚卸差異登録
        UIInventoryDifference inventoryDifference = new UIInventoryDifference();
        inventoryDifference.updateinit(request,urlParam);
        if(inventoryDifference.getMailSendFlg().equals("1")){
          if(inventoryDifference.validate(request)){
            try{
              updateInventoryDiffTableData(conn,inventoryDifference);
              insertinvntoryDiffTblData(conn,inventoryDifference);
              try {conn.commit();}catch(SQLException ee){ee.printStackTrace();}
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.modify"));
            }catch (SIDuplicateKeyException e1) {
              try {conn.rollback();}catch(SQLException ee){ee.printStackTrace();}
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.insert.duplicate"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
              e1.printStackTrace();
            }catch (SIDBAccessException e1) {
              try {conn.rollback();}catch(SQLException ee){ee.printStackTrace();}
              SICustomErrors errors=new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK,errors);
              e1.printStackTrace();
            }
          }else{
            session.setAttribute(SIConfig.SISESSION_INVENTORYDIFFERENCEUPDATE_NAME,inventoryDifference);
            forwardKey(request, response, "webshop.jsp.manager.cmdty.inventory.edit");
          }
        }
        forwardKey(request, response, "webshop.jsp.manager.cmdty.inventory.list");
      }else if(actionName.equals(SIConfig.SIACTION_MODIFY)){//データ選択し、棚卸差異登録画面へ
        UIInventoryDiffListCond inventoryDiffList =new UIInventoryDiffListCond();
        inventoryDiffList.updateinit(request,urlParam);
        try {
          UIInventoryDifference inventory = inventoryDiffList.getInventoryDifference(conn);
          inventory.setPageNumberTxt((String)urlParam.getParam("pageNumberTxt"));
          session.setAttribute(SIConfig.SISESSION_INVENTORYDIFFERENCEUPDATE_NAME,inventory);
          forwardKey(request, response, "webshop.jsp.manager.cmdty.inventory.edit");
        }catch (SIDBAccessException e1) {
          SICustomErrors errors=new SICustomErrors();
          errors.addError(new SICustomError("database.execute.error"));
          request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK,errors);
          e1.printStackTrace();
          forwardKey(request, response, "webshop.jsp.manager.cmdty.inventory.list");
        }
      }else if(actionName.equals(SIConfig.SIACTION_BACK)){//棚卸差異登録画面から元の画面に戻る
        forwardKey(request, response, "webshop.jsp.manager.cmdty.inventory.list");
      }else if(actionName.equals(SIConfig.SIACTION_INVENTORY_EXCEL)){//棚卸差異表出力
        forwardKey(request, response, "webshop.jsp.manager.cmdty.inventory.list");
      }
    }catch (SQLException e) {
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e) {
      e.printStackTrace();
      throw new ServletException();
    }finally {
      databaseConnection.close();
    }
  }

  /**
   * <b>insertInventoryDiffTableData</b>
   * データベースにレコードを新規登録します。(棚卸差異)
   * @param lConnection DBへのコネクション
   * @param lListCond 削除するデータ
   * @return なし
   * @throws SIDBAccessException
   * @throws SIDuplicateKeyException
   */
  private void insertInventoryDiffTableData(Connection lConnection,UIInventoryDifference inventory) throws SIDuplicateKeyException, SIDBAccessException{
    SIInsertRec lRec = new SIInsertRec(SIConfig.SITABLE_INVENTORYDIFFERENCETBL_NAME);
    lRec.add("cmdtycode", inventory.getCmdtyCode());
    lRec.add("individualCode", inventory.getIndividualCode());
    lRec.add("branchCode", inventory.getBranchCode());
    lRec.add("amount", inventory.getAmount());
    lRec.add("season", inventory.getSeasonCbo());
    lRec.execute(lConnection);
    
    //棚卸在庫
    String stockAmount = inventory.getStockAmount(lConnection);
    String inventoryAmount = "0";
    inventoryAmount =SIUtil.add(inventory.getAmount(),stockAmount);
    SIModifyRec MRec = new SIModifyRec(SIConfig.SITABLE_INVENTORYSTOCKTBL_NAME);
    MRec.addCondition("cmdtyCode", inventory.getCmdtyCode());
    MRec.addCondition("individualCode", inventory.getIndividualCode());
    MRec.addCondition("branchCode", inventory.getBranchCode());
    MRec.addCondition("inventoryYear", inventory.getSeasonYearCbo());
    MRec.add(SIUtil.getAmountName(inventory.getSeasonCbo()), inventoryAmount);//在庫数量
    MRec.execute(lConnection);
  }

  /**
   * <b>updateInventoryDiffTableData</b>
   * データベースにレコードを更新します。(棚卸差異)
   * @param lConnection DBへのコネクション
   * @param lListCond 削除するデータ
   * @return なし
   * @throws SIDBAccessException
   * @throws SIDuplicateKeyException
   */
  private void updateInventoryDiffTableData(Connection lConnection,UIInventoryDifference inventory) throws SIDuplicateKeyException, SIDBAccessException{
    SIModifyRec lRec = new SIModifyRec(SIConfig.SITABLE_INVENTORYDIFFERENCETBL_NAME);
    lRec.addCondition("cmdtycode", inventory.getCmdtyCode());
    lRec.addCondition("individualCode", inventory.getIndividualCode());
    lRec.addCondition("branchCode", inventory.getBranchCode());
    lRec.addCondition("season", inventory.getSeason());
    lRec.add("comment",inventory.getComment());
    lRec.add("updateuser",inventory.getUpdateUser());
    lRec.execute(lConnection);
  }

  /**
   * <b>insertinvntoryDiffTblData</b>
   * データベースにレコードを新規登録します。(入出庫データを作成)
   * @param lConnection DBへのコネクション
   * @param lListCond 削除するデータ
   * @param stockFlg true:入庫　false:出庫
   * @return なし
   * @throws SIDBAccessException
   * @throws SIDuplicateKeyException
   */
  private void insertinvntoryDiffTblData(Connection lConnection,UIInventoryDifference inventory) throws SIDuplicateKeyException, SIDBAccessException{
    SIDateTime lDateTime=new SIDateTime();
    String purchaseprice = "";
    String processingexpence = "";
    String orderCode = null;
    boolean stockFlg = true;
    String cnt=inventory.getAmount();
    if(SIUtil.isDigitNegative(inventory.getAmount())){
      stockFlg=false;
      cnt= SIUtil.setNegative(cnt);
    }
    
    if(inventory.getPurchasePriceFlg().equals("1")){//原価を手動入力する場合
      purchaseprice = SIUtil.multi(cnt,inventory.getPurchaseprice());//単価→総額にする
      processingexpence = inventory.getProcessingexpence();
    }else if(inventory.getPurchasePriceFlg().equals("2")){//原価を現在値で自動入力の場合
      purchaseprice = "0";
      processingexpence = "0";
    }
    if(stockFlg&&inventory.getPurchasePriceFlg().equals("2")){//プラス値で原価を現在値で自動入力
      orderCode ="0";
    }else if((!stockFlg)&&inventory.getPurchasePriceFlg().equals("1")){//プラス値で手動入力
      orderCode ="0";
    }
    
    String chargeCode = inventory.getChargeCode(lConnection);
    
    if(stockFlg){
      //入庫履歴
      String storeNo=inventory.getNewStoreNumber(lConnection);
      SIInsertRec lRec=new SIInsertRec("storehistorytbl");
      lRec.add("cmdtycode",inventory.getCmdtyCode());
      lRec.add("individualcode",inventory.getIndividualCode());
      lRec.add("storenumber",storeNo);
      lRec.add("storecharge",chargeCode);
      lRec.add("storebranch",inventory.getBranchCode());
      lRec.add("amount",inventory.getAmount());
      lRec.add("purchaseprice",purchaseprice);
      lRec.add("processingexpence",processingexpence);
      lRec.add("storetype","5");
      lRec.add("comment","棚卸差異調整");
      lRec.add("ordercode",orderCode);
      lRec.add("delflg","0");//0:未承認
      lRec.add("initdatetime",lDateTime.getFullDate());
      lRec.execute(lConnection);
    }else{
      //出庫履歴
      String shipNo=inventory.getNewShipNumber(lConnection);
      //差異数は員数なので変換する
      String amount = SIUtil.setNegative(inventory.getAmount());
      SIInsertRec lRec=new SIInsertRec("shiphistorytbl");
      lRec.add("cmdtycode",inventory.getCmdtyCode());
      lRec.add("individualcode",inventory.getIndividualCode());
      lRec.add("shipnumber",shipNo);
      lRec.add("shipbranch",inventory.getBranchCode());
      lRec.add("shipcharge",chargeCode);
      lRec.add("amount",amount);
      lRec.add("purchaseprice",purchaseprice);
      lRec.add("processingexpence",processingexpence);
      lRec.add("shiptype","5");
      lRec.add("comment","棚卸差異調整");
      lRec.add("ordercode",orderCode);
      lRec.add("delflg","0");//0:未承認
      lRec.add("initdatetime",lDateTime.getFullDate());
      lRec.execute(lConnection);
      
      //出庫のみEC在庫減
      SISpcType lSpc1=new SISpcType("amount-"+amount);
      SIModifyRec lRec1=new SIModifyRec("storestocktbl");
      lRec1.addCondition("cmdtycode",inventory.getCmdtyCode());//親コード
      lRec1.addCondition("individualcode",inventory.getIndividualCode());//個別コード
      lRec1.addCondition("branchcode",inventory.getBranchCode());//支店コード
      lRec1.add("amount",lSpc1);
      lRec1.execute(lConnection);
    }
    
    //棚卸差異を一つでも登録する場合:棚卸ヘッダのステータスを２にする
    SIModifyRec lRec = new SIModifyRec(SIConfig.SITABLE_INVENTORYTBL_NAME);
    lRec.addCondition("branchCode", inventory.getBranchCode());
    lRec.addCondition("season", inventory.getSeason());
    lRec.add("status", "2");
    lRec.add("initdatetime",lDateTime.getFullDate());
    lRec.execute(lConnection); 
  }
}