/** Created on 2003/08/06
 * 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.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.UICustqaListCond;
import jp.co.sint.beans.mallmgr.UIRegCustqa;
import jp.co.sint.config.SIConfig;
import jp.co.sint.config.SIDBMultiConf;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDBUtil;
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.SIModifyRec;
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.SIUtil;

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

/**
 * @author yamauchi
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

public class SIRegCustqaSrv extends SIServlet {
  //ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);
  /**
    * doUpdate
    * HTTP Get リクエストの処理
    * @param
    * @return
    * @throws
    */
  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();
	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 修正

      UICustqaListCond custqaList = new UICustqaListCond();
      UIRegCustqa regCustqa = new UIRegCustqa();

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

      if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)) {  //検索画面
        //データの取得とデータのチェック
		custqaList=new UICustqaListCond(request,urlParam);//7.1.1 ST0236 修正
        custqaList.validate(request);
        session.setAttribute(SIConfig.SISESSION_MAN_CUSTQA_LIST_NAME, custqaList);
        forwardKey(request, response, "webshop.jsp.manager.custqa.list");
      } else if(SIConfig.SIACTION_BACK.equalsIgnoreCase(actionName)){//戻るボタン
        forwardKey(request, response, "webshop.jsp.manager.custqa.list");
      } else if (SIConfig.SIACTION_MODIFY.equalsIgnoreCase(actionName)) { //レコードの修正
		regCustqa.init(request,urlParam);//7.1.1 ST0236 修正

        SILogin lLogin=SIHTMLUtil.getLogin(request);
        boolean lRes=false;
        if (lLogin.isShop()){
          StringBuffer lSqlBuf=new StringBuffer("SELECT CustQACode FROM CustQaTbl WHERE MallShopCode=");
          lSqlBuf.append(SIDBUtil.SQL2Str(lLogin.getMallShopCode())).append(" AND CustQACode=");
          lSqlBuf.append(SIDBUtil.SQL2Str(regCustqa.getCustQACode()));
          try {
            if (SIDBUtil.hasData(connection,lSqlBuf.toString()))lRes=true;
            else lRes=false;
          } catch (SIDBAccessException e1) {
            e1.printStackTrace();
            lRes=false;
          } 
        }else lRes=true;

        if (lRes){
          session.setAttribute(SIConfig.SISESSION_MAN_CUSTQA_EDIT_NAME,regCustqa);
          forwardKey(request, response, "webshop.jsp.manager.custqa.edit");
        }else{
          forwardKey(request, response, "webshop.jsp.manager.custqa.list");
        }
      } else if (SIConfig.SIACTION_DELETE.equalsIgnoreCase(actionName)) { //削除
        try {
          if(custqaList.validateDelete(request)){
            deleteTableData(connection, request);
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                 SIErrorFactory.getErrorMsg("manager.message.success.delete")); 
          }
          forwardKey(request, response, "webshop.jsp.manager.custqa.list");
        } catch (SIDuplicateKeyException e) {

          SICustomErrors errors = new SICustomErrors();
          errors.addError(new SICustomError("database.delete.duplicate"));
          request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
          forwardKey(request, response, "webshop.jsp.manager.custqa.list");
        } catch (SIDBAccessException e) {

          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.custqa.list");
        }
      } else {
        regCustqa = new UIRegCustqa();
		regCustqa.init(request,urlParam);//7.1.1 ST0236 修正
        session.setAttribute(SIConfig.SISESSION_MAN_CUSTQA_EDIT_NAME,regCustqa);
        //データのチェック
        if (regCustqa.validate(request, connection) == false) {
          regCustqa.setActionNameTxt(SIConfig.SIACTION_REMODIFY);
          session.setAttribute(SIConfig.SISESSION_MAN_CUSTQA_EDIT_NAME, regCustqa);
          forwardKey(request, response, "webshop.jsp.manager.custqa.edit");
        } else {
          try {
            if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)) {
            } else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)) {
              updateTableData(connection, regCustqa); //既存のレコードの修正
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.modify"));
                try {databaseConnection.getConnection().commit();}catch(SQLException sqle){}
            } else log.error("no know edit mode.editMode=" + editMode);
            forwardKey(request, response, "webshop.jsp.manager.custqa.result");
          } catch (SIDuplicateKeyException sqle) {

            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("database.delete.duplicate"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
            forwardKey(request, response, "webshop.jsp.manager.custqa.edit");
          } 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.custqa.edit");
          }
        }
     }
    }catch (SQLException e){
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e){
      e.printStackTrace();
      throw new ServletException();
    }finally{
      databaseConnection.close();
    }
  }

  /**
   * updateTableData
   * データベースにレコードを修正します。
   * @param
   * @return
   * @throws
   */
  public static void updateTableData(Connection connection, UIRegCustqa regCustqa) throws SIDuplicateKeyException, SIDBAccessException {
    SIModifyRec lRec = new SIModifyRec("custqaTbl");

	//現在の日付けの取得
	SIDateTime siDate = new SIDateTime();
	
    lRec.addCondition("CustQACode", regCustqa.getCustQACode());

    lRec.add("ATile", regCustqa.getATile());
    lRec.add("ADescription", regCustqa.getADescription());
    lRec.add("ASignature", regCustqa.getASignature());
    if (SIDBMultiConf.SIDB_CURRENT_INX ==SIDBMultiConf.SIDB_POSTGRESQL_INX){
      lRec.add("AInitDateTime", siDate.getFullDateTime());
    }else{
      lRec.add("AInitDateTime",new SIDateTimeType(siDate.getFullDateTime()));
    }

    //データの更新
    lRec.execute(connection);
    try {
      connection.commit();
    } catch (SQLException sqle) {
      throw new SIDBAccessException("update data error.");
    }
  }

  /**
   * deleteTableData
   * データベースにレコードを作成します。
   * @param
   * @return
   * @throws
   */
  public void deleteTableData(Connection connection, HttpServletRequest request) throws SIDuplicateKeyException, SIDBAccessException {
    String testData[] = request.getParameterValues("checkbox_delete");
    if (testData == null) {
      testData = new String[0];
    }
    SIDeleteRec lDeleteRec = new SIDeleteRec();
    if (testData != null) {
      for (int ii = 0; ii < testData.length; ii++) {
        if (SIUtil.isNotNull(testData[ii])) {
          lDeleteRec = new SIDeleteRec();
          lDeleteRec.setTableName("custqatbl");
          lDeleteRec.addCondition("custqacode", testData[ii]);
          lDeleteRec.execute(connection);

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

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

  /**
   * destroy
   * リソースの後処理
   * @param
   * @return
   * @throws
   */
  public void destroy() {
  }
}
