/**
 * Copyright (c) 2003-2004 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 jp.co.sint.basic.SILogin;
import jp.co.sint.beans.mallmgr.UICustAddress;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDBUtil;  //7.3.0 ST2023 追加
import jp.co.sint.database.SIDatabaseConnection;
//import jp.co.sint.database.SIDateTimeType;//7.3.0 ST2023 削除
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.SIErrorFactory;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIUtil;

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

/**
 * @version $Id: SIRegAddrSrv.java,v 1.0 2003/12/09 Exp $
 * @author  yamauchi
 * <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>
 * yamauchi   2004/01/29 18:03:59  Original
 */
public class SIRegAddrSrv 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);
    SIRegMngAccesslogSrv siRegMngAccesslogSrv = new SIRegMngAccesslogSrv();
    String strDBDateTime = null;
    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);//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.manager.addr.result");
      //7.2.0 ST1030 追加 ここから
      } else if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)) {//リロード
        custAddr=(UICustAddress)session.getAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME);
        request.setAttribute("cuc", custAddr.getCustCode());
        forwardKey(request,response,"webshop.jsp.manager.addr.list");
      //7.2.0 ST1030 追加 ここまで
      } 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.manager.addr.edit");
      }else if (SIConfig.SIACTION_MODIFY.equalsIgnoreCase(actionName)){//レコードの修正
        custAddr.init(request,urlParam);//7.1.1 ST0236 修正
        custAddr.reset(databaseConnection.getConnection());
        session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
        forwardKey(request,response,"webshop.jsp.manager.addr.edit");
      }else if (SIConfig.SIACTION_NEW.equalsIgnoreCase(actionName)){//新規のレコード
        custAddr.init(request,urlParam);//7.1.1 ST0236 修正
        session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
        forwardKey(request,response,"webshop.jsp.manager.addr.edit");
      }else if (SIConfig.SIACTION_REMODIFY.equalsIgnoreCase(actionName)){//再修正へ
        forwardKey(request,response,"webshop.jsp.manager.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,false)==false ){
          forwardKey(request,response,"webshop.jsp.manager.addr.edit");
        }else {
          forwardKey(request,response,"webshop.jsp.manager.addr.confirm");
        }
      }else if(SIConfig.SIACTION_DELETE.equalsIgnoreCase(actionName)){
        custAddr=new UICustAddress();
        custAddr.init(request,urlParam);//7.1.1 ST0236 修正
        try {
          if(SIUtil.isNull(custAddr.getCustCode()) || SIUtil.isNull(custAddr.getAddressCode())){
            throw new SIDBAccessException();
          }
          deleteTableData(databaseConnection.getConnection(),custAddr);
          siRegMngAccesslogSrv.insertTableData(databaseConnection.getConnection(),request,"7",null);//7.3.0 ST2023 追加  管理ログ出力
          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.manager.addr.list");
      //7.2.0 ST0249 追加 ここから
      }else if (SIConfig.SIACTION_RESET.equalsIgnoreCase(actionName)) { //リセット
        if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)) {
          custAddr.init(request,urlParam);
          custAddr.reset(databaseConnection.getConnection());
        }
        custAddr.resetInit(request,urlParam);
        session.setAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME,custAddr);
        forwardKey(request,response,"webshop.jsp.manager.addr.edit");
      //7.2.0 ST0249 追加 ここまで
      }else{//DBへのデータ登録
        custAddr=new UICustAddress();
        custAddr=(UICustAddress)session.getAttribute(SIConfig.SISESSION_ADDR_EDIT_NAME);
        try {
          strDBDateTime = SIDBUtil.getDBDateTime(databaseConnection.getConnection());  //7.3.0 ST2023 追加
          if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)){
            //7.3.0 ST2023 修正 引数追加
            insertTableData(databaseConnection.getConnection(),custAddr,request,strDBDateTime);//新規レコードの作成
            siRegMngAccesslogSrv.insertTableData(databaseConnection.getConnection(),request,"5",strDBDateTime);//7.3.0 ST2023 追加  管理ログ出力
            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)) {
            //7.3.0 ST2023 修正 引数追加
            updateTableData(databaseConnection.getConnection(),custAddr,request,strDBDateTime);//既存レコードの修正
            siRegMngAccesslogSrv.insertTableData(databaseConnection.getConnection(),request,"6",strDBDateTime);//7.3.0 ST2023 追加  管理ログ出力
            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);
          //結果画面への遷移
          forwardKey(request,response,"webshop.jsp.manager.addr.result");
        }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.manager.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.manager.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 入力したデータ
   * @param HttpServletRequest リクエスト (ST2023 追加)
   * @param String             日時       (ST2023 追加)
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void insertTableData(Connection lConnection,UICustAddress regAddr,HttpServletRequest request, String strDBDateTime) throws SIDuplicateKeyException,SIDBAccessException{   //7.3.0 ST2023 修正　引数追加
    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());//お知らせ日
    //7.3.0 ST2023 追加  ここから
    SILogin siLogin = SIHTMLUtil.getLogin(request);
    
    if ( siLogin.getMallShopCode() != null ) {                  //更新ショップ（モール）コード
      lRec.add("UpdateMallShopCode",siLogin.getMallShopCode());
    } else {
      lRec.add("UpdateMallShopCode","");
    }
    if ( siLogin.getUserCode() != null ) {                      //更新ユーザーコード
      lRec.add("UpdateUserCode",siLogin.getUserCode());
    } else {
      lRec.add("UpdateUserCode","");
    }
    if ( strDBDateTime != null ) {                               //更新日時
      lRec.add("UpdateDateTime",new SISpcType(SIDBUtil.SQL2Str(strDBDateTime,"::timestamp")));
    } else {
      lRec.add("UpdateDateTime",new SISpcType("TO_CHAR(now(),'YYYY/MM/DD HH24:MI:SS')::timestamp"));
    }
    //7.3.0 ST2023 追加  ここまで
    
    //商品マスタテーブルの更新
    lRec.execute(lConnection);
  }
  
  /**
   * <b>updateTableData</b>
   * データベースにレコードを修正します。
   * @param lConnection DBへのコネクション
   * @param regCmdty 入力したデータ
   * @param HttpServletRequest リクエスト (ST2023 追加)
   * @param String             日時       (ST2023 追加)
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void updateTableData(Connection lConnection,UICustAddress regAddr,HttpServletRequest request, String strDBDateTime)throws SIDBAccessException{  //7.3.0 ST2023 修正　引数追加
    SIModifyRec lRec=new SIModifyRec("CustAddressTbl");
    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番号
      //7.3.0 ST2023 削除 ここから
      //if (SIDBMultiConf.SIDB_CURRENT_INX ==SIDBMultiConf.SIDB_POSTGRESQL_INX){
      //  lRec.add("UpdateDateTime",lDateTime.getFullDateTime());//更新日時
      //}else{
      //  lRec.add("UpdateDateTime",new SIDateTimeType(lDateTime.getFullDateTime()));//更新日時
      //}
      //7.3.0 ST2023 削除 ここまで
      //7.3.0 ST2023 追加 ここから
      SILogin siLogin = SIHTMLUtil.getLogin(request);
      
      if ( siLogin.getMallShopCode() != null ) {                  //更新ショップ（モール）コード
        lRec.add("UpdateMallShopCode",siLogin.getMallShopCode());
      } else {
        lRec.add("UpdateMallShopCode","");
      }
      if ( siLogin.getUserCode() != null ) {                      //更新ユーザーコード
        lRec.add("UpdateUserCode",siLogin.getUserCode());
      } else {
        lRec.add("UpdateUserCode","");
      }
      if ( strDBDateTime != null ) {                               //更新日時
        lRec.add("UpdateDateTime",new SISpcType(SIDBUtil.SQL2Str(strDBDateTime,"::timestamp")));
      } else {
        lRec.add("UpdateDateTime",new SISpcType("TO_CHAR(now(),'YYYY/MM/DD HH24:MI:SS')::timestamp"));
      }
      //7.3.0 ST2023 追加  ここまで
      //商品マスタの更新
      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
   */
  private 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);
    }
  }

}
