/**
 * Created on 2003/11/28
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package jp.co.sint.servlet.mallmgr;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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.UIPayeeInfoList;
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.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 org.apache.log4j.Category;
import jp.co.sint.tools.SIURLParameter;//7.1.1 ST0236 追加

/**
 * @version $Id: SIPayeeInfo.java,v 1.0 2003/11/28 Exp $
 * @author  Shionoya Yoshiaki
 * <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>
 * Shionoya       2003/11/28 12:00:00  Original
 */
public class SIRegPayeeInfoSrv extends SIServlet {

  //ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);

  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);//7.1.1 ST0236 追加
    try {
      Connection connection;

	  String actionName=this.getActionName(urlParam);//画面からのアクション	//7.1.1 ST0236 修正
	  String editMode = this.getEditMode(urlParam); //DBへの編集モード	//7.1.1 ST0236 修正

      UIPayeeInfoList regList = new UIPayeeInfoList();

      //データベースへのコネクションの作成
      connection = databaseConnection.getConnection();

      if (SIConfig.SIACTION_REFRESH.equalsIgnoreCase(actionName)) {//新規登録画面
        //データの取得とデータのチェック
        try{
		  regList.initSelect(request,urlParam);//7.1.1 ST0236 修正
		  regList.validateSelect(request,connection,urlParam);//7.1.1 ST0236 修正
        } catch (SIDBAccessException sqle) {
          SICustomErrors errors = new SICustomErrors();
          errors.addError(new SICustomError("database.execute.error"));
          request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
        }
        session.setAttribute(SIConfig.SISESSION_MAN_PAYEEINFO_LIST_NAME, regList);
        forwardKey(request, response, "webshop.jsp.manager.payeeinfo.list");
      } else if (SIConfig.SIACTION_RESET.equalsIgnoreCase(actionName)) {
        forwardKey(request, response, "webshop.jsp.manager.payeeinfo.list");
      } else if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)) {
        try{//一覧と検索などの画面
		  regList.initList(request,urlParam);//7.1.1 ST0236 修正
          regList.reset(connection);
          session.setAttribute(SIConfig.SISESSION_MAN_PAYEEINFO_LIST_NAME, regList);
          forwardKey(request, response, "webshop.jsp.manager.payeeinfo.list");
        } catch (SIDBAccessException sqle) {
          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.payeeinfo.list");
        }catch(Exception sqle){
          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.payeeinfo.list");
        }
      } else if (SIConfig.SIACTION_REGIST.equalsIgnoreCase(actionName)) {
		regList.init(request,urlParam);//7.1.1 ST0236 修正
        //データのチェック
		if (regList.validate(request, connection,urlParam) == false) {//7.1.1 ST0236 修正
		  regList.setEditModeType((String)urlParam.getParam("editModeType"));//7.1.1 ST0236 修正
          session.setAttribute(SIConfig.SISESSION_MAN_PAYEEINFO_LIST_NAME, regList);
          forwardKey(request, response, "webshop.jsp.manager.payeeinfo.list");
        } else {
          try {
            if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)){
              insertTableData(regList, connection);
              regList.setActionNameTxt(SIConfig.SIACTION_RESET);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.insert"));
            }else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)){
              updateTableData(regList, connection);
              regList.setActionNameTxt(SIConfig.SIACTION_RESET);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.modify"));
            }else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_DELETE)){
			  regList.initList(request,urlParam);//7.1.1 ST0236 修正
              deleteTableData(regList, connection);
              regList.setActionNameTxt(SIConfig.SIACTION_RESET);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.delete"));
            }else log.error("no known edit mode.editMode=" + editMode);
            session.setAttribute(SIConfig.SISESSION_MAN_PAYEEINFO_LIST_NAME, regList);
            forwardKey(request, response, "webshop.jsp.manager.payeeinfo.list");
          } catch (SIDuplicateKeyException sqle) {
            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.payeeinfo.list");
          } catch (SIDBAccessException sqle) {
            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.payeeinfo.list");
          }catch(SQLException sqle){
            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.payeeinfo.list");
          }
        }
      }
    }catch (SQLException e){
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e){
      e.printStackTrace();
      throw new ServletException();
    }finally{
      databaseConnection.close();
    }

  }

  /**
  * insertTableData
  * コードを作成します。
  * @param
  * @return
  * @throws
  */
  private void insertTableData(UIPayeeInfoList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException, SQLException {

    //仕入先IDを設定
    this.getPayeeCode(regList,connection);

    SISpcType lSpcType = new SISpcType();
    SIInsertRec lRec = new SIInsertRec("payeeinfomtbl");

    lRec.add("mallshopcode", regList.getMallShopCode());
    lRec.add("paymethodcode", regList.getPayMethodCode());
    lRec.add("payeecode", regList.getPayeeCode());
    lRec.add("bankcode", regList.getBankCode());
    lRec.add("bankname", regList.getBankName());
    lRec.add("banknamekana", regList.getBankNameKana());
    lRec.add("subbankcode", regList.getSubBankCode());
    lRec.add("subbankname", regList.getSubBankName());
    lRec.add("subbanknamekana", regList.getSubBankNameKana());
    lRec.add("accounttype", regList.getAccountType());
    lRec.add("accountno", regList.getAccountNo());
    lRec.add("accountname", regList.getAccountName());

    log.debug("insert sql=" + lRec.getSQL());
    lRec.execute(connection);
    try {
      connection.commit();
    } catch (SQLException sqle) {
      throw new SIDBAccessException("insert data error.");
    }
  }

  /**
  * updateTableData
  * レコードを修正します。
  * @param
  * @return
  * @throws
  */
  private void updateTableData(UIPayeeInfoList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SISpcType lSpcType = new SISpcType();
    SIModifyRec lRec = new SIModifyRec("payeeinfomtbl");

    lRec.addCondition("mallshopcode", regList.getMallShopCode());
    lRec.addCondition("paymethodcode", regList.getPayMethodCode());
    lRec.addCondition("payeecode", regList.getPayeeCode());

    lRec.add("bankcode", regList.getBankCode());
    lRec.add("bankname", regList.getBankName());
    lRec.add("banknamekana", regList.getBankNameKana());
    lRec.add("subbankcode", regList.getSubBankCode());
    lRec.add("subbankname", regList.getSubBankName());
    lRec.add("subbanknamekana", regList.getSubBankNameKana());
    lRec.add("accounttype", regList.getAccountType());
    lRec.add("accountno", regList.getAccountNo());
    lRec.add("accountname", regList.getAccountName());

    log.debug("update sql=" + lRec.getSQL());
    lRec.execute(connection);
    try {
      connection.commit();
    } catch (SQLException sqle) {
      throw new SIDBAccessException("update data error.");
    }
  }

  /**
	* deleteTableData
	* データベースにレコードを削除します。
	* @param
	* @return
	* @throws
	*/
  private void deleteTableData(UIPayeeInfoList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
	  SISpcType lSpcType = new SISpcType();
	  SIDeleteRec lRec = new SIDeleteRec("PayeeInfoMTbl");

	  lRec.addCondition("mallshopCode", regList.getMallShopCode());
	  lRec.addCondition("paymethodCode", regList.getPayMethodCode());
	  lRec.addCondition("payeecode", regList.getPayeeCode());

  	log.debug("delete sql=" + lRec.getSQL());

    lRec.execute(connection);
	   try {
	    connection.commit();
	  } catch (SQLException sqle) {
	    throw new SIDBAccessException("delete data error.");
	  }
  }

  public void destroy() {
  }

  /**
   * 仕入先IDを自動采番
   * @param regList
   * @param connection
   * @throws SQLException
   */
  private void getPayeeCode(UIPayeeInfoList regList, Connection connection) throws SQLException{
    String payeeCode = null;
    String sql = "SELECT MAX(payeeCode) AS max FROM PayeeInfoMTbl "
    		   + "WHERE mallshopCode = '" + regList.getMallShopCode() + "' "
    		   + "AND paymethodCode = " + regList.getPayMethodCode() + " ";
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery(sql);

    if(resultSet.next()){
      regList.setPayeeCode(Integer.toString(resultSet.getInt("max")+1));
    }else{
      regList.setPayeeCode("1");
    }
    SIDBUtil.close(statement,resultSet);
  }
}
