package nc.bs.arap.busireg;

import nc.bs.businessevent.BdUpdateEvent;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.bs.trade.business.HYPubBO;
import nc.vo.arap.basebill.BaseAggVO;
import nc.vo.arap.basebill.BaseBillVO;
import nc.vo.arap.utils.ArrayUtil;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
/**
 * 二开新建的类，物业付款单保存校验金额不能大于上游应付单的实付金额
 * @author 符耀铭
 * @time 2019-4-25
 */
public class WYPaybillsavecheckmnyListener implements IBusinessListener {

	@Override
	public void doAction(IBusinessEvent event) throws BusinessException {
		BaseAggVO[] bills = this.getBills(event);
		BaseBillVO headvo = (BaseBillVO)bills[0].getParentVO();
		String top_tradetype=bills[0].getItems()[0].getTop_tradetype();
		String top_billid=bills[0].getItems()[0].getTop_billid();
		if("F1-Cxx-W02".equals(top_tradetype)){
			
			HYPubBO hyPubBO=new HYPubBO();
			//def109是否含质保金付款def14
			Object def14 =hyPubBO.findColValue("ap_payablebill", "def14", "pk_payablebill ='"+top_billid+"'");
			
			UFBoolean ishaszhibaojin =def14==null?UFBoolean.FALSE:new UFBoolean(def14.toString());
			
			if(ishaszhibaojin.booleanValue()){
				UFDouble paymny =new UFDouble(headvo.getAttributeValue("money").toString());
				//def108 实付金额 def13
				Object payablemny =hyPubBO.findColValue("ap_payablebill", "def13", "pk_payablebill ='"+top_billid+"'");
				UFDouble payableDouble=payablemny==null?UFDouble.ZERO_DBL:new UFDouble(payablemny.toString());
				if(paymny.doubleValue()>payableDouble.doubleValue()){
					ExceptionUtils.wrappBusinessException("付款金额不得超过上游单据实付金额，请检查!");
				}
			}
		}

	}
	
	private BaseAggVO[] getBills(IBusinessEvent event) {
		Object value = null;
		if(event instanceof BusinessEvent) {
			value = ((BusinessEvent)event).getObject();
		} else if(event instanceof BdUpdateEvent) {
			value = ((BdUpdateEvent)event).getNewObject();
		}

		BaseAggVO[] bills = null;
		if(null != value) {

			if(value.getClass().isArray()) {
				Object[] objs = (Object[])((Object[])value);
				bills = objs instanceof BaseAggVO[]?(BaseAggVO[])((BaseAggVO[])objs):(BaseAggVO[])ArrayUtil.convertSupers2Subs((AggregatedValueObject[])((AggregatedValueObject[])objs), BaseAggVO.class);

			} else {
				bills = new BaseAggVO[]{(BaseAggVO)value};
			}
		}

		return bills;
	}

}
