package nc.bs.arap.busireg;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import nc.bs.businessevent.BdUpdateEvent;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.bs.businessevent.IEventType;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.impl.pubapp.pattern.data.bill.BillQuery;
import nc.itf.uap.pf.IPFBusiAction;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.arap.payable.AggPayableBillVO;
import nc.vo.arap.payable.PayableBillItemVO;
import nc.vo.arap.payable.PayableBillVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nccloud.commons.lang.ArrayUtils;

/** 
 * @author 徐钢
 * @date 2018-10-27
 * @Description:patch_明源接口应付计提联动删除审批_20181109
 *
 */
public class F1CxxMyCloseBeforListener implements IBusinessListener {
	public void doAction(IBusinessEvent event) throws BusinessException {
		if (IEventType.TYPE_DELETE_AFTER.equals(event.getEventType()) || IEventType.TYPE_UNAPPROV_AFTER.equals(event.getEventType())|| IEventType.TYPE_APPROV_AFTER.equals(event.getEventType())) {
			if("NC".equals(InvocationInfoProxy.getInstance().getUserCode())){
				return;
			}
			AggregatedValueObject[] obills = getBills(event);
			if (ArrayUtils.isEmpty(obills)) {
				return;
			}
			for (AggregatedValueObject aggregatedValueObject : obills) {
				if(!(aggregatedValueObject instanceof AggPayableBillVO)){
					continue;
				}
				AggPayableBillVO aggvo = (AggPayableBillVO) aggregatedValueObject;
				PayableBillVO hvo = (PayableBillVO) aggvo.getParentVO();
				PayableBillItemVO[] bvos = (PayableBillItemVO[]) aggvo.getChildrenVO();
				if("F1-Cxx-W01".equals(hvo.getPk_tradetype())){
					//w01删除弃审
					if(IEventType.TYPE_DELETE_AFTER.equals(event.getEventType()) || IEventType.TYPE_UNAPPROV_AFTER.equals(event.getEventType())){
						
						String sql = "";
						if(hvo.getDef2() != null){
							sql = "select ap.billno from ap_payablebill ap where ap.pk_tradetype = 'F1-Cxx-W01' and ap.def1 = 'GXXXXXXX' and nvl(ap.dr,0) = 0 and 1=2";
						}else{
							sql = "select ap.billno from ap_payablebill ap where ap.pk_tradetype = 'F1-Cxx-W01' and ap.def2 = '"+hvo.getDef1()+"' and nvl(ap.dr,0) = 0";
						}
						
						Map apbillno = (Map) new BaseDAO().executeQuery(sql, new MapProcessor());
						
						if(apbillno != null && apbillno.size() > 0){
							String msessge = "系统存在下游的物业应付计提单，需要删除该单据("+apbillno.get("billno")+")后，才能对此应付单进行取消审批/删除操作，谢谢";
							throw new BusinessException(msessge);
						}
						if(hvo.getMoney()!= null && hvo.getMoney().toDouble() < 0){
							sql = "select l.billno from ap_payablebill l where l.pk_tradetype = 'F1-Cxx-W02' and l.def1 = '"+bvos[0].getDef23()+"' and nvl(l.dr,0) = 0";
							if(IEventType.TYPE_UNAPPROV_AFTER.equals(event.getEventType())){
								sql = sql + " and l.approvestatus <> -1";
							}
							Object billno = new BaseDAO().executeQuery(sql, new ColumnProcessor());
							if(billno == null || billno.toString().length() == 0){
								continue;
							}
							String messg = "物业应付计提单（红字）不允许取消审批/删除，请找到对应的应付单（"+billno+"）取消审批/删除，系统自动对此单据进行取消审批/删除操作，谢谢!";
							throw new BusinessException(messg);
						}
					}
				}
				
				if("F1-Cxx-W02".equals(hvo.getPk_tradetype())){// 物业应付单 删除弃审审批，上游游物业计提单  同批次 统一操作，效验上游计提单是红字，而且有对应后到蓝字，提示报错
					StringBuffer sqlstr=new StringBuffer("");
					sqlstr.append("select l1.pk_payablebill,l1.def2,l1.def1").append("\r\n");
					sqlstr.append("  from ap_payablebill l1").append("\r\n");
					sqlstr.append("  left join ap_payableitem l2 on l1.pk_payablebill = l2.pk_payablebill").append("\r\n");
					sqlstr.append("  where  l1.pk_tradetype = 'F1-Cxx-W01' and nvl(l2.def23,'~') <> '~'").append("\r\n");
					sqlstr.append("  and nvl(l2.dr,0) = 0 and nvl(l1.dr,0) = 0 and l2.def23 = '"+hvo.getDef1()+"' and l1.money < 0"); 
					
					List<Map> billno = (List<Map>) new BaseDAO().executeQuery(sqlstr.toString(), new MapListProcessor());
					//w02删除 弃审
					if(IEventType.TYPE_DELETE_AFTER.equals(event.getEventType()) || IEventType.TYPE_UNAPPROV_AFTER.equals(event.getEventType())){
						if(billno != null && billno.size() > 0){
							List<String> lis2 = new ArrayList<String>();
							for (Map map : billno) {
								lis2.add(map.get("pk_payablebill").toString());
							}
							
							BillQuery query = new BillQuery(AggPayableBillVO.class);
							AggPayableBillVO[] aggpayvo = (AggPayableBillVO[])query.query(lis2.toArray(new String[0]));
							IPFBusiAction baService = NCLocator.getInstance().lookup(IPFBusiAction.class);
							if(aggpayvo != null && aggpayvo.length > 0){
								for (AggPayableBillVO aggPayableBillVO : aggpayvo) {
									if(IEventType.TYPE_DELETE_AFTER.equals(event.getEventType())){
										Object result3 = baService.processAction("DELETE", "F1-Cxx-W01",null , aggPayableBillVO, null, null);
									}else{
										Object result3 = baService.processAction("UNAPPROVE", "F1-Cxx-W01", null, aggPayableBillVO, null, null);
									}
								}
							}
						}
						
					}
					//w02审批后
					if(IEventType.TYPE_APPROV_AFTER.equals(event.getEventType())){
						if(billno != null && billno.size() > 0){
							List<String> lis = new ArrayList<String>();
							for (Map map : billno) {
								lis.add(map.get("pk_payablebill").toString());
							}
							BillQuery query = new BillQuery(AggPayableBillVO.class);
							AggPayableBillVO[] aggpayvo = (AggPayableBillVO[])query.query(lis.toArray(new String[0]));
							IPFBusiAction baService = NCLocator.getInstance().lookup(IPFBusiAction.class);
							if(aggpayvo != null && aggpayvo.length > 0){
								for (AggPayableBillVO aggPayableBillVO : aggpayvo) {
									Object result3 = baService.processAction("SAVE", "F1-Cxx-W01",null , aggPayableBillVO, null, null);
								}
							}
						}
					}
				}
			}
		}
	}

	protected AggregatedValueObject[] getBills(IBusinessEvent event) {
		Object object = null;
		if ((event instanceof BusinessEvent)) {
			BusinessEvent e = (BusinessEvent) event;
			object = e.getObject();
		} else if ((event instanceof BdUpdateEvent)) {
			BdUpdateEvent e = (BdUpdateEvent) event;
			object = e.getNewObject();
		}

		AggregatedValueObject[] bills = null;
		if (null != object) {
			if (object.getClass().isArray()) {
				bills = (AggregatedValueObject[]) object;
			} else {
				bills = new AggregatedValueObject[1];
				bills[0] = ((AggregatedValueObject) object);
			}
		}
		return bills;
	}
}
