package nc.ui.cmp.settlement.actions;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.util.List;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.cmp.utils.CmpUtils;
import nc.cmp.utils.DataUtil;
import nc.cmp.utils.SettleUtils;
import nc.desktop.ui.WorkbenchEnvironment;
import nc.itf.cmp.ebank.copy.ICopyCMPPaymentService;
import nc.itf.cmp.ebank.ICMPPaymentService;
import nc.itf.cmp.settlement.ISettlementQueryService;
import nc.pubitf.obm.IObmBuluUI;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.uif2.ShowStatusBarMsgUtil;
import nc.vo.cmp.BusiStatus;
import nc.vo.cmp.SettleStatus;
import nc.vo.cmp.settlement.NetpayTransferVO;
import nc.vo.cmp.settlement.SettleEnumCollection;
import nc.vo.cmp.settlement.SettlementAggVO;
import nc.vo.cmp.settlement.SettlementBodyVO;
import nc.vo.cmp.settlement.SettlementHeadVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.obm.pay.OnlinePaymentVO;
import nc.vo.obm.pay.PaymentRetMsg;
import nc.vo.obm.sec.ObmCAInfoAccessor;
import nc.vo.obm.sec.ObmCASignature;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;

public class ZfNewAction
  extends SettleDefaultAction
{
  ICopyCMPPaymentService paymentService = (ICopyCMPPaymentService)NCLocator.getInstance().lookup(ICopyCMPPaymentService.class);
  private SettlementAggVO[] aggVOs;
  private IObmBuluUI ebank;
	
	
  private static final long serialVersionUID = 8899125168078379198L;
  
  public ZfNewAction()
  {
    setBtnName("按单合并支付");
    putValue("ZfNewAction", getBtnName());
    putValue("Code", "按单合并支付");
  }
  
  public void doAction(ActionEvent e)
    throws Exception
  {
    SettlementAggVO[] aggvos = null;
    try
    {
      Object obj = getValue();
      if (obj.getClass().isArray()) {
        aggvos = (SettlementAggVO[])obj;
      } else {
        aggvos = new SettlementAggVO[] { (SettlementAggVO)obj };
      }
      
      StringBuffer error = new StringBuffer("业务单据编号:");
		for (SettlementAggVO settlementAggVO : aggvos) {
			//表头原币金额
			UFDouble headPrimal = (UFDouble) settlementAggVO.getParentVO().getAttributeValue("primal");
			//表体原币金额
			UFDouble bodyPrimal = new UFDouble(0.00);
			SettlementBodyVO [] settlementBodyVOs = (SettlementBodyVO[]) settlementAggVO.getChildrenVO();
			for (SettlementBodyVO settlementBodyVO : settlementBodyVOs) {
				bodyPrimal = bodyPrimal.add(settlementBodyVO.getPay_last());
			}
			if(headPrimal.compareTo(bodyPrimal) != 0) {
				String billcode = (String) settlementAggVO.getParentVO().getAttributeValue("billcode");
				error.append(billcode);
				error.append(",");
			}
		}
		if(error.length() != 7) {
			throw new BusinessException(error+"表体合计金额不等于表头金额!");
		}
      
      List<SettlementAggVO> aggLst = SettleUtils.filterSettleInfo4NetSettleFlagUnSettle(aggvos);
      if (aggLst.size() == 0)
      {
        ShowStatusBarMsgUtil.showErrorMsg(NCLangRes4VoTransl.getNCLangRes().getStrByID("3607set1_0", "03607set1-0078"), NCLangRes4VoTransl.getNCLangRes().getStrByID("3607set1_0", "03607set1-0079"), getModel().getContext());
        return;
      }
      aggvos = (SettlementAggVO[])aggLst.toArray(new SettlementAggVO[0]);
      ((ICMPPaymentService)NCLocator.getInstance().lookup(ICMPPaymentService.class)).validateCombinPay(aggvos);
	      getEdit().getClientSigner().checkIfCASign();
      

      int i = MessageDialog.showYesNoDlg(getEdit(), NCLangRes4VoTransl.getNCLangRes().getStrByID("3607set_0", "03607set-0029"), NCLangRes4VoTransl.getNCLangRes().getStrByID("3607set_0", "03607set-0050"));
      if (i != 4) {
        return;
      }
      Integer doZhifu = doZhifu(getEdit(), aggvos);
      if (doZhifu.intValue() == -1) {
        return;
      }
      List<String> pkLst = CmpUtils.makeList();
      for (SettlementAggVO aggvo : aggvos) {
        pkLst.add(aggvo.getParentVO().getPrimaryKey());
      }
      aggvos = ((ISettlementQueryService)NCLocator.getInstance().lookup(ISettlementQueryService.class)).querySettlementAggVOsByPks((String[])pkLst.toArray(new String[0]));
      if (!isListSelected()) {
        getEdit().setLoadBean(aggvos[0]);
      }
      getModel().directlyUpdate(aggvos);
      getEdit().setValue(aggvos[0]);
      

      ShowStatusBarMsgUtil.showStatusBarMsg(NCLangRes4VoTransl.getNCLangRes().getStrByID("3607set_0", "03607set-0051"), getModel().getContext());
    }
    catch (BusinessException be)
    {
      Logger.error(be.getMessage(), be);
      throw new BusinessException(be.getMessage());
    }
  }
  
  protected boolean isActionEnable()
  {
    SettlementAggVO[] aggvos = getSelectedAggVOs();
    if ((aggvos == null) || (aggvos.length == 0) || (aggvos[0] == null)) {
      return false;
    }
    for (SettlementAggVO settlementAggVO : aggvos)
    {
      SettlementAggVO currentAggvo = settlementAggVO;
      SettlementHeadVO head = (SettlementHeadVO)currentAggvo.getParentVO();
      if (SettleEnumCollection.Direction.REC.VALUE.equals(head.getDirection())) {
        return false;
      }
      if ((head.getBusistatus() == null) || (!head.getBusistatus().equals(Integer.valueOf(BusiStatus.Sign.getBillStatusKind())))) {
        return false;
      }
      if ("DS".equals(head.getPk_tradetype())) {
        return false;
      }
      if (head.getPk_ftsbill() != null) {
        return false;
      }
      if (SettleUtils.isExistInnerAccount(currentAggvo)) {
        return false;
      }
      for (SettlementBodyVO body : (SettlementBodyVO[])settlementAggVO.getChildrenVO()) {
        if ((body.getSettlestatus() != null) && (body.getSettlestatus().equals(Integer.valueOf(SettleStatus.SETTLERESET.getStatus())))) {
          return false;
        }
      }
    }
    return super.isActionEnable();
  }
  
  public Integer doZhifu(Container parent, SettlementAggVO[] aggs)
		    throws BusinessException
		  {
		    setContainer(parent);
		    setAggVOs(aggs);
		    
		    NetpayTransferVO transferVO = this.paymentService.doCombinPayDelOBMLog(aggs, this.operaterID);

		    PaymentRetMsg[] rets = getEbankUI().doObmBusinessBulu(parent, transferVO.getOnlinePaymentVOs(), 3, "CMP");
		    
		    int len = rets == null ? 0 : rets.length;
		    if ((len == 0) || (rets[0].getTranflag() == null) || (!rets[0].getTranflag().equals(Integer.valueOf(0)))) {
		      return Integer.valueOf(-1);
		    }
		    for (PaymentRetMsg paymentRetMsg : rets)
		    {
		      if (paymentRetMsg.getRetFlag() == 2) {
		        throw new BusinessException(paymentRetMsg.getMsg());
		      }
		      if (paymentRetMsg.getRetFlag() == 1) {
		        return null;
		      }
		    }
		    setCAInfoToPaymentVO(transferVO.getOnlinePaymentVOs());
		    this.paymentService.savePaymentAndDealCombim(transferVO, this.operaterID, this.busidate);
		    return Integer.valueOf(0);
		  }
  
  public SettlementAggVO[] getAggVOs()
  {
    return this.aggVOs;
  }
  
  private final String operaterID = WorkbenchEnvironment.getInstance().getLoginUser().getPrimaryKey();
  private final UFDate busidate = WorkbenchEnvironment.getInstance().getBusiDate();

  
  public void setAggVOs(SettlementAggVO[] aggVOs)
  {
    this.aggVOs = aggVOs;
  }
  private void setCAInfoToPaymentVO(OnlinePaymentVO[] onlinepaymentvos)
  {
    ObmCASignature obmca = new ObmCASignature();
    
    obmca.signPayInfo(onlinepaymentvos, new ObmCAInfoAccessor(), DataUtil.getCurrentUser());
  }
  
  protected IObmBuluUI getEbankUI()
  {
    if (this.ebank == null) {
      try
      {
        Class cl = Class.forName("nc.ui.ebank.out.EbankEntrance");
        this.ebank = ((IObmBuluUI)cl.newInstance());
      }
      catch (Exception ex)
      {
        throw new RuntimeException(ex);
      }
    }
    return this.ebank;
  }
}
