package jp.co.sint.beans.mallmgr;

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

import jp.co.sint.basic.SIBasic;
import jp.co.sint.basic.SICmdty;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDBUtil;
import jp.co.sint.tools.SIBGUtil;
import jp.co.sint.tools.SIUtil;

public class UIRegReceipt extends SIBasic {
  
  // 商品一覧
  private Collection cmdtyList = new ArrayList();
  
  // 顧客名
  private String custName = "";
  
  // 合計金額
  private String totalOfPrice = "0";
  
  // クレジット支払い金額
  private String sumOfCardPayment = "0";
  
  // 代引き支払い金額
  private String sumOfExchangePayment = "0";
  
  // 銀行振り込み金額
  private String sumOfTransferPayment = "0";
  
  // 現金支払額
  private String sumOfCashPayment = "0";
  
  // 送料
  private String totalOfDeliveryFee = "0";
  
  // 手数料
  private String totalOfFee = "0";
  
  // 値引き額
  private String sumOfDiscount = "0";
  
  // ポイント使用額
  private String sumByPoint = "0";
  
  // ポイント残高
  private String pointExists = "0";
  
  // 予定獲得ポイント
  private String pointValue = "0";
  
  // 担当者コード
  private String chargeCode = "";
  
  // 担当者
  private String chargeName = "";
  
  // 受注番号
  private String orderCode = "";
  
  // 発行ユーザー支店
  private String userBranch = "";
  
  // 発行日時
  private String issueDateTime = "";
  
  // 未発行フラグ
  private boolean issueFlg = true;
  
  // ポイント表示するかどうか（上様の場合表示しない）
  private boolean pointEnabledFlg = true;
  
  // EDBTG003-00 cmt-okuda add start
  // セット値引き額
  private String sumOfSetDiscount = "0";
  //EDBTG003-00 cmt-okuda add end
  
  private String taxRate = "0";
  
  public UIRegReceipt() {}
  
  public UIRegReceipt(String orderCode) {
    this.setOrderCode(orderCode);
  }
  
  // getter of chargeCode
  public String getChargeCode() {
    return this.chargeCode;
  }
  
  // getter of chargeName
  public String getChargeName() {
    return this.chargeName;
  }
  
  // getter of cmdtyList
  public Collection getCmdtyList() {
    return this.cmdtyList;
  }
  
  // getter of custName
  public String getCustName() {
    return this.custName;
  }
  
  // getter of orderCode
  public String getOrderCode() {
    return this.orderCode;
  }
  
  // getter of pointEnabledFlg
  public boolean isPointEnabledFlg() {
    return this.pointEnabledFlg;
  }
  
  // getter of pointExists
  public String getPointExists() {
    return this.pointExists;
  }
  
  // getter of pointValue
  public String getPointValue() {
    return this.pointValue;
  }
  
  // getter of issueFlg
  public boolean isIssueFlg() {
    return this.issueFlg;
  }
  
  //getter of issueDateTime
  public String getIssueDateTime() {
    return this.issueDateTime;
  }
  
  // getter of sumByPoint
  public String getSumByPoint() {
    return this.sumByPoint;
  }
  
  // getter of sumOfCardPayment
  public String getSumOfCardPayment() {
    return this.sumOfCardPayment;
  }
  
  // getter of sumOfCashPayment
  public String getSumOfCashPayment() {
    return this.sumOfCashPayment;
  }
  
  // getter of sumOfDiscount
  public String getSumOfDiscount() {
    return this.sumOfDiscount;
  }
  
  // getter of sumOfExchangePayment
  public String getSumOfExchangePayment() {
    return this.sumOfExchangePayment;
  }
  
  // getter of sumOfTransferPayment
  public String getSumOfTransferPayment() {
    return this.sumOfTransferPayment;
  }
  
  // getter of totalOfDeliveryFee
  public String getTotalOfDeliveryFee() {
    return this.totalOfDeliveryFee;
  }
  
  // getter of totalOfFee
  public String getTotalOfFee() {
    return this.totalOfFee;
  }
  
  // getter of totalOfPrice
  public String getTotalOfPrice() {
    return this.totalOfPrice;
  }
  
  //getter of userBranch
  public String getUserBranch() {
    return this.userBranch;
  }
  
  // setter of chargeCode
  public void setChargeCode(String chargeCode) {
    if (SIUtil.isNull(chargeCode)) chargeCode = "";
    this.chargeCode = SIUtil.changeTo(chargeCode.trim(), this.encode);
  }
  
  // setter of chargeName
  public void setChargeName(String chargeName) {
    if (SIUtil.isNull(chargeName)) chargeName = "";
    this.chargeName = SIUtil.changeTo(chargeName.trim(), this.encode);
  }
  
  // setter of cmdtyList
  public void setCmdtyList(Collection cmdtyList) {
    this.cmdtyList = cmdtyList;
  }
  
  // setter of custName
  public void setCustName(String custName) {
    if (SIUtil.isNull(custName)) custName = "";
    this.custName = SIUtil.changeTo(custName.trim(), this.encode);
  }
  
  // setter of orderCode
  public void setOrderCode(String orderCode) {
    if (SIUtil.isNull(orderCode)) orderCode = "";
    this.orderCode = SIUtil.changeTo(orderCode.trim(), this.encode);
  }
  
  // setter of pointEnabledFlg
  public void setPointEnabledFlg(boolean pointEnabledFlg) {
    this.pointEnabledFlg = pointEnabledFlg;
  }
  
  // setter of pointExists
  public void setPointExists(String pointExists) {
    if (SIUtil.isNull(pointExists)) pointExists = "";
    this.pointExists = SIUtil.changeTo(pointExists.trim(), this.encode);
  }
  
  // setter of pointValue
  public void setPointValue(String pointValue) {
    if (SIUtil.isNull(pointValue)) pointValue = "";
    this.pointValue = SIUtil.changeTo(pointValue.trim(), this.encode);
  }
  
  // setter of issueFlg
  public void setIssueFlg(boolean issueFlg) {
    this.issueFlg = issueFlg;
  }
  
  //setter of issueDateTime
  public void setIssueDateTime(String issueDateTime) {
    if (SIUtil.isNull(issueDateTime)) issueDateTime = "";
    this.issueDateTime = SIUtil.changeTo(issueDateTime.trim(), this.encode);
  }
  
  // setter of sumByPoint
  public void setSumByPoint(String sumByPoint) {
    if (SIUtil.isNull(sumByPoint)) sumByPoint = "";
    this.sumByPoint = SIUtil.changeTo(sumByPoint.trim(), this.encode);
  }
  
  // setter of sumOfCardPayment
  public void setSumOfCardPayment(String sumOfCardPayment) {
    if (SIUtil.isNull(sumOfCardPayment)) sumOfCardPayment = "";
    this.sumOfCardPayment = SIUtil.changeTo(sumOfCardPayment.trim(), this.encode);
  }
  
  // setter of sumOfCashPayment
  public void setSumOfCashPayment(String sumOfCashPayment) {
    if (SIUtil.isNull(sumOfCashPayment)) sumOfCashPayment = "";
    this.sumOfCashPayment = SIUtil.changeTo(sumOfCashPayment.trim(), this.encode);
  }
  
  // setter of sumOfDiscount
  public void setSumOfDiscount(String sumOfDiscount) {
    if (SIUtil.isNull(sumOfDiscount)) sumOfDiscount = "";
    this.sumOfDiscount = SIUtil.changeTo(sumOfDiscount.trim(), this.encode);
  }
  
  // setter of sumOfExchangePayment
  public void setSumOfExchangePayment(String sumOfExchangePayment) {
    if (SIUtil.isNull(sumOfExchangePayment)) sumOfExchangePayment = "";
    this.sumOfExchangePayment = SIUtil.changeTo(sumOfExchangePayment.trim(), this.encode);
  }
  
  // setter of sumOfTransferPayment
  public void setSumOfTransferPayment(String sumOfTransferPayment) {
    if (SIUtil.isNull(sumOfTransferPayment)) sumOfTransferPayment = "";
    this.sumOfTransferPayment = SIUtil.changeTo(sumOfTransferPayment.trim(), this.encode);
  }
  
  // setter of totalOfDeliveryFee
  public void setTotalOfDeliveryFee(String totalOfDeliveryFee) {
    if (SIUtil.isNull(totalOfDeliveryFee)) totalOfDeliveryFee = "";
    this.totalOfDeliveryFee = SIUtil.changeTo(totalOfDeliveryFee.trim(), this.encode);
  }
  
  // setter of totalOfFee
  public void setTotalOfFee(String totalOfFee) {
    if (SIUtil.isNull(totalOfFee)) totalOfFee = "";
    this.totalOfFee = SIUtil.changeTo(totalOfFee.trim(), this.encode);
  }
  
  // setter of totalOfPrice
  public void setTotalOfPrice(String totalOfPrice) {
    if (SIUtil.isNull(totalOfPrice)) totalOfPrice = "";
    this.totalOfPrice = SIUtil.changeTo(totalOfPrice.trim(), this.encode);
  }
  
  //setter of userBranch
  public void setUserBranch(String userBranch) {
    if (SIUtil.isNull(userBranch)) userBranch = "";
    this.userBranch = SIUtil.changeTo(userBranch.trim(), this.encode);
  }
  
  // 合計
  public String getTotalOfPrice1() {
  //EDBTG003-00 cmt-okuda mod start
//      return SIUtil.sub(SIUtil.add(totalOfPrice, SIUtil.add(totalOfFee, totalOfDeliveryFee)),SIUtil.add(sumByPoint, sumOfDiscount));
      return SIUtil.sub(SIUtil.add(totalOfPrice, SIUtil.add(totalOfFee, totalOfDeliveryFee)),SIUtil.add(SIUtil.add(sumByPoint, sumOfDiscount), sumOfSetDiscount));
   //EDBTG003-00 cmt-okuda mod end
  }
  
  // 現金残高
  public String getTotalOfPrice2() {
    return SIUtil.sub(getTotalOfPrice1(), SIUtil.add(sumOfCardPayment, sumOfExchangePayment, sumOfTransferPayment));
  }
  
  // 内税
  public String getInnerTax() {
    return SIUtil.sub(getTotalOfPrice1(), SIUtil.getPriceWithoutTax(getTotalOfPrice1(), getTaxRate()));
  }
  
  // お釣り
  public String getChange() {
    return SIUtil.sub(this.getSumOfCashPayment(), getTotalOfPrice2());
  }

  public boolean validate(Connection lConnection) {
    if (SIUtil.isNull(this.getOrderCode())) return false;
    try {
      return SIDBUtil.hasData(lConnection, "SELECT * FROM orderlatestvw WHERE status='1' AND ordercode =" + SIDBUtil.SQL2Str(orderCode));
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  //EDBTG003-00 cmt-okuda add start
 // セット値引き額
  public String getSumOfSetDiscount() {
    return sumOfSetDiscount;
  }
   
  public void setSumOfSetDiscount(String sumOfSetDiscount) {
    if (SIUtil.isNull(sumOfSetDiscount)) sumOfSetDiscount = "";
    this.sumOfSetDiscount = sumOfSetDiscount;
  }
  //EDBTG003-00 cmt-okuda add end
 // 税率
  public String getTaxRate() {
    return taxRate;
  }
   
  public void setTaxRate(String taxRate) {
    if (SIUtil.isNull(taxRate)) taxRate = "";
    this.taxRate = taxRate;
  }
  
  public boolean reset(Connection lConnection) {
    boolean result = false;
    if (SIUtil.isNull(this.getOrderCode())) return result;
    
    Statement lStatement = null;
    ResultSet lResultSet = null;
    StringBuffer orderSql = new StringBuffer();
    StringBuffer cmdtySql = new StringBuffer();
    SICmdty lCmdty = null;
    Collection cmdtys = new ArrayList();
    
    orderSql.append("SELECT a.custCode, a.custName, a.totalOfPrice, a.sumByPoint, a.sumOfDiscount, a.chargeCode, ");
    //EDBTG003-00 cmt-okuda add start
    orderSql.append("a.setdiscount, ");
    //EDBTG003-00 cmt-okuda add end
    orderSql.append("a.totalOfDeliveryFee + a.discountDeliveryFee AS totalOfDeliveryFee, ");
    orderSql.append("a.totalOfFee + a.discountFee AS totalOfFee, ");
    orderSql.append("coalesce(b.sumOfCardPayment, 0) AS sumOfCardPayment, ");
    orderSql.append("coalesce(b.sumOfExchangePayment, 0) AS sumOfExchangePayment, ");
    orderSql.append("coalesce(b.sumOfTransferPayment, 0) AS sumOfTransferPayment, ");
    orderSql.append("coalesce(b.sumOfCashPayment, 0) AS sumOfCashPayment, ");
    orderSql.append("c.pointExists, c.pointValue, d.issueDateTime, e.chargeName, a.taxrate ");
    orderSql.append("FROM ordersumvw a ");
    orderSql.append("LEFT OUTER JOIN chargetbl e ON a.chargecode = e.chargecode ");
    orderSql.append("LEFT OUTER JOIN receiptissuetbl d ON a.ordercode = d.ordercode ");
    orderSql.append("LEFT OUTER JOIN (SELECT ordercode, sum(CASE WHEN paymenttype = '現金' THEN paymentprice ELSE 0 END) AS sumOfCashPayment, ");
    orderSql.append("sum(CASE WHEN paymenttype = 'カード' THEN paymentprice WHEN paymenttype = '店頭カード' THEN paymentprice ELSE 0 END) AS sumOfCardPayment, ");
    orderSql.append("sum(CASE WHEN paymenttype = '代金引換' THEN paymentprice ELSE 0 END) AS sumOfExchangePayment, ");
    orderSql.append("sum(CASE WHEN paymenttype = '銀行振込' THEN paymentprice ELSE 0 END) AS sumOfTransferPayment ");
    orderSql.append("FROM paymenttbl ");
    orderSql.append("WHERE status='0' AND paymentdate IS NOT NULL AND ordercode = ").append(SIDBUtil.SQL2Str(this.getOrderCode()," "));
    orderSql.append("GROUP BY ordercode) b ");
    orderSql.append("ON a.ordercode = b.ordercode , ");
    orderSql.append("(SELECT custcode,sum(CASE WHEN enableflg='1' THEN pointofissue ELSE 0 END) AS pointExists, ");
    orderSql.append("sum(CASE WHEN pointofissue > 0 AND enableflg='2' ");
    orderSql.append("AND ordercode = ").append(SIDBUtil.SQL2Str(this.getOrderCode()," "));
    orderSql.append("THEN pointofissue ELSE 0 END) AS pointValue ");
    orderSql.append("FROM pointmanmtbl GROUP BY custcode) c ");
    orderSql.append("WHERE a.custcode = c.custcode AND a.ordercode = ").append(SIDBUtil.SQL2Str(this.getOrderCode()," "));
    
    //EDBTG003-00 cmt-okuda mod start
//    cmdtySql.append("SELECT individualcode, cmdtyname, price, amount FROM orderdetaillatestvw ");
    cmdtySql.append("SELECT individualcode, cmdtyname, price, amount, setindividualcode, cmdtycode, setdetailflg FROM orderdetaillatestvw ");
    //EDBTG003-00 cmt-okuda mod end
    cmdtySql.append("WHERE ordercode = ").append(SIDBUtil.SQL2Str(this.getOrderCode()," "));
    // EDBTG003-00 cmt-okuda mod start
    //cmdtySql.append("ORDER BY deliverycode, detailcode");
    cmdtySql.append(" ORDER BY setcode, setdetailcode, DetailCode, cmdtycode, individualcode ");
    // EDBTG003-00 cmt-okuda mod end
    
    try {
      lStatement = lConnection.createStatement();
      lResultSet = lStatement.executeQuery(orderSql.toString());
      
      if (lResultSet.next()) {
        this.setCustName(lResultSet.getString("custname"));
        this.setTotalOfPrice(lResultSet.getString("totalOfPrice"));
        this.setTotalOfDeliveryFee(lResultSet.getString("totalOfDeliveryFee"));
        this.setTotalOfFee(lResultSet.getString("totalOfFee"));
        this.setSumByPoint(lResultSet.getString("sumByPoint"));
        this.setSumOfDiscount(lResultSet.getString("sumOfDiscount"));
        this.setSumOfCardPayment(lResultSet.getString("sumOfCardPayment"));
        this.setSumOfExchangePayment(lResultSet.getString("sumOfExchangePayment"));
        this.setSumOfTransferPayment(lResultSet.getString("sumOfTransferPayment"));
        this.setSumOfCashPayment(lResultSet.getString("sumOfCashPayment"));
        this.setIssueFlg(SIUtil.isNotNull(lResultSet.getString("issueDateTime")));
        this.setPointExists(lResultSet.getString("pointExists"));
        this.setPointValue(lResultSet.getString("pointValue"));
        this.setChargeCode(lResultSet.getString("chargeCode"));
        this.setChargeName(lResultSet.getString("chargeName"));
        this.setTaxRate(lResultSet.getString("taxRate"));
        //EDBTG003-00 cmt-okuda add start
        this.setSumOfSetDiscount(lResultSet.getString("setdiscount"));
        //EDBTG003-00 cmt-okuda add end
        if (this.getPointValue().equals("0") || lResultSet.getString("custCode").equals("10")) {
          this.setPointEnabledFlg(false);
        } else {
          this.setPointEnabledFlg(true);
        }
      } else return false;
      
      lResultSet = lStatement.executeQuery(cmdtySql.toString());
      
      while (lResultSet.next()) {
        lCmdty = new SICmdty();
        //EDBTG003-00 cmt-okuda mod start
//        lCmdty.setIndividualCode(lResultSet.getString("individualCode"));
        String strSetcode = lResultSet.getString("setindividualcode");
        if (SIUtil.isNull(strSetcode) || strSetcode.equals("")) {
            lCmdty.setIndividualCode(lResultSet.getString("individualCode"));
            lCmdty.setCmdtyName(getLimitedCmdtyName(lResultSet.getString("cmdtyName")));
        } else {
            lCmdty.setIndividualCode(strSetcode + "(" + lResultSet.getString("individualCode") + ")");
            lCmdty.setCmdtyName(getLimitedCmdtyName(SIBGUtil.getCmdtyFullName(lConnection,lResultSet.getString("cmdtycode"),lResultSet.getString("individualCode"),lResultSet.getString("setdetailflg"))));
        }
        //EDBTG003-00 cmt-okuda mod end
        lCmdty.setUnitPrice(lResultSet.getString("price"));
        lCmdty.setAmount(lResultSet.getString("amount"));
        cmdtys.add(lCmdty);
        result = true;
      }
      
      this.setCmdtyList(cmdtys);
      return result;
      
    } catch (SQLException e) {
      e.printStackTrace();
      return false;
    //EDBTG003-00 cmt-okuda mod start
    } catch (SIDBAccessException e) {
      e.printStackTrace();
      return false;
    //EDBTG003-00 cmt-okuda mod end
    }
  }
  private String getLimitedCmdtyName(String cmdtyName) {
    if(cmdtyName.getBytes().length > 43){
      int i = 0;
      while (cmdtyName.substring(0, cmdtyName.length() - i).getBytes().length > 43){
        i++;
      }
      cmdtyName = cmdtyName.substring(0, cmdtyName.length() - i);
    }
    return cmdtyName;
  }
  
  public void updateReceiptIssue(Connection lConnection){
    if (SIUtil.isNull(orderCode) || SIUtil.isNull(issueDateTime)) return;
    try{
      if(!SIDBUtil.hasData(lConnection, "SELECT * FROM receiptissuetbl WHERE ordercode = "+SIDBUtil.SQL2Str(orderCode))) {
        SIDBUtil.execSQL(lConnection, "INSERT INTO receiptissuetbl VALUES("+SIDBUtil.SQL2Str(orderCode,",")+SIDBUtil.SQL2Str(issueDateTime,")"));
        lConnection.commit();
      }
    } catch (Exception e) {
      return;
    }
    return;
  }
}
