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

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 jp.co.sint.basic.SIUserInfo;
import jp.co.sint.beans.mallmgr.UICustAddress;
import jp.co.sint.config.SIConfig;
import jp.co.sint.config.SIDBMultiConf;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.database.SIDateTimeType;
import jp.co.sint.database.SIDeleteRec;
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.SIURLMap;
import jp.co.sint.tools.SIUtil;
import jp.co.sint.tools.SIURLParameter;//7.1.1 ST0236 追加

import org.apache.log4j.Category;

/**
 * @version $Id: SIAddrSrv.java,v 1.0 2003/12/09 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/09 18:03:59  Original
 */
public class SIAddrSrv 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 修正
        log.debug("doUpdate:actionName="+actionName);
        UICustAddress custAddr=new UICustAddress();
        
        if (SIConfig.SIACTION_CLOSE.equalsIgnoreCase(actionName)){//画面閉じる
          custAddr=(UICustAddress)session.getAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME);
          if (custAddr==null)custAddr=new UICustAddress();
          custAddr.setCloseWindow(true);
          session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
          forwardKey(request,response,"webshop.jsp.front.addr.result");
        }else if (SIConfig.SIACTION_ZIPDIC.equalsIgnoreCase(actionName)){//郵便番号辞書ソフトから県名などを検索
          custAddr.init(request,urlParam);//7.1.1 ST0236 修正
          session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
          forwardKey(request,response,"webshop.jsp.front.addr.edit");
        }else if (SIConfig.SIACTION_MODIFY.equalsIgnoreCase(actionName)){//レコードの修正
          custAddr.init(request,urlParam);//7.1.1 ST0236 修正
          custAddr.setCustCode(SIHTMLUtil.getUserInfo(request).getCustCode());//7.2.0 ST0328 追加
          custAddr.reset(databaseConnection.getConnection());
          session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
          forwardKey(request,response,"webshop.jsp.front.addr.edit");
        }else if (SIConfig.SIACTION_NEW.equalsIgnoreCase(actionName)){//新規のレコード
          custAddr.init(request,urlParam);//7.1.1 ST0236 修正
          SIUserInfo lUserInfo=SIHTMLUtil.getUserInfo(request);
          custAddr.setCustCode(lUserInfo.getCustCode());
          session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
          forwardKey(request,response,"webshop.jsp.front.addr.edit");
        }else if (SIConfig.SIACTION_REMODIFY.equalsIgnoreCase(actionName)){//再修正へ
          forwardKey(request,response,"webshop.jsp.front.addr.edit");
        }else if (SIConfig.SIACTION_CONFIRM.equalsIgnoreCase(actionName)){//データの確認画面へ
          //インスタンスの作成
          custAddr=new UICustAddress();
          //データの取得
          custAddr.init(request,urlParam);//7.1.1 ST0236 修正
          session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
          //データのチェック
          if (custAddr.validate(request,databaseConnection.getConnection())==false ){
            forwardKey(request,response,"webshop.jsp.front.addr.edit");
          }else {
            forwardKey(request,response,"webshop.jsp.front.addr.confirm");
          }
        }else if(SIConfig.SIACTION_DELETE.equalsIgnoreCase(actionName)){
          custAddr=new UICustAddress();
          custAddr.init(request,urlParam);//7.1.1 ST0236 修正
          custAddr.setCustCode(SIHTMLUtil.getUserInfo(request).getCustCode());//7.2.0 ST0328 追加
          try {
            if(SIUtil.isNull(custAddr.getCustCode()) || SIUtil.isNull(custAddr.getAddressCode())){
              throw new SIDBAccessException();
            }
            deleteTableData(databaseConnection.getConnection(),custAddr);
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                 SIErrorFactory.getErrorMsg("manager.message.success.delete"));
            try {databaseConnection.getConnection().commit();}catch(SQLException sqle){}
          }catch(SIDBAccessException e){
            try {databaseConnection.getConnection().rollback();}catch(SQLException ee){}
            SICustomErrors errors=new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
          }
          forwardKey(request,response,"webshop.jsp.front.customer.delivery");
        //7.2.0 ST0249 追加 ここから
        }else if (SIConfig.SIACTION_RESET.equalsIgnoreCase(actionName)) { //リセット
          if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)) {
            custAddr.init(request,urlParam);
            custAddr.setCustCode(SIHTMLUtil.getUserInfo(request).getCustCode());//7.2.0 ST0328 追加
            custAddr.reset(databaseConnection.getConnection());
          }
          custAddr.resetInit(request,urlParam);
          session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
          forwardKey(request,response,"webshop.jsp.front.addr.edit");
        //7.2.0 ST0249 追加 ここまで
        }else{//DBへのデータ登録
          custAddr=new UICustAddress();
          // EDBTG005-00 kamata add start
          if (SIURLMap.isSmartPhone(request)) {
              // スマートフォンの場合
              custAddr.init(request,urlParam);
          } else {
              custAddr=(UICustAddress)session.getAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME);
          }
          // EDBTG005-00 kamata add end
          custAddr.setCustCode(SIHTMLUtil.getUserInfo(request).getCustCode());//7.2.0 ST0328 追加
          try {
            if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)){
              // EDBTG005-00 kamata add start
              custAddr.setInsertUpdateFlg(SIConfig.SIEDIT_MODE_INSERT);
              // EDBTG005-00 kamata add end
              insertTableData(databaseConnection.getConnection(),custAddr);//新規レコードの作成
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              try {databaseConnection.getConnection().commit();}catch(SQLException sqle){}
            }else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)) {
              // EDBTG005-00 kamata add start
              custAddr.setInsertUpdateFlg(SIConfig.SIEDIT_MODE_UPDATE);
              // EDBTG005-00 kamata add end
              updateTableData(databaseConnection.getConnection(),custAddr);//既存レコードの修正
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.modify"));
              try {databaseConnection.getConnection().commit();}catch(SQLException sqle){}
            }else log.error("Found a not defined edit mode.editMode="+editMode);
            //結果画面への遷移
            // EDBTG005-00 kamata add start
            if (SIURLMap.isSmartPhone(request)) {
              // スマートフォンの場合
              session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME, custAddr);
              String callflag = this.getParameter(urlParam,"callflag");
              if ("order".equals(callflag)) {
                forwardKey(request, response, "webshop.jsp.front.ordercounter");
              } else {
                forwardKey(request, response, "webshop.jsp.front.customer.delivery");
              }
            } else {
              forwardKey(request,response,"webshop.jsp.front.addr.result");
            }
            // EDBTG005-00 kamata add end
          }catch(SIDuplicateKeyException sqle){
            try {databaseConnection.getConnection().rollback();}catch(SQLException ee){}
            SICustomErrors errors=new SICustomErrors();
            errors.addError(new SICustomError("database.insert.duplicate"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
            forwardKey(request,response,"webshop.jsp.front.addr.edit");
          }catch(SIDBAccessException sqle){
            try {databaseConnection.getConnection().rollback();}catch(SQLException ee){}
            SICustomErrors errors=new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY,errors);
            forwardKey(request,response,"webshop.jsp.front.addr.edit");
          }
        }
      } catch (SQLException e) {
        e.printStackTrace();
        throw new ServletException();
      } catch (NamingException e) {
        e.printStackTrace();
        throw new ServletException();
      }finally{
        databaseConnection.close();
      }
  }
  
  /**
   * <b>insertTableData</b>
   * データベースにレコードを作成します。
   * @param lConnection DBへのコネクション
   * @param regCmdty 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void insertTableData(Connection lConnection,UICustAddress regAddr) throws SIDuplicateKeyException,SIDBAccessException{
    String lAddressCode=regAddr.getNextAddressCode(lConnection);
    
    SIInsertRec lRec=new SIInsertRec("CustAddressTbl");
    lRec.add("CustCode",regAddr.getCustCode());//顧客コード
    lRec.add("AddressCode",lAddressCode);//アドレス帳番号
    lRec.add("CustCompanyFlg",regAddr.getCustCompanyFlg());//法人個人区分
    lRec.add("DeliveryName",regAddr.getDeliveryName());//配送先呼称
    lRec.add("DeliveryAddressee",regAddr.getDeliveryAddressee());//配送先正式名
    lRec.add("Email",regAddr.getEmail());//EMAIL
    lRec.add("PostCode1",regAddr.getPostCode1());//郵便番号1
    lRec.add("PostCode2",regAddr.getPostCode2());//郵便番号2
    lRec.add("Address1",regAddr.getAddress1());//住所1
    lRec.add("Address2",regAddr.getAddress2());//住所2
    lRec.add("Address3",regAddr.getAddress3());//住所3
    lRec.add("CompanyName",regAddr.getCompanyName());//サロン名
    lRec.add("CorporationName",regAddr.getCorporationName());//会社名
    lRec.add("Tel",regAddr.getTel());//連絡先電話番号
    lRec.add("Fax",regAddr.getFax());//連絡先FAX番号
    lRec.add("SendMailFlg",regAddr.getSendMailFlg());//送信フラグ
    lRec.add("DaysBeforehand",regAddr.getDaysBeforehand());//何日前
    lRec.add("MailMonth",regAddr.getMailMonth());//お知らせ月
    lRec.add("MailDay",regAddr.getMailDay());//お知らせ日
    lRec.add("LastDeliveryDate",regAddr.getLastDeliveryDate());//最終配送日
    
    //アドレス帳テーブルの更新
    lRec.execute(lConnection);
  }
  
  /**
   * <b>updateTableData</b>
   * データベースにレコードを修正します。
   * @param lConnection DBへのコネクション
   * @param regCmdty 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void updateTableData(Connection lConnection,UICustAddress regAddr)throws SIDBAccessException{
    String lAddressCode=regAddr.getNextAddressCode(lConnection);
    log.debug("updateTableData:lAddressCode="+lAddressCode);
    SIModifyRec lRec=new SIModifyRec("CustAddressTbl");
    SIDateTime lDateTime = new SIDateTime();
    
    try {
      lRec.addCondition("CustCode",regAddr.getCustCode());//顧客コード
      lRec.addCondition("AddressCode",regAddr.getAddressCode());//アドレス帳番号
      
      lRec.add("CustCompanyFlg",regAddr.getCustCompanyFlg());//法人個人区分
      lRec.add("DeliveryName",regAddr.getDeliveryName());//配送先呼称
      lRec.add("DeliveryAddressee",regAddr.getDeliveryAddressee());//配送先正式名
      lRec.add("Email",regAddr.getEmail());//EMAIL
      lRec.add("PostCode1",regAddr.getPostCode1());//郵便番号1
      lRec.add("PostCode2",regAddr.getPostCode2());//郵便番号2
      lRec.add("Address1",regAddr.getAddress1());//住所1
      lRec.add("Address2",regAddr.getAddress2());//住所2
      lRec.add("Address3",regAddr.getAddress3());//住所3
      lRec.add("CompanyName",regAddr.getCompanyName());//サロン名
      lRec.add("CorporationName",regAddr.getCorporationName());//会社名
      lRec.add("Tel",regAddr.getTel());//連絡先電話番号
      lRec.add("Fax",regAddr.getFax());//連絡先FAX番号
      if (SIDBMultiConf.SIDB_CURRENT_INX ==SIDBMultiConf.SIDB_POSTGRESQL_INX){
        lRec.add("UpdateDateTime",lDateTime.getFullDateTime());//更新日時
      }else{
        lRec.add("UpdateDateTime",new SIDateTimeType(lDateTime.getFullDateTime()));
      }
      //アドレス帳テーブルの更新
      lRec.execute(lConnection);
    } catch (SIDuplicateKeyException sqle) {
      throw new SIDBAccessException(sqle);
    }
  }
  
  /**
   * <b>deleteTableData</b>
   * データベースにレコードを削除します。
   * @param lConnection DBへのコネクション
   * @param lErrors エラーメッセージ
   * @param cmdtyList 削除するデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void deleteTableData(Connection lConnection,UICustAddress regAddr)throws SIDBAccessException{
    SIDeleteRec lRec=new SIDeleteRec("CustAddressTbl");
    try {
      lRec.addCondition("CustCode",regAddr.getCustCode());//顧客コード
      lRec.addCondition("AddressCode",regAddr.getAddressCode());//アドレス帳番号
      //商品テーブルにレコードの削除
      lRec.execute(lConnection);
    } catch (SIDuplicateKeyException e) {
      throw new SIDBAccessException(e);
    }
  }
}