/**
 * Copyright (c) 2003-2005 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 java.util.StringTokenizer;

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.UIEstimateListCond;
import jp.co.sint.beans.mallmgr.UIRegUpdateEstimate;
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.servlet.SIServlet;
import jp.co.sint.tools.SIBGUtil;
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.SIURLParameter;

import org.apache.log4j.Category;

/**
 * @version $Id: SIRegIndividualSrv.java,v 1.0 2005/08/19 Exp $
 * @author Tsuyoshi Yagi <br>
 * Description: 見積情報検索を行うServlet
 * <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>
 * T.Yagi 2005/12/07 Original
 */
public class SIEstimateListSrv 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);
    
    String actionName = this.getActionName(urlParam); // 画面からのアクション
    try {
      Connection conn = databaseConnection.getConnection();
      
      if (actionName.equals(SIConfig.SIACTION_LIST)) {
        session.setAttribute(SIConfig.SISESSION_MAN_NAVIGATER_LIST_NAME, SIConfig.SINAVI_ESTIMATE_LIST);
        UIEstimateListCond estimateList = new UIEstimateListCond();
        estimateList.init(request, urlParam);
        estimateList.validate(request);
        session.setAttribute(SIConfig.SISESSION_MAN_ESTIMATE_LIST, estimateList);
        forwardKey(request, response, "webshop.jsp.manager.estimate.estimatelist");
      } else if (actionName.equals(SIConfig.SIACTION_DELETE)) {
        UIEstimateListCond estimateList = new UIEstimateListCond();
        estimateList.initDel(request, urlParam);
        if (estimateList.validateDelete(request)) {// 7.3.0 PI-NES0501
          if (estimateList.getEstimateCheck() != null) {
            String[] target = estimateList.getEstimateCheck();
            try {
              boolean sendMailFlg = false;
              String fromMail = SIDBUtil.getFirstData(databaseConnection.getConnection(), "SELECT email FROM chargetbl WHERE chargecode="
                  + SIDBUtil.SQL2Str(manLogin.getUserCode()));
              for (int i = 0; i < estimateList.getEstimateCheck().length; i++) {
                sendMailFlg = sendMailFlg | deleteEstimate(conn, target[i], fromMail);
              }
              try {
                conn.commit();
              } catch (SQLException sqle) {}
              if (sendMailFlg) request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.delete.mail"));
              else request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.delete.mail2"));
              forwardKey(request, response, "webshop.jsp.manager.estimate.estimatelist");
            } catch (SIDBAccessException sqle) {
              try {
                conn.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.estimate.estimatelist");
            }
          } else {
            forwardKey(request, response, "webshop.jsp.manager.estimate.estimatelist");
          }
        } else {
          forwardKey(request, response, "webshop.jsp.manager.estimate.estimatelist");
        }
      } else if (actionName.equals(SIConfig.SIACTION_DETAIL)) {
        UIEstimateListCond estimateList = (UIEstimateListCond) session.getAttribute(SIConfig.SISESSION_MAN_ESTIMATE_LIST);
        if (estimateList == null) estimateList = new UIEstimateListCond();
        estimateList.init(request, urlParam);
        estimateList.validate(request);
        UIRegUpdateEstimate updateEstimate = new UIRegUpdateEstimate();
        try {
          updateEstimate.initialize(conn, estimateList.getEstimateCodeTxt(), manLogin);
        } catch (SIDBAccessException sqle) {
          sqle.printStackTrace();
        }
        session.setAttribute(SIConfig.SISESSION_MAN_UPDATE_ESTIMATE, updateEstimate);
        session.setAttribute(SIConfig.SISESSION_MAN_ESTIMATE_LIST, estimateList);
        if (updateEstimate.getEstimate().getStatus().equals("1")) {
          forwardKey(request, response, "webshop.jsp.manager.estimate.updateestimate");
        } else {
          forwardKey(request, response, "webshop.jsp.manager.estimate.estimate.detail");
        }
      } else if (actionName.equals(SIConfig.SIACTION_MAIL)) {
        String keepnum = this.getParameter(urlParam, "keepnumberTxt");
        try {
          String fromMail = SIDBUtil.getFirstData(databaseConnection.getConnection(), "SELECT email FROM chargetbl WHERE chargecode=" + SIDBUtil.SQL2Str(manLogin.getUserCode()));
          SIBGUtil.sendKeepMail(databaseConnection.getConnection(), keepnum, "", fromMail);
          request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.mail"));
          try {
            databaseConnection.getConnection().commit();
          } catch (SQLException sqle) {}
          forwardKey(request, response, "webshop.jsp.manager.estimate.estimatelist");
        } catch (SIDBAccessException e) {
          try {
            databaseConnection.getConnection().rollback();
          } catch (SQLException sqle) {}
          SICustomErrors errors = new SICustomErrors();
          errors.addError(new SICustomError("manager.message.failure.mail"));
          request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
          forwardKey(request, response, "webshop.jsp.manager.estimate.estimatelist");
        }
      } else {
        forwardKey(request, response, "webshop.jsp.manager.estimate.estimatelist");
      }
    } catch (SQLException e) {
      e.printStackTrace();
      throw new ServletException();
    } catch (NamingException e) {
      e.printStackTrace();
      throw new ServletException();
    } finally {
      databaseConnection.close();
    }
  }
  
  public boolean deleteEstimate(Connection conn, String delTarget, String fromMail) throws SIDBAccessException {
    StringTokenizer delToken = new StringTokenizer(delTarget, "_");
    String estimateCode = delToken.nextToken();
    String keepNumber = delToken.nextToken();
    try {
      SIDeleteRec delRec = new SIDeleteRec("estimatetbl");
      delRec.addCondition("estimatecode", estimateCode);
      delRec.execute(conn);
      delRec = new SIDeleteRec("estimatedetailtbl");
      delRec.addCondition("estimatecode", estimateCode);
      delRec.execute(conn);
      delRec = new SIDeleteRec("estimatedeliverytbl");
      delRec.addCondition("estimatecode", estimateCode);
      delRec.execute(conn);
      return SIBGUtil.deleteKeep(conn, keepNumber, fromMail);
    } catch (SIDuplicateKeyException e) {
      throw new SIDBAccessException(e);
    }
  }
  
  public void destroy() {}
}
