/**
 * Copyright (c) 2003-2005 System Integrator Corporation.
 *                 All Rights Reserved.
 */
package jp.co.sint.beans.mallmgr;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;

import jp.co.sint.basic.SIBasic;
import jp.co.sint.basic.SILogin;
import jp.co.sint.basic.SIStoreStock;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDBUtil;
import jp.co.sint.tools.SIBGUtil;
import jp.co.sint.tools.SICheckDataConf;
import jp.co.sint.tools.SICheckValid;
import jp.co.sint.tools.SICustomError;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIURLParameter;
import jp.co.sint.tools.SIUtil;

import org.apache.log4j.Category;

/**
 * @version $Id: UIRegOrderShipment,v 1.0 2005/09/07 Exp $
 * @author  Tsustyoshi Yagi
 * <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>
 * Tsuyoshi Yagi   2005/09/07    Original
 */

public class UIRegOrderShipment extends SIBasic {
//ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);

  private String[] branchCodeTxt = null;
  
  private String[] branchNameTxt = null;

  private String[] amountTxt = null;

  private String[] allocationTxt = null;
  
  private String[] totalTxt=null;
  
  private int cnt = 0;
  
  private String orderCode="";
  
  private String cmdtyCode="";
  
  private String individualCode="";
  
  private String amount="";
  
  //EDBTG003-00 elecs-matsushima add start
  // セットコード
  private String setCode = "";
  
  // セット明細区分
  private String setDetailFlg = "";
  
  // 受注明細項番
  private String detailCode = "";
  
  //アドレスコード
  private String addressCode = "";
  //EDBTG003-00 elecs-matsushima add end

  /**
   * @return allocationTxt を戻します。
   */
  public String[] getAllocationTxt() {
    return allocationTxt;
  }
  /**
   * @param allocationTxt allocationTxt を設定。
   */
  public void setAllocationTxt(String[] allocationTxt) {
    this.allocationTxt = allocationTxt;
  }
  /**
   * @return amountTxt を戻します。
   */
  public String[] getAmountTxt() {
    return amountTxt;
  }
  /**
   * @param amountTxt amountTxt を設定。
   */
  public void setAmountTxt(String[] amountTxt) {
    this.amountTxt = amountTxt;
  }
  /**
   * @return branchCodeTxt を戻します。
   */
  public String[] getBranchCodeTxt() {
    return branchCodeTxt;
  }
  /**
   * @param branchCodeTxt branchCodeTxt を設定。
   */
  public void setBranchCodeTxt(String[] branchCodeTxt) {
    this.branchCodeTxt = branchCodeTxt;
  }
  /**
   * @return cnt を戻します。
   */
  public int getCnt() {
    return cnt;
  }
  /**
   * @param cnt cnt を設定。
   */
  public void setCnt(int cnt) {
    this.cnt = cnt;
  }
  
  /**
   * @return amount を戻します。
   */
  public String getAmount() {
    return amount;
  }
  /**
   * @param amount amount を設定。
   */
  public void setAmount(String amount) {
    this.amount = amount;
  }
  /**
   * @return cmdtyCode を戻します。
   */
  public String getCmdtyCode() {
    return cmdtyCode;
  }
  /**
   * @param cmdtyCode cmdtyCode を設定。
   */
  public void setCmdtyCode(String cmdtyCode) {
    this.cmdtyCode = cmdtyCode;
  }
  /**
   * @return individualCode を戻します。
   */
  public String getIndividualCode() {
    return individualCode;
  }
  /**
   * @param individualCode individualCode を設定。
   */
  public void setIndividualCode(String individualCode) {
    this.individualCode = individualCode;
  }
  /**
   * @return orderCode を戻します。
   */
  public String getOrderCode() {
    return orderCode;
  }
  /**
   * @param orderCode orderCode を設定。
   */
  public void setOrderCode(String orderCode) {
    this.orderCode = orderCode;
  }
  /**
   * @return branchNameTxt を戻します。
   */
  public String[] getBranchNameTxt() {
    return branchNameTxt;
  }
  /**
   * @param branchNameTxt branchNameTxt を設定。
   */
  public void setBranchNameTxt(String[] branchNameTxt) {
    this.branchNameTxt = branchNameTxt;
  }
  
  /**
   * @return totalTxt を戻します。
   */
  public String[] getTotalTxt() {
    return totalTxt;
  }
  /**
   * @param totalTxt totalTxt を設定。
   */
  public void setTotalTxt(String[] totalTxt) {
    this.totalTxt = totalTxt;
  }
  
  //EDBTG003-00 elecs-matsushima add start
  public String getSetDetailFlg() {
    return this.setDetailFlg;
  }
  
  public void setSetDetailFlg(String setDetailFlg) {
    if (SIUtil.isNull(setDetailFlg)) setDetailFlg = "";
    this.setDetailFlg = setDetailFlg;
  }
  
  public String getDetailCode() {
    return this.detailCode;
  }
  
  public void setDetailCode(String detailCode) {
    if (SIUtil.isNull(detailCode)) detailCode = "";
    this.detailCode = detailCode;
  }
  
  public String getSetCode() {
    return this.setCode;
  }
  
  public void setSetCode(String setCode) {
    if (SIUtil.isNull(setCode)) setCode = "";
    this.setCode = setCode;
  }
  
  public String getAddressCode() {
    return this.addressCode;
  }
  
  public void setAddressCode(String addressCode) {
    this.addressCode = addressCode;
  }
  // EDBTG003-00 elecs-matsushima add end
  
/**
   * init 入力したデータを基づいて、このbeansを設定します。
   * 
   * @param request
   * @return void
   */
  public void init(HttpServletRequest lRequest,SIURLParameter lUrlParam) {
    this.setEncode(SIConfig.SIENCODE_SHIFT_JIS);
    this.setBranchCodeTxt(lRequest.getParameterValues("branchCodeTxt"));
    this.setBranchNameTxt(lRequest.getParameterValues("branchNameTxt"));
    this.setAllocationTxt(lRequest.getParameterValues("allocationTxt"));
    this.setAmountTxt(lRequest.getParameterValues("amountTxt"));
    this.setTotalTxt(lRequest.getParameterValues("totalTxt"));
    this.setCmdtyCode(lRequest.getParameter("cmdtyCode"));
    this.setIndividualCode(lRequest.getParameter("individualCode"));
    this.setOrderCode(lRequest.getParameter("orderCode"));
    this.setAmount(lRequest.getParameter("amount"));
    //EDBTG003-00 elecs-matsushima add start
    this.setSetDetailFlg(lRequest.getParameter("setdetailflg"));
    this.setDetailCode(lRequest.getParameter("detailcode"));
    this.setSetCode(lRequest.getParameter("setcode"));
    this.setAddressCode(lRequest.getParameter("adcd"));
    //EDBTG003-00 elecs-matsushima add end
  }
  
  public boolean validate(HttpServletRequest lRequest, Connection conn) {
    SILogin lLogin = SIHTMLUtil.getLogin(lRequest);
    lRequest.removeAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY);
    SICustomErrors errors = new SICustomErrors();
    
    this.setCnt(this.createCnt(conn));
    
    for (int i = 0; i < this.getCnt(); i++) {
      SICheckValid.checkValid(errors, "出荷数" + this.branchNameTxt[i], this.allocationTxt[i],SICheckDataConf.SICHECK_DATA_EMPTY_TYPE);
      SICheckValid.checkValid(errors, "出荷数" + this.branchNameTxt[i], this.allocationTxt[i],SICheckDataConf.SICHECK_DATA_DIGIT_TYPE);
      if(errors.isEmpty() && Integer.parseInt(this.allocationTxt[i])>Integer.parseInt(this.totalTxt[i])){
        errors.addError((new SICustomError("manager.message.error.allocation3")));
      }
    }
    String sum="0";
    for(int i = 0; i < this.getCnt(); i++) {
      sum=SIUtil.add(sum,this.allocationTxt[i]);
    }
    if(!sum.equals(this.amount)){
      errors.addError((new SICustomError("manager.message.error.allocation")));
    }
    if (!errors.isEmpty())
      lRequest.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
    return errors.isEmpty();

  } 
  
  /**
   * getCollection
   * 
   * @param Connection
   * @return Collection
   * @throws SIDBAccessException
   */
  //EDBTG003-00 elecs-matsushima add start
//  public Collection getCollection(Connection dbConnection, String shopCode, String cmdtyCode,
//      String individualCode,String orderCode) throws SIDBAccessException {
  public Collection getCollection(Connection dbConnection, String shopCode, String cmdtyCode,
         String individualCode,String orderCode, String detailCode) throws SIDBAccessException {
  // EDBTG003-00 elecs-matsushima add end
    Collection storeStockColl = new ArrayList();
    Statement statement = null;
    ResultSet resultSet = null;
    SIStoreStock storeStock = new SIStoreStock();
    StringBuffer sqlStatement = new StringBuffer();
    sqlStatement
        .append("SELECT aa.branchcode,aa.branchname,aa.branchflg,bb.* FROM  branchtbl aa LEFT JOIN (");
    sqlStatement.append("SELECT * FROM storestocktbl WHERE shopcode = '" + shopCode + "' AND ");
    sqlStatement.append("cmdtycode = '" + cmdtyCode + "' AND individualcode = '" + individualCode
        + "') bb ");
    sqlStatement.append("ON aa.branchcode = bb.branchcode ORDER BY aa.branchcode");
    //実行
    try {
      statement = dbConnection.createStatement();
      log.debug("SQL=" + sqlStatement.toString());
      resultSet = statement.executeQuery(sqlStatement.toString());

      if (branchCodeTxt == null) {

        //商品レコードのセットの作成
        while (resultSet.next()) {
          storeStock = new SIStoreStock();
          storeStock.setShopCode(resultSet.getString("shopcode"));
          storeStock.setCmdtyCode(resultSet.getString("cmdtycode"));
          storeStock.setIndividualCode(resultSet.getString("individualcode"));
          storeStock.setBranchCode(resultSet.getString("branchcode"));
          storeStock.setSalesPriorityFlg(resultSet.getString("salespriorityflg"));
          storeStock.setAmount(resultSet.getString("amount"));
          if (SIUtil.isNull(storeStock.getAmount())) {
            storeStock.setAmount("0");
          }
          // EDBTG003-00 mod start
//          storeStock.setAllocation(SIBGUtil.getAllocationNum(dbConnection,orderCode,storeStock.getShopCode(),storeStock.getCmdtyCode(),storeStock.getIndividualCode(),storeStock.getBranchCode()));
          storeStock.setAllocation(SIBGUtil.getAllocationNum(dbConnection,orderCode,storeStock.getShopCode(),storeStock.getCmdtyCode(),storeStock.getIndividualCode(),storeStock.getBranchCode(), detailCode));
          // EDBTG003-00 mod end
          storeStock.setInitDateTime(resultSet.getString("initdatetime"));
          storeStock.setUpdateDateTime(resultSet.getString("updatedatetime"));
          storeStock.setBranchName(resultSet.getString("branchname"));
          storeStock.setBranchFlg(resultSet.getString("branchflg"));
          storeStock.setTotal(SIUtil.add(storeStock.getAmount(),storeStock.getAllocation()));
          int after=Integer.parseInt(storeStock.getTotal())-Integer.parseInt(storeStock.getAllocation());
          storeStock.setAfter(Integer.toString(after));
          storeStockColl.add(storeStock);
        }
      } else {
        //商品レコードのセットの作成
        int count=0;
        while (resultSet.next()) {
          storeStock = new SIStoreStock();
          storeStock.setShopCode(resultSet.getString("shopcode"));
          storeStock.setCmdtyCode(resultSet.getString("cmdtycode"));
          storeStock.setIndividualCode(resultSet.getString("individualcode"));
          storeStock.setBranchCode(resultSet.getString("branchcode"));
          storeStock.setAmount(resultSet.getString("amount"));
          storeStock.setAllocation(this.allocationTxt[count]);
          storeStock.setTotal(this.totalTxt[count]);
          storeStock.setInitDateTime(resultSet.getString("initdatetime"));
          storeStock.setUpdateDateTime(resultSet.getString("updatedatetime"));
          storeStock.setBranchName(resultSet.getString("branchname"));
          storeStock.setBranchFlg(resultSet.getString("branchflg"));
          try{
          int after=Integer.parseInt(storeStock.getTotal())-Integer.parseInt(storeStock.getAllocation());
          storeStock.setAfter(Integer.toString(after));
          }catch(NumberFormatException e){
            storeStock.setAfter("0");
          }
          
          storeStockColl.add(storeStock);
          count++;
        }
      }
    } catch (Exception ex) {
      log.debug("exception sql = " + sqlStatement.toString());
      throw new SIDBAccessException(ex);
    } finally {
      SIDBUtil.close(resultSet, statement);
    }
    return storeStockColl;
  }
  
  public int createCnt(Connection conn) {
    ResultSet resultSet = null;
    StringBuffer sqlStatement = new StringBuffer();
    Statement statement = null;
    int count = 0;
    sqlStatement.append("SELECT count(*) as count FROM  branchtbl ");
    //実行
    try {
      statement = conn.createStatement();
      log.debug("SQL=" + sqlStatement.toString());
      resultSet = statement.executeQuery(sqlStatement.toString());
      while (resultSet.next()) {
        count = (resultSet.getInt("count"));
      }
    } catch (Exception ex) {
      log.debug("exception sql = " + sqlStatement.toString());
      ex.printStackTrace();
    } finally {
      SIDBUtil.close(resultSet, statement);
    }
    return count;
  }
  
  public LinkedHashMap setMap(){
    LinkedHashMap map = new LinkedHashMap();
    String sum="0";
    for (int i = 0; i < this.getCnt(); i++) {
      map.put(this.branchCodeTxt[i],this.allocationTxt[i]);
      sum=SIUtil.add(sum,this.allocationTxt[i]);
    }
    map.put("sum",sum);
    return map;
  }
}
