/** 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 java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

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.SICustPoint;
import jp.co.sint.basic.SILogin;
import jp.co.sint.beans.mallmgr.UICustPointListCond;
import jp.co.sint.config.SIConfig;
import jp.co.sint.config.SIDBMultiConf;
import jp.co.sint.config.SIFlagConf;
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.SIInsertRec;
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.SIFlagUtil;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIURLMap;
import jp.co.sint.tools.SIUtil;

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

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

public class SIRegCustPointSrv 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 追加
    SIRegMngAccesslogSrv siRegMngAccesslogSrv = new SIRegMngAccesslogSrv();
    try{
      Connection connection;
      
      String actionName=this.getActionName(urlParam);//画面からのアクション  //7.1.1 ST0236 修正
      String editMode = this.getEditMode(urlParam); //DBへの編集モード  //7.1.1 ST0236 修正
      
      UICustPointListCond custpointList = new UICustPointListCond();
      
      //データベースへのコネクションの作成
      connection = databaseConnection.getConnection();
      log.debug("doUpdate:actionName=" + actionName + ",editMode=" + editMode);
      
      //検索
      if(SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)){
        //データの取得とデータのチェック
        custpointList.init(request,urlParam);//7.1.1 ST0236 修正
        custpointList.validate(request, connection);
        session.setAttribute(SIConfig.SISESSION_MAN_CUSTPOINT_LIST_NAME, custpointList);
        forwardKey(request, response, "webshop.jsp.manager.custpoint.list");
      //無効ポイントの削除
      }else if(SIConfig.SIACTION_DELETE.equalsIgnoreCase(actionName)){
        try{
          custpointList =(UICustPointListCond)session.getAttribute(SIConfig.SISESSION_MAN_CUSTPOINT_LIST_NAME);
          if(custpointList==null) custpointList = new UICustPointListCond();
          //検索表示データの無効ポイント削除
          SILogin lLogin=SIHTMLUtil.getLogin(request);
          deleteTableData(custpointList, connection,lLogin);
          try{databaseConnection.getConnection().commit();}catch(SQLException ee){ee.printStackTrace();}
          request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,SIErrorFactory.getErrorMsg("manager.message.success.delete"));
        }catch(SIDuplicateKeyException sqle){
          try{databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
          SICustomErrors errors = new SICustomErrors();
          errors.addError(new SICustomError("database.insert.duplicate"));
          request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
        }catch(SIDBAccessException sqle){
          try{databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
          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.custpoint.list");
      }else if(SIConfig.SIACTION_MODIFY.equalsIgnoreCase(actionName)){
        custpointList.initModify(request);
        String comment = (String) urlParam.getParam("comment");
        try{
          if(custpointList.validateModify(request,custpointList,databaseConnection.getConnection())){
            String lDateTime = new SIDateTime().getFullDateTime();
            insertTableData(connection,custpointList,request,comment,lDateTime);
            siRegMngAccesslogSrv.insertTableData(databaseConnection.getConnection(), request, "15", lDateTime);
            try{databaseConnection.getConnection().commit();}catch(SQLException ee){ee.printStackTrace();}
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,SIErrorFactory.getErrorMsg("manager.message.success.insert"));
            String lUrl=SIURLMap.getUrl("webshop.servlet.manager.custpoint")+"?actionNameTxt="+SIConfig.SIACTION_REFRESH;
            redirectHttps(request, response, lUrl);//7.1.1 ST0174 修正
          }else{
            forwardKey(request, response, "webshop.jsp.manager.custpoint.list");
          }
        }catch(SIDuplicateKeyException sqle){
          try{databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
          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.custpoint.list");
        }catch(SIDBAccessException sqle){
          try{databaseConnection.getConnection().rollback();}catch(SQLException ee){ee.printStackTrace();}
          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.custpoint.list");
        }
      }else if(SIConfig.SIACTION_REFRESH.equals(actionName)){
        request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,SIErrorFactory.getErrorMsg("manager.message.success.insert"));
        forwardKey(request, response, "webshop.jsp.manager.custpoint.list");
      }
    }catch (SQLException e){
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e){
      e.printStackTrace();
      throw new ServletException();
    }finally{
      databaseConnection.close();
    }
  }
  
  /**
   * 
   * @param connection
   * @param listCond
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public void insertTableData(Connection connection,UICustPointListCond listCond,HttpServletRequest request,String comment,String now) throws SIDuplicateKeyException, SIDBAccessException{
    SILogin manLogin=SIHTMLUtil.getLogin(request);
    for(int i=0;i<listCond.getCustCodeTxt().length;i++){
      if(SIUtil.isNotNull(listCond.getAddPointTxt()[i]) && !listCond.getAddPointTxt()[i].equals("0")){
        SIInsertRec lInsertRec = new SIInsertRec();
        lInsertRec.setTableName("pointmanMtbl");
        String rfmAnalyseCode=SIDBUtil.getFirstData(connection,SIDBUtil.getNextVal("POINTMANMTBL_POINTMANCD_SEQ"));
        lInsertRec.add("pointmancode",rfmAnalyseCode);
        lInsertRec.add("custcode",listCond.getCustCodeTxt()[i]);
        lInsertRec.add("mallshopcode",manLogin.getMallShopCode());
        lInsertRec.add("Issueflg","2");
        lInsertRec.add("pointofissue",listCond.getAddPointTxt()[i]);
        lInsertRec.add("enableflg","1");
        lInsertRec.add("ordercode","");
        lInsertRec.add("reviewcode","");
        lInsertRec.add("issuedatetime",now);
        lInsertRec.execute(connection);
        
        SIInsertRec lInsertRec2 = new SIInsertRec("investpointlogtbl");
        lInsertRec2.add("pointmancode",rfmAnalyseCode);
        lInsertRec2.add("custcode",listCond.getCustCodeTxt()[i]);
        lInsertRec2.add("pointofissue",listCond.getAddPointTxt()[i]);
        lInsertRec2.add("usercode",manLogin.getUserCode());
        lInsertRec2.add("username",manLogin.getUserName());
        lInsertRec2.add("comment",SIFlagUtil.getFlagName(SIFlagConf.SIFLAG_INVEST_POINT_REASON_FLG_INX, listCond.getAddReason())+listCond.getComment());
        lInsertRec2.add("initdatetime",now);
        lInsertRec2.add("ordercode",listCond.getOrderCode());
        lInsertRec2.execute(connection);
      }
    }
  }
  
  public void deleteTableData(UICustPointListCond custpointList, Connection connection,SILogin lLogin) throws SIDuplicateKeyException, SIDBAccessException{
    SIDeleteRec lDeleteRec = new SIDeleteRec();
    Collection custColl = new ArrayList();
    SICustPoint custPoint = new SICustPoint();
    
    custColl=custpointList.getCollection(connection,lLogin);
    
    Iterator custIte = custColl.iterator();
    while(custIte.hasNext()){
      lDeleteRec=new SIDeleteRec();
      custPoint = (SICustPoint)custIte.next();
      lDeleteRec.setTableName("pointmanMtbl");
      lDeleteRec.addCondition("enableFlg", "0");
      lDeleteRec.addCondition("custcode",custPoint.getCustCode());
      
      //データの更新
      log.debug("delete sql=" + lDeleteRec.getSQL());
      //String l = lDeleteRec.getSQL();
      lDeleteRec.execute(connection);
    }
  }
}
