//nslGwwQRyySTBqdb6vgDeTX2flneCaaVP7NIdF4lqqHYeWcjsCkAJ3zO1zqNoOHrDD/sz60Weax087NE4mI8NA==
package nc.bs.arap.busireg;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import nc.bd.accperiod.InvalidAccperiodExcetion;
import nc.bs.arap.bill.ArapBillCalUtil;
import nc.bs.arap.billact.LogTime;
import nc.bs.arap.cache.ArapBusiPluginCenter;
import nc.bs.arap.verify.FaDMO;
import nc.bs.businessevent.BdUpdateEvent;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IEventType;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.bs.logging.Logger;
import nc.bs.uap.lock.PKLock;
import nc.itf.arap.fieldmap.IBillFieldGet;
import nc.itf.arap.prv.IArapVerifyLogPrivate;
import nc.itf.fi.pub.Currency;
import nc.itf.fi.pub.SysInit;
import nc.itf.uap.busibean.SysinitAccessor;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.md.data.access.NCObject;
import nc.md.model.MetaDataException;
import nc.md.persist.framework.MDPersistenceService;
import nc.pubitf.accperiod.AccountCalendar;
import nc.pubitf.arap.bill.IArapBillPubQueryService;
import nc.pubitf.arap.receivable.IArapReceivableBillPubQueryService;
import nc.pubitf.bd.accessor.GeneralAccessorFactory;
import nc.pubitf.bd.accessor.IGeneralAccessor;
import nc.pubitf.pu.m21.arap.mf1.IOrderQueryForVerify;
import nc.pubitf.pu.m25.ap.f1.IInvoiceQueryForVerify;
import nc.pubitf.so.m30.sobalance.ISoBalance4VerifyQryBill;
import nc.pubitf.uapbd.CurrencyRateUtilHelper;
import nc.vo.arap.agiotage.AgiotageChildVO;
import nc.vo.arap.agiotage.ArapBusiDataVO;
import nc.vo.arap.agiotage.ArapBusiDataVOList;
import nc.vo.arap.basebill.BaseAggVO;
import nc.vo.arap.basebill.BaseBillVO;
import nc.vo.arap.basebill.BaseItemVO;
import nc.vo.arap.basebill.IArapItemFieldVO;
import nc.vo.arap.bill.util.ArapVOTransformUtil;
import nc.vo.arap.debttransfer.DebtTransferVO;
import nc.vo.arap.event.IArapBSEventType;
import nc.vo.arap.gathering.GatheringBillItemVO;
import nc.vo.arap.global.ArapBillDealVOConsts;
import nc.vo.arap.pay.PayBillItemVO;
import nc.vo.arap.payable.PayableBillItemVO;
import nc.vo.arap.pfflow.ArapBillMapVO;
import nc.vo.arap.pfflow.ArapBillMapVOTool;
import nc.vo.arap.pub.ArapBillTypeInfo;
import nc.vo.arap.pub.ArapConstant;
import nc.vo.arap.pub.BillEnumCollection;
import nc.vo.arap.pub.BillEnumCollection.FromSystem;
import nc.vo.arap.receivable.ReceivableBillItemVO;
import nc.vo.arap.sysinit.SysinitConst;
import nc.vo.arap.utils.ARAPModuleEnableUtil;
import nc.vo.arap.utils.ArrayUtil;
import nc.vo.arap.utils.StringUtil;
import nc.vo.arap.verify.AggverifyVO;
import nc.vo.arap.verify.RBVerify;
import nc.vo.arap.verify.SameMnyVerify;
import nc.vo.arap.verify.UnsameMnyVerify;
import nc.vo.arap.verify.VerifyDetailVO;
import nc.vo.arap.verify.VerifyTool;
import nc.vo.arap.verify.VerifyfaVO;
import nc.vo.arap.verifynew.ProxyVerify;
import nc.vo.arap.verifynew.QueryAndRuleFaVO;
import nc.vo.bd.accessor.IBDData;
import nc.vo.fi.pub.SqlUtils;
import nc.vo.fipub.exception.ExceptionHandler;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.MapList;
import nc.vo.pubapp.pattern.pub.PubAppTool;
import nc.vo.tmpub.util.SqlUtil;
import nc.vo.verifynew.pub.ConditionVO;
import nc.vo.verifynew.pub.DefaultVerifyRuleVO;
import nc.vo.verifynew.pub.VerifyCom;
import nccloud.bs.arap.sagas.util.SagasUtils;
import nccloud.bs.arap.util.Collections;
import nccloud.commons.lang.ArrayUtils;
import nccloud.commons.lang.StringUtils;
import nccloud.vo.arap.bdloss.BdLossChildVO;
import nccloud.vo.arap.bdrecovery.BdRecoverySKVO;

@SuppressWarnings("unchecked")
public class BillRegisterForBusiDataBO {

	private static String SPECIAL_KEY = "def1"; // 应收应付内部拉单核销，按照此字段记录上下游单据的主键，用于批量处理核销;

	Map<String, ArrayList<AggverifyVO>> aggMap = new HashMap<String, ArrayList<AggverifyVO>>();

	AggregatedValueObject[] aggvos = null;

	public AggregatedValueObject[] getAggvos() {
		return this.aggvos;
	}

	public void setAggvos(AggregatedValueObject[] aggvos) {
		this.aggvos = aggvos;
	}

	String pkorg = "";

	private String pk_user;

	private Integer syscode;

	public Integer getSyscode() {
		return this.syscode;
	}

	public void setSyscode(Integer syscode) {
		this.syscode = syscode;
	}

	public String getPkorg() {
		return this.pkorg;
	}

	public void setPkorg(String pkorg) {
		this.pkorg = pkorg;
	}

	public String getPk_user() {
		return this.pk_user;
	}

	public void setPk_user(String pkUser) {
		this.pk_user = pkUser;
	}

	/**
	 * 统一调用批量接口
	 * 
	 * @param obj
	 * @return
	 */
	protected AggregatedValueObject[] dealUserObj(Object obj) {
		if (obj instanceof BusinessEvent.BusinessUserObj) {
			obj = ((BusinessEvent.BusinessUserObj) obj).getUserObj();
		}
		AggregatedValueObject[] retvos = null;
		if (obj.getClass().isArray()) {
			retvos = (AggregatedValueObject[]) obj;
		} else {
			retvos = new AggregatedValueObject[] { (AggregatedValueObject) obj };
		}
		this.pk_user = (String) retvos[0].getParentVO().getAttributeValue(ArapBusiDataVO.APPROVER);
		this.syscode = (Integer) retvos[0].getParentVO().getAttributeValue(ArapBusiDataVO.SYSCODE);
		this.pkorg = (String) retvos[0].getParentVO().getAttributeValue(ArapBusiDataVO.PK_ORG);
		return retvos;
	}

	/**
	 * 业务单据登账接口
	 */
	public void doAction(IBusinessEvent event) throws BusinessException {
		this.doBusiAction(event);
	}

	/**
	 * 扩展核销规则处理
	 * 
	 * @param vos
	 * @param ruleVOMap
	 * @param com
	 * @throws BusinessException
	 * @throws MetaDataException
	 */
	private void billRBVerifyBySrcBillForExtend(AggregatedValueObject[] vos,
			Hashtable<String, DefaultVerifyRuleVO> ruleVOMap, VerifyCom verifyCom)
			throws BusinessException, MetaDataException {
		// 查询扩展核销规则，进行处理
		List<Object> rules = ArapBusiPluginCenter.getAllVerifyrulePlugins(getSyscode());

		ArrayList<AggverifyVO> aggVOList = new ArrayList<AggverifyVO>();
		BillVerifyRuleInvoker ruleInvoker = null;
		for (AggregatedValueObject vo : vos) {
			for (Object vrule : rules) {
				ruleInvoker = new BillVerifyRuleInvoker(vrule);
				if (ruleInvoker.isMatch((BaseAggVO) vo)) {
					// 收付款合同支持自动核销后在手工核销节点反核销，其他插件不支持,每个规则都要使用独立的verifycom
					VerifyCom com = new VerifyCom();
					com.setIsauto(UFBoolean.TRUE);
					if (vrule instanceof BillVerifyRule
							&& "nc.impl.fct.pub.verify.FctBillVerifyRule".equals(vrule.getClass().getName())) {
						// 收付款合同注册的核销规则扩展插件
						com.setIsauto(UFBoolean.FALSE);
						com.setIsreserve(VerifyDetailVO.reserve_fct);
					}

					String[] matchFields = ruleInvoker.getMatchFields();
					for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
						rule.setM_creditObjKeys(matchFields);
						rule.setM_debtObjKeys(matchFields);
					}

					String queryOpBillSql = ruleInvoker.getQueryOpBillSql((BaseAggVO) vo);
					NCObject[] objectByCond = null;
					if (PubAppTool.isNull(queryOpBillSql)) {
						objectByCond = MDPersistenceService.lookupPersistenceQueryService()
								.queryBillOfNCObjectByCond(ArapBusiDataVO.class, " 1=2 ", false);
					} else {
						objectByCond = MDPersistenceService.lookupPersistenceQueryService().queryBillOfNCObjectByCond(
								ArapBusiDataVO.class, queryOpBillSql + " and billclass in ('yf','ys','fk','sk') ",
								false);
					}

					List<ArapBusiDataVO> jfList = new ArrayList<ArapBusiDataVO>();
					List<ArapBusiDataVO> dfList = new ArrayList<ArapBusiDataVO>();
					// 区分本方 对方
					if (objectByCond != null) {
						for (NCObject data : objectByCond) {
							ArapBusiDataVO busiDataVO = (ArapBusiDataVO) data.getContainmentObject();
							busiDataVO.setAttributeValue(ArapBusiDataVO.SETT_MONEY, busiDataVO.getOccupationmny());

							if (busiDataVO.getDirection().intValue() == 1) {
								jfList.add(busiDataVO);
							} else {
								dfList.add(busiDataVO);
							}
						}
					}
					this.aggMap.clear();
					this.aggMap = this.onVerify(com, ruleVOMap, jfList.toArray(new ArapBusiDataVO[0]),
							dfList.toArray(new ArapBusiDataVO[0]));
					aggVOList.addAll(this.getAggVerifyVO(this.aggMap, UFBoolean.FALSE));
					if (aggVOList != null && aggVOList.size() > 0) {
						NCLocator.getInstance().lookup(IArapVerifyLogPrivate.class).save(aggVOList, ruleVOMap, com);
						// 重新查询单据表体的信息
						this.reQueryBillIteminfo(vo);

						aggVOList.clear();
					}
					this.aggMap.clear();

					// 重置rule，以便后续使用
					for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
						rule.setM_creditObjKeys(null);
						rule.setM_debtObjKeys(null);
					}
				}
			}
		}
	}

	private void reQueryBillIteminfo(AggregatedValueObject vo) throws BusinessException {
		CircularlyAccessibleValueObject[] childrenVO = vo.getChildrenVO();
		List<String> pks = new ArrayList<String>();
		for (CircularlyAccessibleValueObject s : childrenVO) {
			pks.add(s.getPrimaryKey());
		}

		if (vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE).equals(IBillFieldGet.F0)) {
			IArapReceivableBillPubQueryService service = NCLocator.getInstance()
					.lookup(IArapReceivableBillPubQueryService.class);
			try {
				ReceivableBillItemVO[] items = service.queryRecieableBillItem(pks.toArray(new String[pks.size()]));
				vo.setChildrenVO(items);
			} catch (BusinessException e) {
				ExceptionHandler.handleException(e);
			}
		} else if (vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE).equals(IBillFieldGet.F1)) {
			try {
				Collection<PayableBillItemVO> bills = MDPersistenceService.lookupPersistenceQueryService()
						.queryBillOfVOByPKs(PayableBillItemVO.class, pks.toArray(new String[pks.size()]), false);
				PayableBillItemVO[] items = bills.toArray(new PayableBillItemVO[] {});
				vo.setChildrenVO(items);
			} catch (BusinessException e) {
				ExceptionHandler.handleException(e);
			}
		}
	}

	private void doBusiAction(IBusinessEvent event) throws BusinessException, MetaDataException, DAOException {
		// 生效后
		long t1 = System.currentTimeMillis();
		if (IArapBSEventType.TYPE_EFFECTION_AFTER.equals(event.getEventType())) {
			BusinessEvent e = (BusinessEvent) event;
			if (null != e.getUserObject()) {
				AggregatedValueObject[] vos = this.dealUserObj(e.getUserObject());
				this.setAggvos(vos);
				for (AggregatedValueObject obj : vos) {
					CircularlyAccessibleValueObject parentVO = obj.getParentVO();
					UFBoolean isinit = (UFBoolean) parentVO.getAttributeValue("isinit");
					if (isinit != null && isinit.booleanValue()) {
						// 如果是期初单据，不用审核监听，直接返回
						return;
					}
				}

				List<ArapBusiDataVO> busiDataVOList = new ArapVOTransformUtil().transform(vos);
				doInsertRegister(busiDataVOList);

				if (busiDataVOList != null && busiDataVOList.size() > 0 && !SagasUtils.isCompensateStage()) {
					// 加入saga冻结busidata 补偿阶段不冻结
					SagasUtils.frozenAndAddSaga(SagasUtils.OTHER,
							busiDataVOList.toArray(new ArapBusiDataVO[busiDataVOList.size()]), IBillFieldGet.BILLNO,
							busiDataVOList.get(0).getPk_billtype());
				}

				for (AggregatedValueObject obj : vos) {
					String billclass = (String) obj.getParentVO().getAttributeValue("billclass");
					if (billclass != null && (billclass.equals(ArapConstant.ARAP_ZS_BILLCLASS)
							|| billclass.equals(ArapConstant.ARAP_ZF_BILLCLASS))) {
						return;
					}
				}

				// 拉式生成单自动核销
				List<String> pks = new ArrayList<String>();
				List<ArapBillMapVO> scmList = new ArrayList<ArapBillMapVO>();
				List<ArapBillMapVO> defF2List = new ArrayList<ArapBillMapVO>();
				List<ArapBillMapVO> psList = new ArrayList<ArapBillMapVO>();
				List<ArapBillMapVO> pcmListNoMatch = new ArrayList<ArapBillMapVO>();
				MapList<String, ArapBillMapVO> pcmListBatchNoMatch = new MapList<String, ArapBillMapVO>();
				List<ArapBillMapVO> pcmListMatch = new ArrayList<ArapBillMapVO>();
				Hashtable<String, DefaultVerifyRuleVO> ruleVOMap = this.creatVerifyRuleVO();
				VerifyCom com = new VerifyCom();

				// begin
				// 做了预核销的数据核销 add by zhaoyanf
				vos = billPreVerify(vos, ruleVOMap, com);
				// end

				// 收付核销规则业务插件注册核销
				this.billRBVerifyBySrcBillForExtend(vos, ruleVOMap, null);

				// 自动核销方案条件
				String pk_billtype = "";
				Map<String, VerifyfaVO> tradetypes = new HashMap<String, VerifyfaVO>();
				MapList<VerifyfaVO, String> tradeTypeBills = new MapList<VerifyfaVO, String>();
				for (AggregatedValueObject vo : vos) {
					VerifyfaVO faVO = null;
					// 单据来源系统
					Integer src_syscode = (Integer) vo.getParentVO().getAttributeValue(IBillFieldGet.SRC_SYSCODE);
					BaseItemVO[] childrenVO = (BaseItemVO[]) vo.getChildrenVO();

					pk_billtype = (String) vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE);
					if (IBillFieldGet.F0.equals(pk_billtype) || IBillFieldGet.F2.equals(pk_billtype)) {
						faVO = new VerifyfaVO();
						faVO.setNode_code("20060VPS");
					} else if (IBillFieldGet.F1.equals(pk_billtype) || IBillFieldGet.F3.equals(pk_billtype)) {
						faVO = new VerifyfaVO();
						faVO.setNode_code("20080VPS");
					}
					if (faVO != null) {
						String pk_org = (String) vo.getParentVO().getAttributeValue(IBillFieldGet.PK_ORG);
						String pk_tradetype = (String) vo.getParentVO().getAttributeValue(IBillFieldGet.PK_TRADETYPEID);
						String key = pk_org + pk_tradetype;
						faVO.setPk_org(pk_org);
						faVO.setBf_transtype(pk_tradetype);
						if (!tradetypes.containsKey(key)) {
							tradetypes.put(key, faVO);
							tradeTypeBills.put(faVO, vo.getParentVO().getPrimaryKey());
						} else {
							tradeTypeBills.put(tradetypes.get(key), vo.getParentVO().getPrimaryKey());
						}
					}

					if (ArapBillDealVOConsts.BILLTYPE_21.equals(childrenVO[0].getTop_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_36D1.equals(childrenVO[0].getTop_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_36D7.equals(childrenVO[0].getTop_billtype())) {
						for (BaseItemVO itemVO : childrenVO) {
							if ((ArapBillDealVOConsts.BILLTYPE_36D1.equals(childrenVO[0].getTop_billtype())
									|| ArapBillDealVOConsts.BILLTYPE_36D7.equals(childrenVO[0].getTop_billtype()))
									&& ArapBillDealVOConsts.BILLTYPE_21.equals(childrenVO[0].getSrc_billtype())) {
								// 采购订单-付款申请-付款单，情况直接按照供应链的自动核销控制逻辑走
								ArapBillMapVO mapVO = ArapBillMapVOTool
										.changeVotoBillMapNew((BaseBillVO) vo.getParentVO(), itemVO);
								mapVO.setS_itemid(itemVO.getPurchaseorder());// 付款单
								// 如果不将单据类型改为21，在classname_pu 和 classname_ps 匹配的时候会匹配到 classname_ps，
								// 从而取 com.setReserveFlag(VerifyDetailVO.reserve_pc)，导致预占用金额不回写。
								mapVO.setS_billid(itemVO.getSrc_billid());
								mapVO.setS_billtype(ArapBillDealVOConsts.BILLTYPE_21);
								scmList.add(mapVO);

							} else if (itemVO.getTop_termch() == null) {
								ArapBillMapVO mapVO = ArapBillMapVOTool
										.changeVotoBillMapNew((BaseBillVO) vo.getParentVO(), itemVO);
								mapVO.setS_itemid(itemVO.getPurchaseorder());// 付款单
								scmList.add(mapVO);
							} else {
								// 应付单-付款申请-付款单,自动核销，不支持手工核销节点反核销
								ArapBillMapVO mapVO = new ArapBillMapVO();
								mapVO.setT_itemid(itemVO.getPrimaryKey());
								mapVO.setS_termid(itemVO.getTop_termch());
								mapVO.setS_itemid(itemVO.getPrimaryKey());
								mapVO.setS_system(src_syscode);
								mapVO.setS_billtype(itemVO.getTop_billtype());
								mapVO.setYbje(itemVO.getMoney_bal());
								psList.add(mapVO);
							}
						}
					} else if (ArapBillDealVOConsts.BILLTYPE_25.equals(childrenVO[0].getTop_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_45.equals(childrenVO[0].getTop_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_Z2.equals(childrenVO[0].getTop_billtype())) {
						for (BaseItemVO itemVO : childrenVO) {
							ArapBillMapVO mapVO = ArapBillMapVOTool.changeVotoBillMapNew((BaseBillVO) vo.getParentVO(),
									itemVO);
							scmList.add(mapVO);
						}
					} else if (ArapBillDealVOConsts.BILLTYPE_30.equals(childrenVO[0].getSrc_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_Z3.equals(childrenVO[0].getTop_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_32.equals(childrenVO[0].getTop_billtype())) {
						for (BaseItemVO itemVO : childrenVO) {
							ArapBillMapVO mapVO = ArapBillMapVOTool
									.changeVotoBillMapNewForSo((BaseBillVO) vo.getParentVO(), itemVO);
							scmList.add(mapVO);
						}
					} else if (ArapBillDealVOConsts.BILLTYPE_4D48.equals(childrenVO[0].getTop_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_4D50.equals(childrenVO[0].getTop_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_4D46.equals(childrenVO[0].getTop_billtype())
							|| "4D52".equals(childrenVO[0].getTop_billtype())
							|| "4D39".equals(childrenVO[0].getTop_billtype())
							|| "4D83".equals(childrenVO[0].getTop_billtype())
							|| "4D53".equals(childrenVO[0].getTop_billtype())
							|| "4D33".equals(childrenVO[0].getTop_billtype())) {
						Set<String> set_4D46 = new HashSet<String>();
						Set<String> set_other = new HashSet<String>();
						for (BaseItemVO itemVO : childrenVO) {
							String srcBillid = itemVO.getSrc_billid();
							if (StringUtils.isNotEmpty(srcBillid)) {
								if (ArapBillDealVOConsts.BILLTYPE_4D46.equals(childrenVO[0].getTop_billtype())) {
									set_4D46.add(srcBillid);
								} else {
									set_other.add(srcBillid);
								}
							}
						}
						if (set_4D46.size() > 0) {
							Collection<PayableBillItemVO> itemVOList = MDPersistenceService
									.lookupPersistenceQueryService().queryBillOfVOByCond(
											ArapBillTypeInfo.getInstance(IBillFieldGet.F1).getItemvoClass(),
											SqlUtils.getInStr(IArapItemFieldVO.SRC_BILLID,
													set_4D46.toArray(new String[set_4D46.size()]), true)
													+ " and dr = 0",
											false);
							if (itemVOList != null && !itemVOList.isEmpty()) {
								Map<String, List<PayableBillItemVO>> srcMap = new HashMap<String, List<PayableBillItemVO>>();
								for (PayableBillItemVO itemCollection : itemVOList) {
									String src_billid = itemCollection.getSrc_billid();
									if (!srcMap.containsKey(src_billid)) {
										srcMap.put(src_billid, new ArrayList<PayableBillItemVO>());
									}
									srcMap.get(src_billid).add(itemCollection);
								}
								for (BaseItemVO itemVO : childrenVO) {
									String srcBillid = itemVO.getSrc_billid();
									if (StringUtils.isNotEmpty(srcBillid) && ArapBillDealVOConsts.BILLTYPE_4D46
											.equals(childrenVO[0].getTop_billtype())) {
										List<PayableBillItemVO> payableBillItemList = srcMap.get(srcBillid);
										if (payableBillItemList != null && payableBillItemList.size() > 0) {
											for (PayableBillItemVO item : payableBillItemList) {
												ArapBillMapVO mapVO = new ArapBillMapVO();
												mapVO.setT_itemid(itemVO.getPrimaryKey());
												mapVO.setS_itemid(item.getPrimaryKey());
												mapVO.setS_system(1);// 应付

												if (!StringUtil.isEmpty(itemVO.getSrc_itemid())
														&& !StringUtil.isEmpty(item.getSrc_itemid())
														&& itemVO.getSrc_itemid().equals(item.getSrc_itemid())) {
													pcmListMatch.add(mapVO);
												} else {
													pcmListBatchNoMatch.put(item.getParentPK(), mapVO);
												}
											}
										}
									}
								}
								srcMap.clear();
							}
						}

						if (set_other.size() > 0) {
							Collection<PayBillItemVO> itemVOList = MDPersistenceService.lookupPersistenceQueryService()
									.queryBillOfVOByCond(
											ArapBillTypeInfo.getInstance(IBillFieldGet.F3).getItemvoClass(),
											SqlUtils.getInStr(IArapItemFieldVO.SRC_BILLID,
													set_other.toArray(new String[set_other.size()]), true)
													+ " and dr = 0",
											false);
							if (itemVOList != null && !itemVOList.isEmpty()) {
								Map<String, List<PayBillItemVO>> srcMapOther = new HashMap<String, List<PayBillItemVO>>();
								for (PayBillItemVO itemVO : itemVOList) {
									String src_billid = itemVO.getSrc_billid();
									if (!srcMapOther.containsKey(src_billid)) {
										srcMapOther.put(src_billid, new ArrayList<PayBillItemVO>());
									}
									srcMapOther.get(src_billid).add(itemVO);
								}
								for (BaseItemVO itemVO : childrenVO) {
									String srcBillid = itemVO.getSrc_billid();
									if (StringUtils.isNotEmpty(srcBillid) && !ArapBillDealVOConsts.BILLTYPE_4D46
											.equals(childrenVO[0].getTop_billtype())) {
										List<PayBillItemVO> payBillItemList = srcMapOther.get(srcBillid);
										if (payBillItemList != null && payBillItemList.size() > 0) {
											for (PayBillItemVO item : payBillItemList) {
												ArapBillMapVO mapVO = new ArapBillMapVO();
												mapVO.setT_itemid(itemVO.getPrimaryKey());
												mapVO.setS_itemid(item.getPrimaryKey());
												mapVO.setS_system(1);// 应付

												if (!StringUtil.isEmpty(itemVO.getSrc_itemid())
														&& !StringUtil.isEmpty(item.getSrc_itemid())
														&& itemVO.getSrc_itemid().equals(item.getSrc_itemid())) {
													pcmListMatch.add(mapVO);
												} else {
													pcmListBatchNoMatch.put(item.getParentPK(), mapVO);
												}
											}
										}

									}
								}
								srcMapOther.clear();
							}
						}
						set_4D46.clear();
						set_other.clear();
					} else if ("4D62".equals(childrenVO[0].getTop_billtype()) && IBillFieldGet.F2.equals(pk_billtype)) {
						// 4D60 - 4D65 - F0
						// 4D60 - 4D62 - F2
						// 同合同的应收和收款核销
						Set<String> srcbillSet = new HashSet<String>(); // 收款单审批
						for (BaseItemVO itemVO : childrenVO) {
							srcbillSet.add(itemVO.getSrc_billid());

						}

						if (srcbillSet.size() > 0) {
							Collection<ReceivableBillItemVO> itemVOList = MDPersistenceService
									.lookupPersistenceQueryService().queryBillOfVOByCond(
											ArapBillTypeInfo.getInstance(IBillFieldGet.F0).getItemvoClass(),
											SqlUtils.getInStr(IArapItemFieldVO.SRC_BILLID,
													srcbillSet.toArray(new String[srcbillSet.size()]), true)
													+ " and dr = 0",
											false);

							if (itemVOList != null && itemVOList.size() > 0) {
								Map<String, List<ReceivableBillItemVO>> srcbill2map = new HashMap<String, List<ReceivableBillItemVO>>();
								for (ReceivableBillItemVO itemVO : itemVOList) {
									String src_billid = itemVO.getSrc_billid();
									if (!srcbill2map.containsKey(src_billid)) {
										srcbill2map.put(src_billid, new ArrayList<ReceivableBillItemVO>());
									}
									srcbill2map.get(src_billid).add(itemVO);
								}

								for (BaseItemVO itemVO : childrenVO) {
									if (StringUtil.isEmpty(itemVO.getSrc_billid())) {
										continue;
									}

									List<ReceivableBillItemVO> values = srcbill2map.get(itemVO.getSrc_billid());
									if (values != null && values.size() != 0) {
										for (ReceivableBillItemVO item : values) {
											ArapBillMapVO mapVO = new ArapBillMapVO();
											mapVO.setT_itemid(itemVO.getPrimaryKey());
											mapVO.setS_itemid(item.getPrimaryKey());
											pcmListNoMatch.add(mapVO);
										}
									}
								}
								srcbill2map.clear();
							}
						}
					} else if ("4D65".equals(childrenVO[0].getTop_billtype()) && IBillFieldGet.F0.equals(pk_billtype)) {
						Set<String> srcbillSet = new HashSet<String>();
						for (BaseItemVO itemVO : childrenVO) {
							if (!StringUtil.isEmpty(itemVO.getSrc_billid())) {
								srcbillSet.add(itemVO.getSrc_billid());
							}
						}
						if (srcbillSet.size() > 0) {
							Collection<GatheringBillItemVO> itemVOList = MDPersistenceService
									.lookupPersistenceQueryService().queryBillOfVOByCond(
											ArapBillTypeInfo.getInstance(IBillFieldGet.F2).getItemvoClass(),
											SqlUtils.getInStr(IArapItemFieldVO.SRC_BILLID,
													srcbillSet.toArray(new String[srcbillSet.size()]), true)
													+ " and dr = 0",
											false);

							if (itemVOList != null && itemVOList.size() > 0) {
								Map<String, List<GatheringBillItemVO>> srcbill2map = new HashMap<String, List<GatheringBillItemVO>>();
								for (GatheringBillItemVO itemVO : itemVOList) {
									String src_billid = itemVO.getSrc_billid();
									if (!srcbill2map.containsKey(src_billid)) {
										srcbill2map.put(src_billid, new ArrayList<GatheringBillItemVO>());
									}
									srcbill2map.get(src_billid).add(itemVO);
								}

								for (BaseItemVO itemVO : childrenVO) {
									if (StringUtil.isEmpty(itemVO.getSrc_billid())) {
										continue;
									}
									List<GatheringBillItemVO> values = srcbill2map.get(itemVO.getSrc_billid());
									if (values != null && values.size() != 0) {
										for (GatheringBillItemVO item : values) {
											ArapBillMapVO mapVO = new ArapBillMapVO();
											mapVO.setT_itemid(itemVO.getPrimaryKey());
											mapVO.setS_itemid(item.getPrimaryKey());
											pcmListNoMatch.add(mapVO);
										}
									}
								}
								srcbill2map.clear();
							}
						}
					}

					if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(childrenVO[0].getTop_billtype())
							|| ArapBillDealVOConsts.BILLTYPE_36D7.equals(childrenVO[0].getTop_billtype())) {
						for (BaseItemVO itemVO : childrenVO) {
							String srcBillid = itemVO.getSrc_billid();
							if (StringUtils.isNotEmpty(srcBillid)) {
								Collection<PayableBillItemVO> itemCollections = MDPersistenceService
										.lookupPersistenceQueryService().queryBillOfVOByCond(
												ArapBillTypeInfo.getInstance(IBillFieldGet.F1).getItemvoClass(),
												SqlUtils.getInStr(IArapItemFieldVO.SRC_BILLID,
														new String[] { srcBillid }, true) + " and pk_org='"
														+ itemVO.getPk_org() + "' and dr = 0",
												false);
								if (itemCollections != null) {
									for (PayableBillItemVO item : itemCollections) {
										ArapBillMapVO mapVO = new ArapBillMapVO();
										mapVO.setT_itemid(itemVO.getPrimaryKey());
										mapVO.setS_itemid(item.getPrimaryKey());
										mapVO.setS_system(1);// 应付

										if (itemVO.getSrc_itemid() != null) {
											if (!itemVO.getSrc_itemid().equals(item.getSrc_itemid())) {
												continue;
											}
											pcmListMatch.add(mapVO);
										} else {
											pcmListBatchNoMatch.put(item.getParentPK(), mapVO);
										}
									}
								}
							}
						}
					}
					UFBoolean isrefund = (UFBoolean) vo.getParentVO().getAttributeValue(IBillFieldGet.ISREFUND);
					// 应收应付内部的单据进行自动核销 + 来自于退款单据的核销
					if (src_syscode.intValue() == FromSystem.AR.VALUE.intValue()
							|| src_syscode.intValue() == FromSystem.AP.VALUE.intValue()
							|| (isrefund != null && isrefund.booleanValue())) {
						pks.add(vo.getParentVO().getPrimaryKey());
					}

					// 应收应付自制的或者是其他系统传递过来的收款单都可能建立订单核销关系
					if (vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE).equals(IBillFieldGet.F2)) {
						for (BaseItemVO itemVO : childrenVO) {
							ArapBillMapVO mapVO = ArapBillMapVOTool
									.changeVotoBillMapNewForSo((BaseBillVO) vo.getParentVO(), itemVO);
							defF2List.add(mapVO);
						}
					}
				}
				try {
					if (scmList != null && !scmList.isEmpty()) {
						// 供应链核销 ，查询返回核销关系数据
						if (scmList.get(0).getS_billtype() == null) {
							// 采购订单-》应付， 采购订单-》合同-》付款 ，自动核销
							this.VerifyByContractNo(scmList, com, ruleVOMap);
							return;
						}
						List<ArapBillMapVO> newList = new ArrayList<ArapBillMapVO>();
						newList.addAll(scmList);
						List<ArapBillMapVO> puList1 = new ArrayList<ArapBillMapVO>();
						for (ArapBillMapVO vo : scmList) {
							if (StringUtils.isEmpty(vo.getS_itemid())) {
							} else {
								puList1.add(vo);
							}
						}
						Map<ArapBillMapVO, Collection<ArapBillMapVO>> arapBillMap = null;
						if (scmList.get(0).getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_21)) {
							com.setReserveFlag(VerifyDetailVO.reserve_pu);
							com.setIsauto(UFBoolean.FALSE);
							if (Collections.isNotEmpty(puList1)) {
								arapBillMap = NCLocator.getInstance().lookup(IInvoiceQueryForVerify.class)
										.queryArapBillmap(scmList.toArray(new ArapBillMapVO[0]));
							}
						} else if (scmList.get(0).getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_36D7)
								|| scmList.get(0).getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_36D1)) {
							if (ARAPModuleEnableUtil.isPUEnable(InvocationInfoProxy.getInstance().getGroupId())) {
								com.setReserveFlag(VerifyDetailVO.reserve_pc);
								com.setIsauto(UFBoolean.FALSE);
								if (Collections.isNotEmpty(puList1)) {
									arapBillMap = NCLocator.getInstance().lookup(IInvoiceQueryForVerify.class)
											.queryArapBillmap(scmList.toArray(new ArapBillMapVO[0]));
								}
							}
						} else if (scmList.get(0).getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_25)
								|| scmList.get(0).getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_45)) {
							com.setReserveFlag(VerifyDetailVO.reserve_pu);
							com.setIsauto(UFBoolean.FALSE);
							if (Collections.isNotEmpty(puList1)) {
								arapBillMap = NCLocator.getInstance().lookup(IOrderQueryForVerify.class)
										.queryArapBillmap(scmList.toArray(new ArapBillMapVO[0]));
							}
						} else if (scmList.get(0).getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_30)
								|| scmList.get(0).getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_32)) {
							com.setReserveFlag(VerifyDetailVO.reserve_so);
							com.setIsauto(UFBoolean.TRUE);
							if (Collections.isNotEmpty(puList1)) {
								arapBillMap = NCLocator.getInstance().lookup(ISoBalance4VerifyQryBill.class)
										.queryArapBillmap(scmList.toArray(new ArapBillMapVO[0]));
							}
						}

						this.printMapForDebug(arapBillMap);

						Collection<Collection<ArapBillMapVO>> mapCollections = null;
						if (arapBillMap != null && arapBillMap.size() > 0) {
							arapBillMap = ArapBillMapVOTool.combineSameSourceBillMap(arapBillMap);

							// 组织返回的mapvo
							for (ArapBillMapVO vo : arapBillMap.keySet()) {
								Collection<ArapBillMapVO> collection = arapBillMap.get(vo);
								for (ArapBillMapVO vo1 : collection) {
									vo1.setT_billid(vo.getT_billid());
									vo1.setT_billtype(vo.getT_billtype());
									vo1.setT_itemid(vo.getT_itemid());
									vo1.setPk_currtype(vo.getPk_currtype());
								}
							}
							// 核销 --单据来自供应链的
							mapCollections = arapBillMap.values();
							for (Collection<ArapBillMapVO> collection : mapCollections) {
								this.doVerifyWithMap(collection, ruleVOMap, com, null);
							}
						}
						// 采购订单-》应付， 采购订单-》合同-》付款 ，自动核销
						this.VerifyByContractNo(newList, com, ruleVOMap);
					}
					/**
					 * add by 符耀铭 2019-5-14 物业付款单和物业应付单根据明源GUID核销 begin
					 */
					String djlxbm = (String) vos[0].getParentVO().getAttributeValue("pk_tradetype");
					if ("F3-Cxx-W01".equals(djlxbm) || "F1-Cxx-W02".equals(djlxbm)) {
						VerifyByGuid(vos, com, ruleVOMap);
					}
					if ("F1-Cxx-W01".equals(djlxbm) || "F1-Cxx-W02".equals(djlxbm)) {
						return;
					}
					/**
					 * add by 符耀铭 2019-5-14 物业付款单和物业应付单根据明源GUID核销 end
					 */

					// 自制收款单已经和销售订单建立预核销
					if (defF2List.size() > 0) {
						Map<ArapBillMapVO, Collection<ArapBillMapVO>> arapBillMap = null;

						if (ARAPModuleEnableUtil.isSOEnable(InvocationInfoProxy.getInstance().getGroupId())) {
							arapBillMap = NCLocator.getInstance().lookup(ISoBalance4VerifyQryBill.class)
									.queryArapBillmap(scmList.toArray(new ArapBillMapVO[0]));
							com.setReserveFlag(VerifyDetailVO.reserve_so);
						}

						Collection<Collection<ArapBillMapVO>> mapCollections = null;
						if (arapBillMap != null && arapBillMap.size() > 0) {
							arapBillMap = ArapBillMapVOTool.combineSameSourceBillMap(arapBillMap);

							// 组织返回的mapvo
							for (ArapBillMapVO vo : arapBillMap.keySet()) {
								Collection<ArapBillMapVO> collection = arapBillMap.get(vo);
								for (ArapBillMapVO vo1 : collection) {
									vo1.setT_billid(vo.getT_billid());
									vo1.setT_billtype(vo.getT_billtype());
									vo1.setT_itemid(vo.getT_itemid());
									vo1.setPk_currtype(vo.getPk_currtype());
								}
							}
							// 核销 --单据来自供应链的
							mapCollections = arapBillMap.values();
							com.setIsauto(UFBoolean.TRUE);
							for (Collection<ArapBillMapVO> collection : mapCollections) {
								this.doVerifyWithMap(collection, ruleVOMap, com, null);
							}
						}
					}

					if (pks != null && pks.size() > 0) {
						com.setReserveFlag(VerifyDetailVO.reserve_arap);
						com.setExactVerify(true);
						com.setIsauto(UFBoolean.TRUE);
						for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
							rule.setM_creditObjKeys(new String[] { BillRegisterForBusiDataBO.SPECIAL_KEY });
							rule.setM_debtObjKeys(new String[] { BillRegisterForBusiDataBO.SPECIAL_KEY });
						}
						// arap内部的单据审核时自动核销
						Collection<ArapBillMapVO> billMapData = new BaseDAO().retrieveByClause(ArapBillMapVO.class,
								SqlUtils.getInStr("t_billid", pks.toArray(new String[] {}), true)
										+ " and ISMANUAL<>'Y'");
						// arap内部单据自动核销，付款退款单生效生成的退款收款单和来源应收单自动核销
						UFBoolean isrefund = (UFBoolean) vos[0].getParentVO().getAttributeValue(IBillFieldGet.ISREFUND);
						if (isrefund != null && isrefund.booleanValue()) {
							com.setRefund(true);
						}
						this.doArapVerifyWithMap(billMapData, ruleVOMap, com);
						this.updateBillMapYbye(billMapData, true, null);
					}

					// 来自资金的付款排程单据
					if (psList != null && !psList.isEmpty()) {
						for (String key : ruleVOMap.keySet()) {
							DefaultVerifyRuleVO ruleVO = ruleVOMap.get(key);
							ruleVO.setIsFkpc(new Boolean(true));
						}
						com.setReserveFlag(VerifyDetailVO.reserve_pc);
						com.setIsauto(UFBoolean.TRUE);

						for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
							rule.setM_creditObjKeys(new String[] { SPECIAL_KEY });
							rule.setM_debtObjKeys(new String[] { SPECIAL_KEY });
						}

						this.doVerifyWithMap(psList, ruleVOMap, com, null);
					}
					// 来自项目预付和进度款的核销
					if (pcmListNoMatch.size() > 0 || pcmListMatch.size() > 0 || pcmListBatchNoMatch.size() > 0) {
						com.setReserveFlag(VerifyDetailVO.reserve_pcm);
						com.setIsauto(UFBoolean.FALSE);
						String billclass = (String) vos[0].getParentVO().getAttributeValue(IBillFieldGet.BILLCLASS);
						if (billclass.equals("ys") || billclass.equals("sk")) {
							for (ArapBillMapVO vo : pcmListNoMatch) {
								List<ArapBillMapVO> voss = new ArrayList<ArapBillMapVO>();
								voss.add(vo);
								this.doVerifyWithMap(voss, ruleVOMap, com);
							}
						} else {
							for (ArapBillMapVO vo : pcmListMatch) {
								List<ArapBillMapVO> voss = new ArrayList<ArapBillMapVO>();
								voss.add(vo);
								this.doVerifyWithMap(voss, ruleVOMap, com);
							}

							for (String key : pcmListBatchNoMatch.keySet()) {
								List<ArapBillMapVO> list = pcmListBatchNoMatch.get(key);
								this.doVerifyWithMap(list, ruleVOMap, com);
							}

							if (pcmListNoMatch.size() > 0) {
								this.doVerifyWithMap(pcmListNoMatch, ruleVOMap, com);
							}
						}
					}

					// 根据自动核销方案核销
					for (VerifyfaVO faVO : tradeTypeBills.keySet()) {
						if (faVO != null) {
							FaDMO dmo = new FaDMO();
							String sql = "  pk_org='" + faVO.getPk_org() + "' and node_code='" + faVO.getNode_code()
									+ "' and dr=0 and isinit='1'  and ";
							if (IBillFieldGet.F0.equals(pk_billtype) || IBillFieldGet.F3.equals(pk_billtype)) {
								sql += "  (COALESCE(bf_transtype,'~') ='~' or bf_transtype ='' or bf_transtype ='"
										+ faVO.getBf_transtype() + "') order by bf_transtype";
							} else {
								sql += "   (COALESCE(df_transtype,'~') ='~' or df_transtype ='' or df_transtype ='"
										+ faVO.getBf_transtype() + "') order by df_transtype";
							}
							List<VerifyfaVO> verifyfaVOs = dmo.queryFa(sql);
							if (verifyfaVOs != null && verifyfaVOs.size() > 0) {
								for (VerifyfaVO favo : verifyfaVOs) {
									int szxt = 0;
									if (favo.getNode_code().equals("20060VPS")) {// 应收
										szxt = 0;
									} else if (favo.getNode_code().equals("20080VPS")) {// 应付
										szxt = 1;
									}
									QueryAndRuleFaVO convertVo = new QueryAndRuleFaVO(favo, favo.getPk_org(),
											InvocationInfoProxy.getInstance().getUserId().trim(), Integer.valueOf(szxt),
											null, new UFDate(InvocationInfoProxy.getInstance().getBizDateTime()));

									ConditionVO condition = convertVo.getFilterConditionVO();
									if (IBillFieldGet.F0.equals(pk_billtype) || IBillFieldGet.F3.equals(pk_billtype)) {
										condition.setAttributeValue("jfFa", " and " + SqlUtils.getInStr("pk_bill",
												tradeTypeBills.get(faVO).toArray(new String[] {}), true));
									} else {
										condition.setAttributeValue("dfFa", " and " + SqlUtils.getInStr("pk_bill",
												tradeTypeBills.get(faVO).toArray(new String[] {}), true));
									}
									DefaultVerifyRuleVO[] rules = convertVo.getRuleVO();
									if (rules == null || rules.length == 0) {
									} else {
										ProxyVerify.getIArapVerifyLogPrivate().autoVerify(condition, rules);
									}
								}
							}
						}
					}
				} catch (BusinessException e1) {
					throw ExceptionHandler.handleException(e1);
				}
			}

		}
		// 取消生效前处理
		else if (IArapBSEventType.TYPE_UNEFFECTION_BEFORE.equals(event.getEventType())) {
			this.uneffectBill(event);
		}

		// 新增后-期初单
		else if (IEventType.TYPE_INSERT_AFTER.equals(event.getEventType())) {
			BusinessEvent e = (BusinessEvent) event;
			if (null != e.getUserObject()) {
				AggregatedValueObject[] vos = this.dealUserObj(e.getUserObject());
				// 期初单据新增后保存
				UFBoolean isinit = (UFBoolean) vos[0].getParentVO().getAttributeValue("isinit"); // 期初标志
				if (isinit != null && isinit.booleanValue()) {
					List<ArapBusiDataVO> busiDataVOList = new ArapVOTransformUtil().transform(vos);
					this.doInsertRegister(busiDataVOList);
				}
			}
		}

		// 删除后-期初单
		else if (IEventType.TYPE_DELETE_BEFORE.equals(event.getEventType())) {
			BusinessEvent e = (BusinessEvent) event;
			if (null != e.getUserObject()) {
				AggregatedValueObject[] vos = this.dealUserObj(e.getUserObject());
				List<String> deldata = new ArrayList<String>();
				for (AggregatedValueObject vo : vos) {
					deldata.add(vo.getParentVO().getPrimaryKey());
				}
				this.doCheckBillDeal(deldata);
				this.doDeleteRegisterByBillid(deldata.toArray(new String[] {}));
			}
		}

		if (IEventType.TYPE_UPDATE_AFTER.equals(event.getEventType())) {
			BdUpdateEvent e = (BdUpdateEvent) event;
			if (null != e.getNewObject()) {
				AggregatedValueObject[] vos = this.dealUserObjForInit(e.getNewObject());
				// 期初单据新增后保存
				UFBoolean isinit = (UFBoolean) vos[0].getParentVO().getAttributeValue("isinit"); // 期初标志
				String pk_bill = vos[0].getParentVO().getPrimaryKey(); // 期初标志
				if (isinit != null && isinit.booleanValue()) {
					// 先删除再插入
					new BaseDAO().deleteByClause(ArapBusiDataVO.class, " pk_bill ='" + pk_bill + "'");
					List<ArapBusiDataVO> busiDataVOList = new ArapVOTransformUtil().transform(vos);
					doInsertRegister(busiDataVOList);
				}

			}
		}
		LogTime.debug(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006ver_0",
				"02006ver-0258")/*
								 * @res "BillRegisterForBusiData(业务单据登账接口)"
								 */, t1);
	}

	private AggregatedValueObject[] billUneffectPreVerify(AggregatedValueObject[] vos, boolean isfkpc)
			throws BusinessException {
		Set<String> billSet = new HashSet<String>();
		Set<String> billtypeSet = new HashSet<String>();
		for (AggregatedValueObject vo : vos) {
			billSet.add(vo.getParentVO().getPrimaryKey());
			billtypeSet.add((String) vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE));
		}

		Collection<ArapBillMapVO> billMapData = new BaseDAO().retrieveByClause(ArapBillMapVO.class,
				SqlUtils.getInStr("t_billid", billSet.toArray(new String[billSet.size()]), true) + " and ISMANUAL='Y'");
		Map<String, UFDouble> key2ybye = this.doUnVerifyWithMap(billMapData, isfkpc, true);

		this.updateBillMapYbye(billMapData, false, key2ybye);

		// 7、重新查询单据
		IArapBillPubQueryService service = NCLocator.getInstance().lookup(IArapBillPubQueryService.class);
		// 本方单据
		BaseAggVO[] bfAggVOs = service.findBillByPrimaryKey(billSet.toArray(new String[0]),
				billtypeSet.toArray(new String[0]));
		return bfAggVOs;
	}

	/**
	 * 预核销关联的核销处理
	 * 
	 * @param vos
	 * @param ruleVOMap
	 * @param com
	 * @throws BusinessException
	 */
	private AggregatedValueObject[] billPreVerify(AggregatedValueObject[] vos,
			Hashtable<String, DefaultVerifyRuleVO> ruleVOMap, VerifyCom com) throws BusinessException {
		Set<String> billSet = new HashSet<String>();
		Set<String> billtypeSet = new HashSet<String>();
		for (AggregatedValueObject vo : vos) {
			billSet.add(vo.getParentVO().getPrimaryKey());
			billtypeSet.add((String) vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE));
		}
		// 1、查询可预核销数据
		Collection<ArapBillMapVO> billMapData = new BaseDAO().retrieveByClause(ArapBillMapVO.class,
				SqlUtils.getInStr("t_billid", billSet.toArray(new String[billSet.size()]), true) + " and ISMANUAL='Y'");
		if (billMapData == null || billMapData.isEmpty())
			return vos;
		com.setReserveFlag(VerifyDetailVO.reserve_arap);
		com.setExactVerify(true);
		for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
			rule.setM_creditObjKeys(new String[] { BillRegisterForBusiDataBO.SPECIAL_KEY });
			rule.setM_debtObjKeys(new String[] { BillRegisterForBusiDataBO.SPECIAL_KEY });
		}

		this.aggMap.clear();
		Set<String> pks = new HashSet<String>();
		for (ArapBillMapVO billMapVO : billMapData) {
			pks.add(billMapVO.getS_itemid());
			pks.add(billMapVO.getT_itemid());
		}
		if (pks.isEmpty())
			return vos;
		Collection<ArapBusiDataVO> busiList = new BaseDAO().retrieveByClause(ArapBusiDataVO.class,
				SqlUtils.getInStr("pk_item", pks.toArray(new String[] {}), true) + " and money_bal <> 0 "
						+ " and pausetransact ='N' ");
		if (busiList == null || busiList.isEmpty())
			return vos;
		ArapBusiDataVO[] busiDataVOs = busiList.toArray(new ArapBusiDataVO[busiList.size()]);
		DefaultVerifyRuleVO ruleVO = ruleVOMap.values().iterator().next();
		VerifyTool.sortVector(busiDataVOs, ruleVO.getM_verifySeq());
		// 比较ts 使用
		Map<String, String> busiDataTsMap = new HashMap<String, String>();
		Map<String, List<ArapBusiDataVO>> pk2BusiDataVO = new HashMap<String, List<ArapBusiDataVO>>();
		for (ArapBusiDataVO vo : busiDataVOs) {
			busiDataTsMap.put(vo.getPk_busidata(), vo.getTs().toString());
			String pk_item = vo.getPk_item();
			if (!pk2BusiDataVO.containsKey(pk_item))
				pk2BusiDataVO.put(pk_item, new ArrayList<ArapBusiDataVO>());
			pk2BusiDataVO.get(pk_item).add(vo);
		}
		com.setBusiDataTsMap(busiDataTsMap);
		com.setIsauto(UFBoolean.TRUE);
		aggMap.clear();

		// 2、设置busidatavo中的sett_money;
		for (ArapBillMapVO billMapVO : billMapData) {
			UFDouble sett_money = billMapVO.getYbye();
			// 来源
			List<ArapBusiDataVO> sBusiDataVOList = pk2BusiDataVO.get(billMapVO.getS_itemid());
			setSettmoney(sBusiDataVOList, sett_money);
			// 目的
			List<ArapBusiDataVO> tBusiDataVOList = pk2BusiDataVO.get(billMapVO.getT_itemid());
			setSettmoney(tBusiDataVOList, sett_money);
		}

		// 4、分组：借方vo、贷方vo
		List<ArapBusiDataVO> jf_vos = new ArrayList<ArapBusiDataVO>();// 借方
		List<ArapBusiDataVO> df_vos = new ArrayList<ArapBusiDataVO>();// 贷方
		for (ArapBusiDataVO vo : busiDataVOs) {
			Integer direction = (Integer) vo.getAttributeValue(ArapBusiDataVO.DIRECTION);
			if (direction.intValue() == 1) {
				jf_vos.add(vo);
			} else {
				df_vos.add(vo);
			}
		}

		// 5、核销
		aggMap = onVerify4Pre(billMapData, com, ruleVOMap, jf_vos.toArray(new ArapBusiDataVO[] {}),
				df_vos.toArray(new ArapBusiDataVO[] {}));
		// 6、组装核销结果集vo
		ArrayList<AggverifyVO> aggVOList = this.getAggVerifyVO(aggMap, com.getIsauto());
		this.dealOrgScomment(aggVOList);
		// 7、核销结果保存
		if (aggVOList != null && aggVOList.size() > 0) {
			NCLocator.getInstance().lookup(IArapVerifyLogPrivate.class).save(aggVOList, ruleVOMap, com);
		}

		this.updateBillMapYbye(billMapData, true, null);

		// 7、重新查询单据
		IArapBillPubQueryService service = NCLocator.getInstance().lookup(IArapBillPubQueryService.class);
		// 本方单据
		BaseAggVO[] bfAggVOs = service.findBillByPrimaryKey(billSet.toArray(new String[0]),
				billtypeSet.toArray(new String[0]));
		return bfAggVOs;
	}

	/**
	 * 预核销关联后核销
	 * 
	 * @param billMapData
	 * @param com
	 * @param ruleVOMap
	 * @param jf_vos
	 * @param df_vos
	 * @return
	 */
	private Map<String, ArrayList<AggverifyVO>> onVerify4Pre(Collection<ArapBillMapVO> billMapData, VerifyCom com,
			Map<String, DefaultVerifyRuleVO> ruleVOMap, ArapBusiDataVO[] jf_vos, ArapBusiDataVO[] df_vos) {

		// 自动核销 只有红蓝对冲，同币种核销
		com.setM_creditSelected(df_vos);
		com.setM_debitSelected(jf_vos);
		AggverifyVO aggvo = null;
		if (!ArrayUtils.isEmpty(jf_vos) || !ArrayUtils.isEmpty(df_vos)) {
			// 处理内部红蓝对冲，单据间的红蓝对冲
			// 按行处理，存在多对多的情况
			DefaultVerifyRuleVO rulevo = ruleVOMap.get("RB_VERIFY");
			RBVerify rbverify = new RBVerify(com);
			SameMnyVerify smverify = new SameMnyVerify(com);
			for (ArapBillMapVO billMapVO : billMapData) {
				String s_itemid = billMapVO.getS_itemid();
				String t_itemid = billMapVO.getT_itemid();
				String sDirect = "F0".equals(billMapVO.getS_billtype()) || "F3".equals(billMapVO.getS_billtype()) ? "D"
						: "C";
				String tDirect = "F0".equals(billMapVO.getT_billtype()) || "F3".equals(billMapVO.getT_billtype()) ? "D"
						: "C";
				if (sDirect.equals(tDirect)) {
					int i = 0;
					for (ArapBusiDataVO df_vo : df_vos) {
						if (s_itemid.equals(df_vo.getPk_item()) || t_itemid.equals(df_vo.getPk_item())) {
							df_vo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, billMapVO.getPk_billmap());
						} else {
							df_vo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, i++);
						}
					}
					for (ArapBusiDataVO jf_vo : jf_vos) {
						if (s_itemid.equals(jf_vo.getPk_item()) || t_itemid.equals(jf_vo.getPk_item())) {
							jf_vo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, billMapVO.getPk_billmap());
						} else {
							jf_vo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, i++);
						}
					}
					aggvo = rbverify.onVerify(jf_vos, df_vos, rulevo);
					if (!ArrayUtils.isEmpty(aggvo.getChildrenVO())) {
						if (this.aggMap.containsKey("RB_VERIFY")) {
							this.aggMap.get("RB_VERIFY").add(aggvo);
						} else {
							ArrayList<AggverifyVO> temp = new ArrayList<AggverifyVO>();
							temp.add(aggvo);
							this.aggMap.put("RB_VERIFY", temp);
						}
					}
				} else {
					int i = 0;
					for (ArapBusiDataVO df_vo : df_vos) {
						if (s_itemid.equals(df_vo.getPk_item()) || t_itemid.equals(df_vo.getPk_item())) {
							df_vo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, billMapVO.getPk_billmap());
						} else {
							df_vo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, i++);
						}
					}
					for (ArapBusiDataVO jf_vo : jf_vos) {
						if (s_itemid.equals(jf_vo.getPk_item()) || t_itemid.equals(jf_vo.getPk_item())) {
							jf_vo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, billMapVO.getPk_billmap());
						} else {
							jf_vo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, i++);
						}
					}
					aggvo = smverify.onVerify(jf_vos, df_vos, rulevo);
					if (!ArrayUtils.isEmpty(aggvo.getChildrenVO())) {
						if (this.aggMap.containsKey("SAME_VERIFY")) {
							this.aggMap.get("SAME_VERIFY").add(aggvo);
						} else {
							ArrayList<AggverifyVO> temp = new ArrayList<AggverifyVO>();
							temp.add(aggvo);
							this.aggMap.put("SAME_VERIFY", temp);
						}
					}
				}
			}
		}

		return this.aggMap;

	}

	/**
	 * 设置结算金额和核销时匹配规则的维度
	 * 
	 * @param busiDataVOList
	 * @param sett_money
	 */
	private void setSettmoney(List<ArapBusiDataVO> busiDataVOList, UFDouble sett_money) {
		if (busiDataVOList != null && !busiDataVOList.isEmpty()) {
			UFDouble tmp = sett_money;
			for (ArapBusiDataVO busiDataVO : busiDataVOList) {
				if (UFDouble.ZERO_DBL.compareTo(tmp) == 0)
					break;
				int multi = UFDouble.ZERO_DBL.compareTo(busiDataVO.getMoney_bal()) > 0 ? -1 : 1;
				UFDouble settMoney = busiDataVO.getAttributeValue(ArapBusiDataVO.SETT_MONEY) == null ? UFDouble.ZERO_DBL
						: (UFDouble) busiDataVO.getAttributeValue(ArapBusiDataVO.SETT_MONEY);
				UFDouble diffMoney = busiDataVO.getMoney_bal().sub(busiDataVO.getOccupationmny()).sub(settMoney);
				if (sett_money.multiply(busiDataVO.getMoney_bal()).compareTo(UFDouble.ZERO_DBL) < 0) {// 红蓝对冲数据
					if (diffMoney.abs().compareTo(tmp.abs()) < 0) {
						busiDataVO.setAttributeValue(ArapBusiDataVO.SETT_MONEY, settMoney.add(diffMoney));
						tmp = tmp.add(diffMoney);
					} else {
						busiDataVO.setAttributeValue(ArapBusiDataVO.SETT_MONEY,
								settMoney.add(tmp.abs().multiply(multi)));
						tmp = UFDouble.ZERO_DBL;
					}
				} else {
					if (diffMoney.abs().compareTo(tmp.abs()) < 0) {
						busiDataVO.setAttributeValue(ArapBusiDataVO.SETT_MONEY, settMoney.add(diffMoney));
						tmp = tmp.sub(diffMoney);
					} else {
						busiDataVO.setAttributeValue(ArapBusiDataVO.SETT_MONEY, settMoney.add(tmp));
						tmp = UFDouble.ZERO_DBL;
					}
				}
			}
		}
	}

	private void printMapForDebug(Map<ArapBillMapVO, Collection<ArapBillMapVO>> arapBillMap) {
		try {
			if (arapBillMap != null) {
				for (ArapBillMapVO vo : arapBillMap.keySet()) {
					Log.getInstance(LogTime.class).debug("ARAPBILLMAP");/* -=notranslate=- */
					Log.getInstance(LogTime.class).debug(vo.getYbje());/* -=notranslate=- */
					Log.getInstance(LogTime.class).debug(vo.getYbye());/* -=notranslate=- */
					Log.getInstance(LogTime.class).debug(vo.getS_itemid());/* -=notranslate=- */
					Log.getInstance(LogTime.class).debug(vo.getT_itemid());/* -=notranslate=- */
					for (ArapBillMapVO svo : arapBillMap.get(vo)) {
						Log.getInstance(LogTime.class).debug(svo.getYbje());/* -=notranslate=- */
						Log.getInstance(LogTime.class).debug(svo.getYbye());/* -=notranslate=- */
						Log.getInstance(LogTime.class).debug(svo.getS_itemid());/* -=notranslate=- */
						Log.getInstance(LogTime.class).debug(svo.getT_itemid());/* -=notranslate=- */
					}
					Log.getInstance(LogTime.class).debug("ENDDDDD");/* -=notranslate=- */
				}
			}
		} catch (Exception e) {
		}
	}

	private void uneffectBill(IBusinessEvent event) throws BusinessException {
		BusinessEvent e = (BusinessEvent) event;
		if (null != e.getUserObject()) {
			AggregatedValueObject[] vos = this.dealUserObj(e.getUserObject());

			String billclass = ((BaseAggVO) vos[0]).getHeadVO().getBillclass();
			boolean ifF1Uneffect = billclass != null && billclass.equals(IBillFieldGet.YF);// 是否应付单反审核，是的话则反核销不需要通知付款申请接口
			boolean isfkpc = false;// 是否应付单反审核，是的话则反核销不需要通知付款申请接口
			if (ifF1Uneffect) {
				isfkpc = true;
			}

			// begin
			// 做了预核销的数据核销 add by zhaoyanf
			vos = billUneffectPreVerify(vos, isfkpc);
			// end

			List<String> deldata = new ArrayList<String>();
			List<String> pks = new ArrayList<String>();
			List<ArapBillMapVO> puList = new ArrayList<ArapBillMapVO>(); // 采购
			List<ArapBillMapVO> soList = new ArrayList<ArapBillMapVO>(); // 销售订单-收款单
			List<ArapBillMapVO> htList = new ArrayList<ArapBillMapVO>(); // 销售合同-收单
			List<ArapBillMapVO> psList = new ArrayList<ArapBillMapVO>(); // 付款排程
			List<ArapBillMapVO> pcmList = new ArrayList<ArapBillMapVO>(); // 项目合同
			List<String> bodypks = new ArrayList<String>();
			List<ArapBillMapVO> F2ForSoList = new ArrayList<ArapBillMapVO>(); // 订单收款,//
																				// 手工挂上一个收款单
			for (AggregatedValueObject vo : vos) {
				Integer src_syscode = (Integer) vo.getParentVO().getAttributeValue(IBillFieldGet.SRC_SYSCODE);
				BaseItemVO[] childrenVO = (BaseItemVO[]) vo.getChildrenVO();
				if (src_syscode.intValue() == FromSystem.AR.VALUE.intValue()
						|| src_syscode.intValue() == FromSystem.AP.VALUE.intValue()) {
					pks.add(vo.getParentVO().getPrimaryKey());
					if (src_syscode.intValue() == FromSystem.AR.VALUE.intValue()
							&& vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE).equals(IBillFieldGet.F2)) {
						for (BaseItemVO itemVO : childrenVO) {
							ArapBillMapVO mapVO = new ArapBillMapVO();
							mapVO.setT_itemid(itemVO.getPrimaryKey());
							if (IBillFieldGet.F2.equals(itemVO.getAttributeValue(IBillFieldGet.TOP_BILLTYPE))) {
								bodypks.add(itemVO.getPrimaryKey());
							} else {
								F2ForSoList.add(mapVO);
							}
						}
					}
					if (src_syscode.intValue() == FromSystem.AP.VALUE.intValue()
							&& vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE).equals(IBillFieldGet.F3)) {
						for (BaseItemVO itemVO : childrenVO) {
							ArapBillMapVO mapVO = new ArapBillMapVO();
							mapVO.setT_itemid(itemVO.getPrimaryKey());
							if (IBillFieldGet.F3.equals(itemVO.getAttributeValue(IBillFieldGet.TOP_BILLTYPE))) {
								bodypks.add(itemVO.getPrimaryKey());
							}
						}
					}
				} else {
					String pk_billtype = (String) vo.getParentVO().getAttributeValue(IBillFieldGet.PK_BILLTYPE);
					if (pk_billtype.equals(IBillFieldGet.F0) || pk_billtype.equals(IBillFieldGet.F2)) {
						for (BaseItemVO itemVO : childrenVO) {
							ArapBillMapVO mapVO = new ArapBillMapVO();
							mapVO.setT_itemid(itemVO.getPrimaryKey());
							// 销售合同-收款单
							if (ArapBillDealVOConsts.BILLTYPE_Z3.equals(itemVO.getTop_billtype())) {
								htList.add(mapVO);
							} else {
								soList.add(mapVO);
							}
						}
					} else if (pk_billtype.equals(IBillFieldGet.F1) || pk_billtype.equals(IBillFieldGet.F3)) {
						for (BaseItemVO itemVO : childrenVO) {
							ArapBillMapVO mapVO = new ArapBillMapVO();
							mapVO.setT_itemid(itemVO.getPrimaryKey());
							// 应付单 -付款申请||执行计划 -付款单
							if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(childrenVO[0].getTop_billtype())
									|| ArapBillDealVOConsts.BILLTYPE_36D7.equals(childrenVO[0].getTop_billtype())) {
								psList.add(mapVO);
							} else if (itemVO.getTop_billtype() != null && (ArapBillDealVOConsts.BILLTYPE_4D46
									.equals(childrenVO[0].getTop_billtype())
									|| ArapBillDealVOConsts.BILLTYPE_4D50.equals(childrenVO[0].getTop_billtype())
									|| ArapBillDealVOConsts.BILLTYPE_4D48.equals(childrenVO[0].getTop_billtype()))) {
								pcmList.add(mapVO);
							} else {
								puList.add(mapVO);
							}
						}
					}
				}
				deldata.add(vo.getParentVO().getPrimaryKey());
			}
			this.doCheckBillDeal(deldata);
			// 拉式生成单审核后反核销
			try {

				if (pks != null && pks.size() > 0) {
					Collection<ArapBillMapVO> billMapData = new BaseDAO().retrieveByClause(ArapBillMapVO.class,
							SqlUtils.getInStr("t_billid", pks.toArray(new String[] {}), true) + " and ISMANUAL<>'Y'");
					this.doUnVerifyWithMap(billMapData, isfkpc, false);
					this.updateBillMapYbye(billMapData, false, null);
					// 订单收款 手工挂上收款单
					if (billMapData == null || billMapData.size() == 0) {
						if (F2ForSoList != null && !F2ForSoList.isEmpty()) {
							// 订单收款 手工挂上一个 收款单 ，收款单不更新预占用余额，应收单更新
							this.doUnVerifyWithMap(F2ForSoList, isfkpc, false);
						}
					}
				}
				// 项目合同单据
				if (pcmList != null && !pcmList.isEmpty()) {
					this.doUnVerifyWithMap(pcmList, isfkpc, false);
					;
				}
				// 来自资金的付款排程单据
				if (psList != null && !psList.isEmpty()) {
					this.doUnVerifyWithMap(psList, Boolean.TRUE, false);
				}
				if (soList != null && !soList.isEmpty()) {
					// 订单-收款单不更新预占用余额，应收单更新
					this.doUnVerifyWithMap(soList, isfkpc, false);
				}
				if (htList != null && !htList.isEmpty()) {
					// 合同-收款单更新预占用余额
					this.doUnVerifyWithMap(htList, isfkpc, false);
				}
				if (puList != null && !puList.isEmpty()) {
					this.doUnVerifyWithMap(puList, isfkpc, false);
				}

				if (bodypks.size() > 0) {
					Collection<ArapBillMapVO> billMapData = new HashSet<ArapBillMapVO>();
					for (String pk : bodypks) {
						ArapBillMapVO vo = new ArapBillMapVO();
						vo.setT_itemid(pk);
						billMapData.add(vo);
					}
					this.doUnVerifyWithMap(billMapData, isfkpc, false);
				}

				this.doDeleteRegisterByBillid(deldata.toArray(new String[] {}));
			} catch (Exception e1) {
				throw ExceptionHandler.handleException(e1);
			}
		}
	}

	protected AggregatedValueObject[] dealUserObjForInit(Object obj) {

		AggregatedValueObject[] retvos = null;
		if (obj.getClass().isArray()) {
			retvos = (AggregatedValueObject[]) obj;
		} else {
			retvos = new AggregatedValueObject[] { (AggregatedValueObject) obj };
		}
		this.pk_user = (String) retvos[0].getParentVO().getAttributeValue(ArapBusiDataVO.APPROVER);
		this.syscode = (Integer) retvos[0].getParentVO().getAttributeValue(ArapBusiDataVO.SYSCODE);
		this.pkorg = (String) retvos[0].getParentVO().getAttributeValue(ArapBusiDataVO.PK_ORG);
		return retvos;
	}

	@SuppressWarnings("unused")
	private void VerifyByContractNo(AggregatedValueObject[] vos, VerifyCom com,
			Hashtable<String, DefaultVerifyRuleVO> ruleVOMap) throws BusinessException {
	}

	private void VerifyByContractNo(List<ArapBillMapVO> MapVOList, VerifyCom com,
			Hashtable<String, DefaultVerifyRuleVO> ruleVOMap) throws BusinessException {
	}

	// 核销后 ，billmap表 ybye字段赋值为0
	private void updateBillMapYbye(Collection<ArapBillMapVO> billMapData, boolean setZero,
			Map<String, UFDouble> key2ybye) throws DAOException {
		String[] fild = new String[] { "ybye" };
		if (billMapData != null && billMapData.size() > 0) {
			if (setZero) {
				for (ArapBillMapVO vo : billMapData) {
					vo.setYbye(UFDouble.ZERO_DBL);
				}
			} else {
				if (key2ybye == null) {
					for (ArapBillMapVO vo : billMapData) {
						vo.setYbye(vo.getYbje());
					}
				} else {
					for (ArapBillMapVO vo : billMapData) {
						String key = vo.getS_itemid() + vo.getT_itemid();
						int multi = vo.getYbje().compareTo(UFDouble.ZERO_DBL) > 0 ? 1 : -1;
						if (key2ybye.get(key) != null)
							vo.setYbye(key2ybye.get(key).abs().multiply(multi));
					}
				}

			}
			billMapData.toArray(new SuperVO[0]);
			new BaseDAO().updateVOArray(billMapData.toArray(new SuperVO[0]), fild);
		}

	}

	public void doCheckBillDeal(List<String> pkbillList) throws BusinessException {
		String[] pkbillArr = pkbillList.toArray(new String[] {});
		String insql = "";
		BaseDAO dao = new BaseDAO();
		insql = SqlUtils.getInStr("pk_bill", pkbillArr, true);
		String[] fields = new String[] { VerifyDetailVO.PK_BILL, VerifyDetailVO.BILLNO };
		// 查询核销数据
		Collection<VerifyDetailVO> verifydata = dao.retrieveByClause(VerifyDetailVO.class,
				insql + " and isauto='N' and isreserve = 0", fields);
		StringBuffer billStr = new StringBuffer();
		Set<String> billSet = new java.util.HashSet<String>();
		if (verifydata != null && verifydata.size() > 0) {
			for (VerifyDetailVO vo : verifydata) {
				billSet.add(vo.getBillno());
			}
			for (String billno : billSet) {
				billStr.append(billno);
				billStr.append(",");
			}
			int lastIndexOf = billStr.lastIndexOf(",");
			String substring = billStr.substring(0, lastIndexOf);
			throw new BusinessException(
					nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006ver_0", "02006ver-0251")/*
																										 * @res "单据"
																										 */
							+ substring + nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006ver_0",
									"02006ver-0259")/*
													 * @res "已经进行核销，不能取消审核"
													 */);

		}
		// 是否做过汇兑损益处理
		Collection<AgiotageChildVO> agiotagedata = dao.retrieveByClause(AgiotageChildVO.class,
				insql + "and not exists (select 1 from ARAP_VERIFYDETAIL where " + insql + " )", fields);
		if (agiotagedata != null && agiotagedata.size() > 0) {
			throw new BusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006ver_0",
					"02006ver-0260")/*
									 * @res "已经做过汇兑损益，不能取消操作"
									 */);
		}
		// 是否做过并账处理
		Collection<DebtTransferVO> debtdata = dao.retrieveByClause(DebtTransferVO.class, insql, fields);
		if (debtdata != null && debtdata.size() > 0) {
			throw new BusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006ver_0",
					"02006ver-0261")/*
									 * @res "已经做过并账，不能取消操作"
									 */);
		}
		// 是否做过坏账损失处理
		String[] badLossFields = new String[] { BdLossChildVO.PK_BILL };
		Collection<BdLossChildVO> badLossdata = dao.retrieveByClause(BdLossChildVO.class,
				insql + " and isnull(dr,0)=0 ", badLossFields);
		if (badLossdata != null && badLossdata.size() > 0) {
			throw new BusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006ver_0",
					"02006ver-0262")/* @res "已经做过坏账损失，不能取消操作" */);
		}
		// 是否做过坏账收回处理
		String bdRecInsql = "";
		bdRecInsql = SqlUtils.getInStr(BdRecoverySKVO.PK_GATHERBILL, pkbillArr, true);
		String[] badRecFields = new String[] { BdRecoverySKVO.PK_GATHERBILL };
		Collection<BdRecoverySKVO> badRecdata = dao.retrieveByClause(BdRecoverySKVO.class,
				bdRecInsql + " and isnull(dr,0)=0 ", badRecFields);
		if (badRecdata != null && badRecdata.size() > 0) {
			throw new BusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006ver_0",
					"02006ver-0263")/* @res "已经做过坏账收回，不能取消操作" */);
		}
	}

	protected void doInsertRegister(List<ArapBusiDataVO> insertdatas) throws BusinessException {
		Logger.debug("插入arap_busidata 表  数量 =" + insertdatas.size());
		if (insertdatas != null && insertdatas.size() > 0)
			new BaseDAO().insertVOList(insertdatas);
	}

	protected void doUpdateRegister(List<ArapBusiDataVO> updatedatas) throws BusinessException {
		new BaseDAO().updateVOList(updatedatas);
	}

	protected void doDeleteRegisterByBillid(String[] billids) throws BusinessException {
		// 业务数据加锁
		if (!PKLock.getInstance().addBatchDynamicLock(billids)) {
			throw new BusinessException(
					nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006ver_0", "02006ver-0257")/*
																										 * @res "并发错误"
																										 */);
		}
		new BaseDAO().deleteByClause(ArapBusiDataVO.class, SqlUtils.getInStr("pk_bill", billids, true));
	}

	protected void doDeleteRegisterByItemid(String[] itemids) throws BusinessException {
		new BaseDAO().deleteByClause(ArapBusiDataVO.class, SqlUtils.getInStr("pk_item", itemids, true));
	}

	// 反核销
	private Map<String, UFDouble> doUnVerifyWithMap(Collection<ArapBillMapVO> mapvos, Boolean isFkpc, Boolean isPre)
			throws BusinessException {

		if (mapvos == null || mapvos.size() == 0) {
			return null;
		}
		Map<String, String> businoMap = new HashMap<String, String>();

		List<String> pks = new ArrayList<String>();
		for (ArapBillMapVO vo : mapvos) {
			pks.add(vo.getT_itemid());
		}
		Map<String, UFDouble> key2ybye = new HashMap<String, UFDouble>();// 对于预核销数据，用于回写billmap表
		// 核销子表
		Collection<VerifyDetailVO> detailColet = new BaseDAO().retrieveByClause(VerifyDetailVO.class,
				SqlUtils.getInStr("pk_item", pks.toArray(new String[] {}), true));
		for (VerifyDetailVO detailvo : detailColet) {
			if (businoMap.containsKey(detailvo.getBusino())) {
				businoMap.put(detailvo.getBusino(), businoMap.get(detailvo.getBusino()));
			} else {
				businoMap.put(detailvo.getBusino(), detailvo.getBusino());
			}
			if (isPre) {
				String key = detailvo.getPk_item2() + detailvo.getPk_item();
				UFDouble money = detailvo.getMoney_cr().add(detailvo.getMoney_de());
				if (!key2ybye.containsKey(key)) {
					key2ybye.put(key, money);
				} else {
					key2ybye.put(key, key2ybye.get(key).add(money));
				}

			}
		}
		if (businoMap.size() == 0) {
			return null;
		}
		// 组织核销聚合VO
		Set<String> keyset = businoMap.keySet();
		keyset.toArray(new String[keyset.size()]);
		NCLocator.getInstance().lookup(IArapVerifyLogPrivate.class)
				.onCancelVerify(keyset.toArray(new String[keyset.size()]), isFkpc);
		return key2ybye.size() == 0 ? null : key2ybye;
	}

	// 核销
	private void doVerifyWithMap(Collection<ArapBillMapVO> mapvos, Hashtable<String, DefaultVerifyRuleVO> ruleVOMap,
			VerifyCom com, String nouse) throws BusinessException {
		if (mapvos == null || mapvos.size() == 0) {
			return;
		}

		// 根据参数确定是否要按照预收付标志核销
		if (VerifyDetailVO.reserve_so.equals(com.getReserveFlag())) {
			UFBoolean isNeed = SysInit.getParaBoolean(this.getPkorg(), SysinitConst.AR35);
			if (isNeed != null && isNeed.booleanValue()) {
				for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
					rule.setM_creditObjKeys(new String[] { IArapItemFieldVO.PREPAY });
					rule.setM_debtObjKeys(new String[] { IArapItemFieldVO.PREPAY });
				}
			}
		} else if (VerifyDetailVO.reserve_pu.equals(com.getReserveFlag())) {
			UFBoolean isNeed = SysInit.getParaBoolean(this.getPkorg(), SysinitConst.AP35);
			if (isNeed != null && isNeed.booleanValue()) {
				for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
					rule.setM_creditObjKeys(new String[] { IArapItemFieldVO.PREPAY });
					rule.setM_debtObjKeys(new String[] { IArapItemFieldVO.PREPAY });
				}
			}
		} else if (VerifyDetailVO.reserve_pcm.equals(com.getReserveFlag())) {
			UFBoolean isNeed = SysInit.getParaBoolean(this.getPkorg(), SysinitConst.AP35);// 应付
			if (mapvos.iterator().next().getS_system() == 0) {// 应收
				isNeed = SysInit.getParaBoolean(this.getPkorg(), SysinitConst.AR35);
			}
			if (isNeed != null && isNeed.booleanValue()) {
				for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
					rule.setM_creditObjKeys(new String[] { IArapItemFieldVO.PREPAY });
					rule.setM_debtObjKeys(new String[] { IArapItemFieldVO.PREPAY });
				}
			}
		}

		this.aggMap.clear();
		List<String> pks = new ArrayList<String>();
		List<String> termPkList = new ArrayList<String>();
		List<String> itemPkList = new ArrayList<String>();
		Collection<ArapBusiDataVO> busiList = null;
		ArapBillMapVO[] mapVOs2 = mapvos.toArray(new ArapBillMapVO[0]);
		// 调试是 注释 再打开
		Map<String, String> item_top_termMap = new HashMap<String, String>();
		for (ArapBillMapVO vo : mapvos) {
			// 根据系统来源判断 是否来自付款申请
			if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(vo.getS_billtype())
					|| ArapBillDealVOConsts.BILLTYPE_36D7.equals(vo.getS_billtype())) {
				// 判断 只有资金的付款排成 才可以按协议行核销
				termPkList.add(vo.getS_termid());
				itemPkList.add(vo.getT_itemid());
				item_top_termMap.put(vo.getS_itemid(), vo.getS_termid());
			} else {
				if (vo.getS_itemid() == null) { // 源头id 为空 ，没有数据不用核销
				} else {
					pks.add(vo.getS_itemid());
					pks.add(vo.getT_itemid());
				}
			}
		}
		if (termPkList != null && termPkList.size() > 0) {
			String sql = SqlUtils.getInStr("pk_termitem", termPkList.toArray(new String[] {}), true)
					+ " and pausetransact ='N' " + " or "
					+ SqlUtils.getInStr("pk_item", itemPkList.toArray(new String[] {}), true)
					+ " and pausetransact ='N' ";
			busiList = new BaseDAO().retrieveByClause(ArapBusiDataVO.class, sql);
			if (busiList != null) {
				for (ArapBusiDataVO b : busiList) {
					String pk_item = b.getPk_item();
					if (item_top_termMap.containsKey(pk_item)) {
						b.setDef1(item_top_termMap.get(pk_item));
					} else {
						b.setDef1(b.getPk_termitem());
					}

				}
			}
		} else {
			if (pks != null && pks.size() > 0) {
				busiList = new BaseDAO().retrieveByClause(ArapBusiDataVO.class,
						SqlUtils.getInStr("pk_item", pks.toArray(new String[] {}), true) + " and pk_org='"
								+ ruleVOMap.values().iterator().next().getPk_org() + "' and pausetransact ='N' "
								+ " and money_bal <> 0  " + " and pk_currtype ='" + mapVOs2[0].getPk_currtype()

								+ "'");
			}
		}
		if (busiList == null || busiList.size() == 0) {
			return;
		}
		// 比较ts 使用
		Map<String, String> busiDataTsMap = new HashMap<String, String>();
		for (ArapBusiDataVO vo : busiList) {
			busiDataTsMap.put(vo.getPk_busidata(), vo.getTs().toString());
		}
		com.setBusiDataTsMap(busiDataTsMap);
		List<ArapBusiDataVO> jfList = new ArrayList<ArapBusiDataVO>();
		List<ArapBusiDataVO> dfList = new ArrayList<ArapBusiDataVO>();
		// 区分本方 对方
		for (ArapBusiDataVO data : busiList) {
			boolean isjf = false;
			for (ArapBillMapVO mpvo : mapVOs2) {
				if (data.getPk_item().equals(mpvo.getT_itemid())) {
					isjf = true;
				}
			}
			if (isjf) {
				jfList.add(data);
			} else {
				dfList.add(data);
			}
		}
		// 排序
		Integer flag = ruleVOMap.get("SAME_VERIFY").getM_verifySeq();
		ArapBusiDataVO[] jfVos = jfList.toArray(new ArapBusiDataVO[0]);
		ArapBusiDataVO[] dfVos = dfList.toArray(new ArapBusiDataVO[0]);
		VerifyTool.sortVector(jfVos, flag.intValue());
		VerifyTool.sortVector(dfVos, flag.intValue());

		Map<String, List<ArapBusiDataVO>> dfBusidataMap = getBusidataMap(dfVos);

		UFDouble clje = UFDouble.ZERO_DBL;
		UFDouble jf_clje = UFDouble.ZERO_DBL;
		for (ArapBillMapVO vo : mapVOs2) {
			clje = clje.add(vo.getYbje());
		}
		jf_clje = clje;
		// 分配金额
		if (mapVOs2[0].getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_36D1)
				|| mapVOs2[0].getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_36D7)) {
			for (ArapBillMapVO vo : mapvos) {
				if (vo.getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_36D1)
						|| vo.getS_billtype().equals(ArapBillDealVOConsts.BILLTYPE_36D7)) {
					// 付款申请，s_item =null,用s_termitem
					// UFDouble clje1 = vo.getYbje();
					if (dfList != null && dfList.size() > 0) {
						for (ArapBusiDataVO datavo : dfVos) {
							UFDouble occupationmny = datavo.getOccupationmny();
							UFDouble money_bal = datavo.getMoney_bal();
							occupationmny = money_bal.sub(occupationmny);
							// if (clje1.compareTo(occupationmny) > 0) {
							// datavo.setAttributeValue(ArapBusiDataVO.SETT_MONEY,
							// occupationmny);
							// clje1 = clje.sub(occupationmny);
							// } else {
							// clje1 = UFDouble.ZERO_DBL;
							// }
							datavo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, occupationmny);
						}
					}
				}
			}
		} else {
			// 排序后 分配金额
			if (dfList != null && dfList.size() > 0) {
				for (String pk_item : dfBusidataMap.keySet()) {
					List<ArapBusiDataVO> list = dfBusidataMap.get(pk_item);
					UFDouble verifyMoney = UFDouble.ZERO_DBL;
					for (ArapBillMapVO mapvo : mapvos) {
						if (pk_item.equals(mapvo.getS_itemid())) {
							verifyMoney = mapvo.getYbje();
							break;
						}
					}
					for (ArapBusiDataVO datavo : list) {
						UFDouble occupationmny = datavo.getOccupationmny();
						UFDouble money_bal = datavo.getMoney_bal();
						if (datavo.getPk_billtype().equals(IBillFieldGet.F2)) {
							// 有销售订单收款预核销 占用
							if (verifyMoney.compareTo(money_bal.sub(occupationmny)) > 0) {
								datavo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, money_bal.sub(occupationmny));
								verifyMoney = verifyMoney.sub(money_bal.sub(occupationmny));
							} else {
								datavo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, verifyMoney);
								verifyMoney = UFDouble.ZERO_DBL;
							}
						} else {
							if (verifyMoney.compareTo(occupationmny) > 0) {
								datavo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, occupationmny);
								verifyMoney = verifyMoney.sub(occupationmny);
							} else {
								datavo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, verifyMoney);
								verifyMoney = UFDouble.ZERO_DBL;
							}
						}
					}
				}
			}
		}
		for (ArapBusiDataVO jfvo : jfVos) {
			UFDouble occupationmny = jfvo.getOccupationmny();
			UFDouble money_bal = jfvo.getMoney_bal();
			if (jfvo.getPk_billtype().equals(IBillFieldGet.F2)) {
				// 有销售订单收款预核销 占用
				if (jf_clje.compareTo(money_bal.sub(occupationmny)) > 0) {
					jfvo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, money_bal.sub(occupationmny));
					jf_clje = jf_clje.sub(money_bal.sub(occupationmny));
				} else {
					jfvo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, jf_clje);
					jf_clje = UFDouble.ZERO_DBL;
				}
			} else {
				if (jf_clje.compareTo(occupationmny) > 0 || jf_clje.compareTo(occupationmny) < 0) {
					jfvo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, occupationmny);
					jf_clje = jf_clje.sub(occupationmny);
				} else {
					jfvo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, jf_clje);
					jf_clje = UFDouble.ZERO_DBL;
				}
			}
		}
		// for (ArapBusiDataVO jfvo : jfVos) {
		// UFDouble occupationmny = jfvo.getOccupationmny();
		// jfvo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, occupationmny);
		// }
		// for (ArapBusiDataVO dfvo : dfVos) {
		// UFDouble occupationmny = dfvo.getOccupationmny();
		// dfvo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, occupationmny);
		// }
		List<ArapBusiDataVO> jf = new ArrayList<ArapBusiDataVO>();
		List<ArapBusiDataVO> df = new ArrayList<ArapBusiDataVO>();

		for (ArapBusiDataVO jfvo : jfVos) {
			if (jfvo.getDirection().intValue() == BillEnumCollection.Direction.DEBIT.VALUE.intValue()) {
				jf.add(jfvo);
			} else {
				df.add(jfvo);
			}
		}
		for (ArapBusiDataVO jfvo : dfVos) {
			if (jfvo.getDirection().intValue() == BillEnumCollection.Direction.DEBIT.VALUE.intValue()) {
				jf.add(jfvo);
			} else {
				df.add(jfvo);
			}
		}

		aggMap = onVerify(com, ruleVOMap, jf.toArray(new ArapBusiDataVO[] {}), df.toArray(new ArapBusiDataVO[] {}));
		ArrayList<AggverifyVO> aggVOList = getAggVerifyVO(aggMap, com.getIsauto());
		// 核销结果保存
		if (aggVOList != null && aggVOList.size() > 0) {
			NCLocator.getInstance().lookup(IArapVerifyLogPrivate.class).save(aggVOList, ruleVOMap, com);
		}

	}

	private Map<String, List<ArapBusiDataVO>> getBusidataMap(ArapBusiDataVO[] dfVos) {
		Map<String, List<ArapBusiDataVO>> dataMap = new HashMap<String, List<ArapBusiDataVO>>();
		for (ArapBusiDataVO vo : dfVos) {
			if (dataMap.containsKey(vo.getPk_item())) {
				dataMap.get(vo.getPk_item()).add(vo);
			} else {
				List<ArapBusiDataVO> tempList = new ArrayList<ArapBusiDataVO>();
				tempList.add(vo);
				dataMap.put(vo.getPk_item(), tempList);
			}
		}

		return dataMap;
	}

	public static String SAMVERIFYFLAG = "SAMVERIFYFLAG"; // 同币种核销

	public static String UNVERIFYFLAG = "UNVERIFYFLAG"; // 异币种核销

	public static String HCSAMVERIFYFLAG = "HCSAMVERIFYFLAG"; // 同币种红冲核销

	public static String HCUNVERIFYFLAG = "HCUNVERIFYFLAG"; // 异币种红冲核销

	/**
	 * 收付内部拉单核销
	 * 
	 * @param mapvos
	 * @param ruleVOMap
	 * @param com
	 * @throws BusinessException
	 */
	private void doArapVerifyWithMap(Collection<ArapBillMapVO> mapvos, Hashtable<String, DefaultVerifyRuleVO> ruleVOMap,
			VerifyCom com) throws BusinessException {
		// 效率问题，改为批量处理
		if (mapvos != null && mapvos.size() > 0) {
			List<ArapBillMapVO> billMapDataArap = new ArrayList<ArapBillMapVO>();
			List<ArapBillMapVO> billMapDataUnRb = new ArrayList<ArapBillMapVO>();
			Map<String, List<ArapBillMapVO>> billMapDataUnSam = new HashMap<String, List<ArapBillMapVO>>();
			for (ArapBillMapVO vo : mapvos) {
				if (StringUtil.isEmpty(vo.getSettlecurr()) || vo.getSettlemoney() == null) {
					billMapDataArap.add(vo);
				} else {
					if (IBillFieldGet.F0.equals(vo.getS_billtype()) && IBillFieldGet.F3.equals(vo.getT_billtype())) { // 红字应收拉付款
						billMapDataArap.add(vo);
					} else if (vo.getS_billtype().equals(vo.getT_billtype())) {// 红冲
						billMapDataUnRb.add(vo);
					} else {
						if (vo.getPk_currtype().equals(vo.getSettlecurr())) {// 同币种
							billMapDataArap.add(vo);
						} else { // 异币种按照上游下游币种汇总
							String key = vo.getPk_currtype() + "*" + vo.getSettlecurr();
							if (billMapDataUnSam.get(key) != null) {
								billMapDataUnSam.get(key).add(vo);
							} else {
								List<ArapBillMapVO> map = new ArrayList<ArapBillMapVO>();
								map.add(vo);
								billMapDataUnSam.put(key, map);
							}
						}

					}
				}
			}
			if (billMapDataArap != null && billMapDataArap.size() > 0) {
				this.doVerifyWithMap(billMapDataArap, ruleVOMap, com);
			}
			if (billMapDataUnRb != null && billMapDataUnRb.size() > 0) {
				this.doArapVerifyWithMap(billMapDataUnRb, this.createRBVerifyRuleVO(),
						BillRegisterForBusiDataBO.HCUNVERIFYFLAG, com.getIsauto());
			}
			for (String key : billMapDataUnSam.keySet()) {
				this.doArapVerifyWithMap(billMapDataUnSam.get(key), null, BillRegisterForBusiDataBO.UNVERIFYFLAG,
						com.getIsauto());
			}
		}
	}

	/**
	 * @param mapvos      核销map
	 * @param ruleVOMap   核销规则
	 * @param isSamVerify 是否同币种
	 * @param isRed       是否红冲
	 * @throws BusinessException
	 */
	private void doArapVerifyWithMap(List<ArapBillMapVO> mapvos, Hashtable<String, DefaultVerifyRuleVO> ruleVOMap,
			String verifyFlag, UFBoolean isauto) throws BusinessException {
		if (mapvos == null || mapvos.size() == 0) {
			return;
		}
		this.aggMap.clear();
		VerifyCom com = new VerifyCom();
		com.setReserveFlag(VerifyDetailVO.reserve_arap);
		com.setExactVerify(true);
		Map<String, List<ArapBusiDataVO>> busiMap = new HashMap<String, List<ArapBusiDataVO>>();
		List<String> pks = new ArrayList<String>();
		List<String> termPkList = new ArrayList<String>();
		List<String> itemPkList = new ArrayList<String>();
		Collection<ArapBusiDataVO> busiList = null;
		Map<String, String> item_TermMap = new HashMap<String, String>();
		// 根据系统来源判断 是否来自付款申请
		for (ArapBillMapVO vo : mapvos) {
			if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(vo.getS_billtype())) {
				// 判断 只有资金的付款排成 才可以按协议行核销
				termPkList.add(vo.getS_termid());
				itemPkList.add(vo.getT_itemid());
			} else {
				if (vo.getS_itemid() == null) { // 源头id 为空 ，没有数据不用核销
				} else {
					pks.add(vo.getS_itemid());
					pks.add(vo.getT_itemid());
				}
			}
		}

		if (termPkList != null && termPkList.size() > 0) {
			String sql = SqlUtils.getInStr("pk_termitem", termPkList.toArray(new String[] {}), true)
					+ " and pausetransact ='N' " + " or "
					+ SqlUtils.getInStr("pk_item", itemPkList.toArray(new String[] {}), true);
			busiList = new BaseDAO().retrieveByClause(ArapBusiDataVO.class, sql);
		} else {
			if (pks != null && pks.size() > 0) {
				busiList = new BaseDAO().retrieveByClause(ArapBusiDataVO.class,
						SqlUtils.getInStr("pk_item", pks.toArray(new String[] {}), true) + " and money_bal <> 0 "
								+ " and pausetransact ='N' ");
			} else {
			}
		}
		if (busiList == null || busiList.size() == 0) {
			return;
		}

		// 比较ts 使用
		Map<String, String> busiDataTsMap = new HashMap<String, String>();
		for (ArapBusiDataVO vo : busiList) {
			busiDataTsMap.put(vo.getPk_busidata(), vo.getTs().toString());
		}
		com.setBusiDataTsMap(busiDataTsMap);

		// 以表体行分组
		for (ArapBusiDataVO bvo : busiList) {
			item_TermMap.put(bvo.getPk_termitem(), bvo.getPk_item());
			if (busiMap.containsKey(bvo.getPk_item())) {
				List<ArapBusiDataVO> list2 = busiMap.get(bvo.getPk_item());
				list2.add(bvo);
				busiMap.put(bvo.getPk_item(), list2);
			} else {
				List<ArapBusiDataVO> slist = new ArrayList<ArapBusiDataVO>();
				slist.add(bvo);
				busiMap.put(bvo.getPk_item(), slist);
			}
		}
		Map<String, ArrayList<AggverifyVO>> aggMap = null;

		List<ArapBusiDataVO> jf_vos_list = new ArrayList<ArapBusiDataVO>();
		List<ArapBusiDataVO> df_vos_list = new ArrayList<ArapBusiDataVO>();

		// 取下游单据日期
		UFDate busiDate = null;
		if (BillRegisterForBusiDataBO.UNVERIFYFLAG.equals(verifyFlag)) {
			busiDate = busiMap.get(mapvos.get(0).getT_itemid()).get(0).getBilldate();
			ruleVOMap = this.createUnVerifyRuleVO(mapvos.get(0), busiDate);
		}
		for (ArapBillMapVO vo : mapvos) {
			ArapBusiDataVO[] jf_vos = null;
			ArapBusiDataVO[] df_vos = null;

			ArapBusiDataVO[] jf_vostemp = null;
			ArapBusiDataVO[] df_vostemp = null;
			String sItemid = vo.getS_itemid();
			String tItemid = vo.getT_itemid();
			List<ArapBusiDataVO> slist = null;
			if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(vo.getS_billtype())) {
			} else {
				if (sItemid == null) {
					return;
				}
			}
			List<ArapBusiDataVO> tlist = null;
			// 付款排程
			if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(vo.getS_billtype())) {
				String stermid = vo.getS_termid();
				String titemid = vo.getT_itemid();
				// 根据源协议表id，获得源子表id
				String sitemid = item_TermMap.get(stermid);
				slist = busiMap.get(sitemid);
				tlist = busiMap.get(titemid);
			} else {
				slist = busiMap.get(sItemid);
				tlist = busiMap.get(tItemid);
			}

			if (com.isArapVerify()) {
				if (slist != null) {
					for (ArapBusiDataVO svo : slist) {
						svo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, svo.getPk_item());
					}
				}
				if (tlist != null) {
					for (ArapBusiDataVO tvo : tlist) {
						tvo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, tvo.getTop_itemid());
					}
				}
			}
			ArapBusiDataVOList svolist = new ArapBusiDataVOList(slist);
			ArapBusiDataVOList tvolist = new ArapBusiDataVOList(tlist);
			if (tvolist.getVolist() == null || tvolist.getVolist().size() == 0 || svolist.getVolist() == null
					|| svolist.getVolist().size() == 0) {
				return;
			} else {
				if (BillRegisterForBusiDataBO.SAMVERIFYFLAG.equals(verifyFlag)) {
					// 退货核销，红字应收单（负金额），付款单
					if (svolist.getVolist().get(0).getPk_billtype().equals(IBillFieldGet.F0)
							&& tvolist.getVolist().get(0).getPk_billtype().equals(IBillFieldGet.F3)) {
						svolist.setDealMoney(vo.getYbje().multiply(-1), com.isSoVerify(), aggMap);
						tvolist.setDealMoney(vo.getYbje(), com.isSoVerify(), aggMap);
					} else {
						svolist.setDealMoney(vo.getYbje(), com.isSoVerify(), aggMap);
						tvolist.setDealMoney(vo.getYbje(), com.isSoVerify(), aggMap);
					}
				} else if (BillRegisterForBusiDataBO.UNVERIFYFLAG.equals(verifyFlag)) {
					svolist.setUnDealMoney(vo, true, aggMap, busiDate);
					tvolist.setUnDealMoney(vo, false, aggMap, busiDate);
				} else if (BillRegisterForBusiDataBO.HCSAMVERIFYFLAG.equals(verifyFlag)) {
					svolist.setHcDealMoney(vo, true, aggMap);
					tvolist.setHcDealMoney(vo, false, aggMap);
				} else if (BillRegisterForBusiDataBO.HCUNVERIFYFLAG.equals(verifyFlag)) {
					svolist.setHcDealMoney(vo, true, aggMap);
					tvolist.setHcDealMoney(vo, false, aggMap);
				}
			}
			// 取财务组织，核销顺序参数时使用
			this.setPkorg(vo.getPk_org());
			// 判断借贷方
			if (this.isJie(svolist.getVolist())) {
				jf_vostemp = new ArapBusiDataVO[svolist.getVolist().size()];
				svolist.getVolist().toArray(jf_vostemp);

				df_vostemp = new ArapBusiDataVO[tvolist.getVolist().size()];
				tvolist.getVolist().toArray(df_vostemp);
			} else {
				df_vostemp = new ArapBusiDataVO[svolist.getVolist().size()];
				svolist.getVolist().toArray(df_vostemp);

				jf_vostemp = new ArapBusiDataVO[tvolist.getVolist().size()];
				tvolist.getVolist().toArray(jf_vostemp);
			}
			// 退货核销，特殊处理
			if (jf_vostemp[0].getPk_billtype().equals(IBillFieldGet.F0)
					&& df_vostemp[0].getPk_billtype().equals(IBillFieldGet.F3)) {
				jf_vos = ArrayUtil.union(jf_vos, jf_vostemp);
				jf_vos = ArrayUtil.union(jf_vos, df_vostemp);
				com.setRedContrast(true);
			} else {

				jf_vos = ArrayUtil.union(jf_vos, jf_vostemp);
				df_vos = ArrayUtil.union(df_vos, df_vostemp);
			}

			if (jf_vos != null) {
				for (ArapBusiDataVO jfvo : jf_vos) {
					jf_vos_list.add(jfvo);
				}
			}
			if (df_vos != null) {
				for (ArapBusiDataVO dfvo : df_vos) {
					df_vos_list.add(dfvo);
				}
			}
			if (BillRegisterForBusiDataBO.HCSAMVERIFYFLAG.equals(verifyFlag)
					|| BillRegisterForBusiDataBO.HCUNVERIFYFLAG.equals(verifyFlag)) {
				if (this.isJie(svolist.getVolist())) {
					jf_vos_list.addAll(df_vos_list);
					df_vos_list.clear();
				} else {
					df_vos_list.addAll(jf_vos_list);
					jf_vos_list.clear();
				}
			}
		}

		if (com.isArapVerify()) {// 合并为批量处理
			aggMap = this.onVerify(com, ruleVOMap, jf_vos_list.toArray(new ArapBusiDataVO[] {}),
					df_vos_list.toArray(new ArapBusiDataVO[] {}));
		}

		ArrayList<AggverifyVO> aggVOList = this.getAggVerifyVO(aggMap, isauto);

		if (aggVOList != null && aggVOList.size() > 0) {
			for (AggverifyVO v : aggVOList) {
				VerifyCom.validate(v);
			}
		}

		this.dealOrgScomment(aggVOList);
		// 核销结果保存
		if (aggVOList != null && aggVOList.size() > 0) {
			NCLocator.getInstance().lookup(IArapVerifyLogPrivate.class).save(aggVOList, ruleVOMap, com);
		}
	}

	private void dealOrgScomment(ArrayList<AggverifyVO> aggVOList) {
		for (AggverifyVO aggVO : aggVOList) {
			VerifyDetailVO[] childrenVO = (VerifyDetailVO[]) aggVO.getChildrenVO();
			for (VerifyDetailVO verifyvo : childrenVO) {
				// 代收代付摘要
				if (!StringUtil.isEmpty(verifyvo.getSrc_org()) && !verifyvo.getPk_org().equals(verifyvo.getSrc_org())) {
					IGeneralAccessor accessor = GeneralAccessorFactory
							.getAccessor("2cfe13c5-9757-4ae8-9327-f5c2d34bcb46");
					IBDData docByPk = accessor.getDocByPk(verifyvo.getSrc_org());
					String orgName = "";
					if (docByPk != null) {
						orgName = docByPk.getName().toString();
					}
					if (IBillFieldGet.F0.equals(verifyvo.getPk_billtype())
							|| IBillFieldGet.F2.equals(verifyvo.getPk_billtype())) {
						verifyvo.setScomment(verifyvo.getScomment() + " "
								+ nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006pub0322_0",
										"02006pub0322-0033", null, new String[] { orgName })/*
																							 * @ res "代收："
																							 */);
					} else {
						verifyvo.setScomment(verifyvo.getScomment() + " "
								+ nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2006pub0322_0",
										"02006pub0322-0034", null, new String[] { orgName })/*
																							 * @ res "代付："
																							 */);
					}
				}
			}
		}
	}

	private void doVerifyWithMap(Collection<ArapBillMapVO> mapvos, Hashtable<String, DefaultVerifyRuleVO> ruleVOMap,
			VerifyCom com) throws BusinessException {
		if (mapvos == null || mapvos.size() == 0) {
			return;
		}
		this.aggMap.clear();
		Map<String, List<ArapBusiDataVO>> busiMap = new HashMap<String, List<ArapBusiDataVO>>();
		List<String> pks = new ArrayList<String>();
		List<String> termPkList = new ArrayList<String>();
		List<String> itemPkList = new ArrayList<String>();
		Collection<ArapBusiDataVO> busiList = null;
		Map<String, String> item_TermMap = new HashMap<String, String>();
		Map<String, String> tItem_sItemMap = new HashMap<String, String>();
		// 调试是 注释 再打开
		for (ArapBillMapVO vo : mapvos) {
			// 根据系统来源判断 是否来自付款申请
			if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(vo.getS_billtype())) {
				// 判断 只有资金的付款排成 才可以按协议行核销
				termPkList.add(vo.getS_termid());
				itemPkList.add(vo.getT_itemid());
			} else {
				if (vo.getS_itemid() == null) { // 源头id 为空 ，没有数据不用核销
				} else {
					pks.add(vo.getS_itemid());
					pks.add(vo.getT_itemid());
					tItem_sItemMap.put(vo.getT_itemid(), vo.getS_itemid());
				}
			}
		}

		// 根据参数确定是否要按照预收付标志核销
		if (VerifyDetailVO.reserve_so.equals(com.getReserveFlag())) {
			UFBoolean isNeed = SysInit.getParaBoolean(this.getPkorg(), SysinitConst.AR35);
			if (isNeed != null && isNeed.booleanValue()) {
				for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
					rule.setM_creditObjKeys(new String[] { IArapItemFieldVO.PREPAY });
					rule.setM_debtObjKeys(new String[] { IArapItemFieldVO.PREPAY });
				}
			}
		} else if (VerifyDetailVO.reserve_pu.equals(com.getReserveFlag())) {
			UFBoolean isNeed = SysInit.getParaBoolean(this.getPkorg(), SysinitConst.AP35);
			if (isNeed != null && isNeed.booleanValue()) {
				for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
					rule.setM_creditObjKeys(new String[] { IArapItemFieldVO.PREPAY });
					rule.setM_debtObjKeys(new String[] { IArapItemFieldVO.PREPAY });
				}
			}
		} else if (VerifyDetailVO.reserve_pcm.equals(com.getReserveFlag())) {
			UFBoolean isNeed = SysInit.getParaBoolean(this.getPkorg(), SysinitConst.AP35);// 应付
			if (mapvos.iterator().next().getS_system() == 0) {// 应收
				isNeed = SysInit.getParaBoolean(this.getPkorg(), SysinitConst.AR35);
			}
			if (isNeed != null && isNeed.booleanValue()) {
				for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
					rule.setM_creditObjKeys(new String[] { IArapItemFieldVO.PREPAY });
					rule.setM_debtObjKeys(new String[] { IArapItemFieldVO.PREPAY });
				}
			}
		}

		if (termPkList != null && termPkList.size() > 0) {
			String sql = SqlUtils.getInStr("pk_termitem", termPkList.toArray(new String[] {}), true)
					+ " and pausetransact ='N' " + " or "
					+ SqlUtils.getInStr("pk_item", itemPkList.toArray(new String[] {}), true);
			busiList = new BaseDAO().retrieveByClause(ArapBusiDataVO.class, sql);
		} else {
			if (pks != null && pks.size() > 0) {
				busiList = new BaseDAO().retrieveByClause(ArapBusiDataVO.class,
						SqlUtils.getInStr("pk_item", pks.toArray(new String[] {}), true) + " and money_bal <> 0 "
								+ " and pausetransact ='N' ");
			} else {
			}
		}

		if (busiList == null || busiList.size() == 0) {
			return;
		}

		// 比较ts 使用
		Map<String, String> busiDataTsMap = new HashMap<String, String>();
		for (ArapBusiDataVO vo : busiList) {
			busiDataTsMap.put(vo.getPk_busidata(), vo.getTs().toString());
		}
		com.setBusiDataTsMap(busiDataTsMap);

		// 以表体行分组
		for (ArapBusiDataVO bvo : busiList) {
			item_TermMap.put(bvo.getPk_termitem(), bvo.getPk_item());
			if (busiMap.containsKey(bvo.getPk_item())) {
				List<ArapBusiDataVO> list2 = busiMap.get(bvo.getPk_item());
				list2.add(bvo);
				busiMap.put(bvo.getPk_item(), list2);
			} else {
				List<ArapBusiDataVO> slist = new ArrayList<ArapBusiDataVO>();
				slist.add(bvo);
				busiMap.put(bvo.getPk_item(), slist);
			}
		}
		Map<String, ArrayList<AggverifyVO>> aggMap = null;

		List<ArapBusiDataVO> jf_vos_list = new ArrayList<ArapBusiDataVO>();
		List<ArapBusiDataVO> df_vos_list = new ArrayList<ArapBusiDataVO>();

		for (ArapBillMapVO vo : mapvos) {
			ArapBusiDataVO[] jf_vos = null;
			ArapBusiDataVO[] df_vos = null;

			ArapBusiDataVO[] jf_vostemp = null;
			ArapBusiDataVO[] df_vostemp = null;
			String sItemid = vo.getS_itemid();
			String tItemid = vo.getT_itemid();
			List<ArapBusiDataVO> slist = null;
			if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(vo.getS_billtype())) {
			} else {
				if (sItemid == null) {
					continue;
				}
			}
			List<ArapBusiDataVO> tlist = null;
			// 付款排程
			if (ArapBillDealVOConsts.BILLTYPE_36D1.equals(vo.getS_billtype())) {
				String stermid = vo.getS_termid();
				String titemid = vo.getT_itemid();
				// 根据源协议表id，获得源子表id
				String sitemid = item_TermMap.get(stermid);
				slist = busiMap.get(sitemid);
				tlist = busiMap.get(titemid);
			} else {
				slist = busiMap.get(sItemid);
				tlist = busiMap.get(tItemid);
			}

			if (com.isArapVerify()) {
				if (slist != null) {
					for (ArapBusiDataVO svo : slist) {
						svo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, svo.getPk_item());
					}
				}
				if (tlist != null) {
					if (com.isRefund()) {
						for (ArapBusiDataVO tvo : tlist) {
							tvo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY,
									tItem_sItemMap.get(tvo.getPk_item()));
						}
					} else {
						for (ArapBusiDataVO tvo : tlist) {
							tvo.setAttributeValue(BillRegisterForBusiDataBO.SPECIAL_KEY, tvo.getTop_itemid());
						}
					}
				}
			}

			ArapBusiDataVOList svolist = new ArapBusiDataVOList(slist);
			ArapBusiDataVOList tvolist = new ArapBusiDataVOList(tlist);
			if (tvolist.getVolist() == null || tvolist.getVolist().size() == 0 || svolist.getVolist() == null
					|| svolist.getVolist().size() == 0) {
				continue;
			} else {
				// 退货核销，红字应收单（负金额），付款单
				if (svolist.getVolist().get(0).getPk_billtype().equals(IBillFieldGet.F0)
						&& tvolist.getVolist().get(0).getPk_billtype().equals(IBillFieldGet.F3)) {
					svolist.setDealMoney(vo.getYbje().multiply(-1), com.isSoVerify(), aggMap);
					tvolist.setDealMoney(vo.getYbje(), com.isSoVerify(), aggMap);
				} else {
					svolist.setDealMoney(vo.getYbje(), com.isSoVerify(), aggMap, com.getReserveFlag());
					tvolist.setDealMoney(vo.getYbje(), com.isSoVerify(), aggMap, com.getReserveFlag());
				}
			}
			// 取财务组织，核销顺序参数时使用
			this.setPkorg(vo.getPk_org());
			// 判断借贷方
			if (this.isJie(svolist.getVolist())) {
				jf_vostemp = new ArapBusiDataVO[svolist.getVolist().size()];
				svolist.getVolist().toArray(jf_vostemp);

				df_vostemp = new ArapBusiDataVO[tvolist.getVolist().size()];
				tvolist.getVolist().toArray(df_vostemp);
			} else {
				df_vostemp = new ArapBusiDataVO[svolist.getVolist().size()];
				svolist.getVolist().toArray(df_vostemp);

				jf_vostemp = new ArapBusiDataVO[tvolist.getVolist().size()];
				tvolist.getVolist().toArray(jf_vostemp);
			}
			// 退货核销，特殊处理
			if (jf_vostemp[0].getPk_billtype().equals(IBillFieldGet.F0)
					&& df_vostemp[0].getPk_billtype().equals(IBillFieldGet.F3)) {
				jf_vos = ArrayUtil.union(jf_vos, jf_vostemp);
				jf_vos = ArrayUtil.union(jf_vos, df_vostemp);
				com.setRedContrast(true);
			} else {

				jf_vos = ArrayUtil.union(jf_vos, jf_vostemp);
				df_vos = ArrayUtil.union(df_vos, df_vostemp);
			}

			if (!com.isArapVerify() && com.getReserveFlag().intValue() != VerifyDetailVO.reserve_pcm) {
				aggMap = this.onVerify(com, ruleVOMap, jf_vos, df_vos);
				// for(ArapBusiDataVO v:jf_vos){
				// v.setAttributeValue("SETT_MONEY", null);
				// }
				// for(ArapBusiDataVO v:df_vos){
				// v.setAttributeValue("SETT_MONEY", null);
				// }
			} else {
				if (jf_vos != null) {
					for (ArapBusiDataVO jfvo : jf_vos) {
						jf_vos_list.add(jfvo);
					}
				}
				if (df_vos != null) {
					for (ArapBusiDataVO dfvo : df_vos) {
						df_vos_list.add(dfvo);
					}
				}
			}
		}

		if (com.isArapVerify() || com.getReserveFlag().intValue() == VerifyDetailVO.reserve_pcm) {// 合并为批量处理
			aggMap = this.onVerify(com, ruleVOMap, jf_vos_list.toArray(new ArapBusiDataVO[] {}),
					df_vos_list.toArray(new ArapBusiDataVO[] {}));
		}

		ArrayList<AggverifyVO> aggVOList = this.getAggVerifyVO(aggMap, com.getIsauto());
		this.dealOrgScomment(aggVOList);
		// 核销结果保存
		if (aggVOList != null && aggVOList.size() > 0) {
			NCLocator.getInstance().lookup(IArapVerifyLogPrivate.class).save(aggVOList, ruleVOMap, com);
		}
	}

	private Map<String, ArrayList<AggverifyVO>> onVerify(VerifyCom com, Map<String, DefaultVerifyRuleVO> ruleVOMap,
			ArapBusiDataVO[] jf_vos, ArapBusiDataVO[] df_vos) throws BusinessException {

		// 自动核销 只有红蓝对冲，同币种核销

		com.setM_creditSelected(df_vos);
		com.setM_debitSelected(jf_vos);
		AggverifyVO aggvo = null;
		if (!ArrayUtils.isEmpty(jf_vos) || !ArrayUtils.isEmpty(df_vos)) {
			if (!ArrayUtils.isEmpty(jf_vos)) {
				SagasUtils.frozenAndAddSaga(SagasUtils.OTHER, jf_vos, IBillFieldGet.BILLNO, jf_vos[0].getPk_billtype());
			}
			if (!ArrayUtils.isEmpty(df_vos)) {
				SagasUtils.frozenAndAddSaga(SagasUtils.OTHER, df_vos, IBillFieldGet.BILLNO, df_vos[0].getPk_billtype());
			}

			for (String key : ruleVOMap.keySet()) {
				if (ArrayUtils.isEmpty(jf_vos) || ArrayUtils.isEmpty(df_vos)) {
					if (key.equals("SAME_VERIFY")) {
						continue;
					}
				} else {
					String billclass = jf_vos[0].getBillclass();
					String billclass2 = df_vos[0].getBillclass();

					if (billclass.equals(IBillFieldGet.YS) && billclass2.equals(IBillFieldGet.FK)
							|| billclass.equals(IBillFieldGet.FK) && billclass2.equals(IBillFieldGet.YS)) {
						if (key.equals("SAME_VERIFY") || key.equals("UNSAME_VERIFY")) {
							continue;
						}
					}
					if (billclass.equals(IBillFieldGet.YS) && billclass2.equals(IBillFieldGet.SK)
							|| billclass.equals(IBillFieldGet.SK) && billclass2.equals(IBillFieldGet.YS)
							|| billclass.equals(IBillFieldGet.YF) && billclass2.equals(IBillFieldGet.FK)
							|| billclass.equals(IBillFieldGet.FK) && billclass2.equals(IBillFieldGet.YF)) {
						if (key.equals("RB_VERIFY")) {
							continue;
						}
					}
				}

				DefaultVerifyRuleVO rulevo = ruleVOMap.get(key);
				if (key.equals("SAME_VERIFY")) {

					SameMnyVerify smverify = new SameMnyVerify(com);
					aggvo = smverify.onVerify(jf_vos, df_vos, rulevo);
					if (aggvo == null) {
						continue;
					}
					if (!ArrayUtils.isEmpty(aggvo.getChildrenVO())) {
						if (this.aggMap.containsKey("SAME_VERIFY")) {
							this.aggMap.get(key).add(aggvo);
						} else {
							ArrayList<AggverifyVO> temp = new ArrayList<AggverifyVO>();
							temp.add(aggvo);
							this.aggMap.put("SAME_VERIFY", temp);
						}
					}
				} else if (key.equals("RB_VERIFY")) {
					RBVerify rbverify = new RBVerify(com);
					aggvo = rbverify.onVerify(jf_vos, df_vos, rulevo);
					if (!ArrayUtils.isEmpty(aggvo.getChildrenVO())) {
						if (this.aggMap.containsKey("RB_VERIFY")) {
							this.aggMap.get(key).add(aggvo);
						} else {
							ArrayList<AggverifyVO> temp = new ArrayList<AggverifyVO>();
							temp.add(aggvo);
							this.aggMap.put("RB_VERIFY", temp);
						}
					}
				} else if (key.equals("UNSAME_VERIFY")) {
					UnsameMnyVerify unsameMnyVerify = new UnsameMnyVerify(com);
					aggvo = unsameMnyVerify.onVerify(jf_vos, df_vos, rulevo);
					if (!ArrayUtils.isEmpty(aggvo.getChildrenVO())) {
						if (this.aggMap.containsKey("UNSAME_VERIFY")) {
							this.aggMap.get(key).add(aggvo);
						} else {
							ArrayList<AggverifyVO> temp = new ArrayList<AggverifyVO>();
							temp.add(aggvo);
							this.aggMap.put("UNSAME_VERIFY", temp);
						}

					}
				}

			}
		}

		return this.aggMap;

	}

	@SuppressWarnings("rawtypes")
	private ArrayList<AggverifyVO> getAggVerifyVO(Map<String, ArrayList<AggverifyVO>> aggMap, UFBoolean isauto)
			throws BusinessException {
		List<VerifyDetailVO> detailVOList = new ArrayList<VerifyDetailVO>();
		ArrayList resultList = new ArrayList();
		if (aggMap == null) {
			return resultList;
		}
		for (String key : aggMap.keySet()) {
			detailVOList.clear();
			ArrayList<AggverifyVO> arrayList = aggMap.get(key);
			if (arrayList != null) {
				for (AggverifyVO aggVO : arrayList) {
					VerifyDetailVO[] childrenVO = (VerifyDetailVO[]) aggVO.getChildrenVO();
					// 审核后自动核销，设置标志位 核销记录查询不出来
					for (VerifyDetailVO verifyvo : childrenVO) {
						verifyvo.setIsauto(isauto);
						detailVOList.add(verifyvo);
					}
				}
				// 组织聚合vo
				AggverifyVO aggVO = new AggverifyVO();
				aggVO.setChildrenVO(detailVOList.toArray(new VerifyDetailVO[0]));
				// 计算全局 集团本位币
				VerifyCom.calGroupAndGloablMny(aggVO);
				ArrayList<AggverifyVO> aggvolist = (ArrayList) VerifyCom.verifySumData(aggVO);

				resultList.addAll(aggvolist);
			}
		}
		return resultList;
	}

	/**
	 * 异币种核销规则
	 * 
	 * @param vo
	 * @param busiDate 取下游单据日期所对应的汇率。
	 * @return
	 * @throws BusinessException
	 */
	private Hashtable<String, DefaultVerifyRuleVO> createUnVerifyRuleVO(ArapBillMapVO vo, UFDate busiDate)
			throws BusinessException {
		Hashtable<String, DefaultVerifyRuleVO> ruleMap = new Hashtable<String, DefaultVerifyRuleVO>();
		DefaultVerifyRuleVO rulevo = this.getVerifyRuleVO();
		rulevo.setM_verifyName("UNSAME_VERIFY");
		// 是否跨组织 跨组织中币取集团本币，否则取组织本币
		String pk_group = InvocationInfoProxy.getInstance().getGroupId();
		String pk_org = InvocationInfoProxy.getInstance().getGroupId();
		if (vo.getPk_org().equals(vo.getPk_org1())) {
			pk_org = vo.getPk_org();
		}
		String verifyCurr = CurrencyRateUtilHelper.getInstance().getLocalCurrtypeByOrgID(pk_org);
		rulevo.setM_verifyCurr(verifyCurr);
		// UFDate busiDate =new
		// UFDate(InvocationInfoProxy.getInstance().getBizDateTime());
		// 判断来源单据是否借方
		if (IBillFieldGet.F2.equals(vo.getS_billtype()) || IBillFieldGet.F1.equals(vo.getS_billtype())) {
			// 借方币种、汇率
			int rateType = ArapBillCalUtil.getRateType(vo.getT_billtype(), pk_group);
			rulevo.setM_debitCurr(vo.getPk_currtype());
			rulevo.setM_jfbz2zjbzHL(Currency.getRate(pk_org, vo.getPk_currtype(), verifyCurr, busiDate, rateType));
			rulevo.setM_debttoBBExchange_rate(
					Currency.getRate(vo.getPk_org(), vo.getPk_currtype(), busiDate, rateType));
			// 贷方币种。汇率
			int rateType1 = ArapBillCalUtil.getRateType(vo.getS_billtype(), pk_group);
			rulevo.setM_creditCurr(vo.getSettlecurr());
			rulevo.setM_dfbz2zjbzHL(Currency.getRate(pk_org, vo.getSettlecurr(), verifyCurr, busiDate, rateType1));
			rulevo.setM_creditoBBExchange_rate(
					Currency.getRate(vo.getPk_org1(), vo.getSettlecurr(), busiDate, rateType1));
		} else {
			// 借方币种、汇率
			int rateType = ArapBillCalUtil.getRateType(vo.getS_billtype(), pk_group);
			rulevo.setM_debitCurr(vo.getSettlecurr());
			rulevo.setM_jfbz2zjbzHL(Currency.getRate(pk_org, vo.getSettlecurr(), verifyCurr, busiDate, rateType));
			rulevo.setM_debttoBBExchange_rate(
					Currency.getRate(vo.getPk_org1(), vo.getSettlecurr(), busiDate, rateType));

			// 贷方币种。汇率
			int rateType1 = ArapBillCalUtil.getRateType(vo.getT_billtype(), pk_group);
			rulevo.setM_creditCurr(vo.getPk_currtype());
			rulevo.setM_dfbz2zjbzHL(Currency.getRate(pk_org, vo.getPk_currtype(), verifyCurr, busiDate, rateType1));
			rulevo.setM_creditoBBExchange_rate(
					Currency.getRate(vo.getPk_org(), vo.getPk_currtype(), busiDate, rateType1));
		}
		ruleMap.put("UNSAME_VERIFY", rulevo);
		return ruleMap;
	}

	private Hashtable<String, DefaultVerifyRuleVO> createRBVerifyRuleVO() {
		Hashtable<String, DefaultVerifyRuleVO> ruleMap = new Hashtable<String, DefaultVerifyRuleVO>();
		DefaultVerifyRuleVO rulevo = this.getVerifyRuleVO();
		rulevo.setM_verifyName("RB_VERIFY");
		ruleMap.put("RB_VERIFY", rulevo);
		return ruleMap;
	}

	// private Hashtable<String, DefaultVerifyRuleVO> createVerifyRuleVO() {
	// Hashtable<String, DefaultVerifyRuleVO> ruleMap =
	// new Hashtable<String, DefaultVerifyRuleVO>();
	// DefaultVerifyRuleVO rulevo = this.getVerifyRuleVO();
	// rulevo.setM_verifyName("SAME_VERIFY");
	// ruleMap.put("SAME_VERIFY", rulevo);
	// return ruleMap;
	// }

	private DefaultVerifyRuleVO getVerifyRuleVO() {
		DefaultVerifyRuleVO rulevo = new DefaultVerifyRuleVO();
		Integer m_hxSeq = Integer.valueOf(0);
		// UFDateTime busidate = null;
		try {
			// busidate =
			// NCLocator.getInstance().lookup(IServerEnvironmentService.class)
			// .getServerTime();
			String hxSeq = "";
			if (this.getSyscode() == 0) {
				hxSeq = SysinitAccessor.getInstance().getParaString(this.getPkorg(), "AR1");
			} else {
				hxSeq = SysinitAccessor.getInstance().getParaString(this.getPkorg(), "AP1");
			}
			if (SysinitConst.VERIFY_ZAO.equals(hxSeq)) {
				m_hxSeq = Integer.valueOf(0);
			} else {
				m_hxSeq = Integer.valueOf(1);
			}

		} catch (Exception e) {
			ExceptionHandler.consume(e);
		}
		rulevo.setM_verifySeq(m_hxSeq);
		UFDate clrq = new UFDate(InvocationInfoProxy.getInstance().getBizDateTime());
		rulevo.setM_Clrq(clrq);
		AccountCalendar ac = AccountCalendar.getInstanceByPk_org(this.getPkorg());
		try {
			ac.setDate(clrq);
		} catch (InvalidAccperiodExcetion e) {
			ExceptionHandler.consume(e);
		}
		rulevo.setSystem(this.getSyscode());
		rulevo.setPk_org(this.getPkorg());
		rulevo.setM_Clnd(ac.getYearVO().getPeriodyear());
		rulevo.setM_Clqj(ac.getMonthVO().getAccperiodmth());
		rulevo.setIsOccuption(true);
		rulevo.setM_clr(this.getPk_user());
		return rulevo;
	}

	private Hashtable<String, DefaultVerifyRuleVO> creatVerifyRuleVO() {

		Hashtable<String, DefaultVerifyRuleVO> ruleMap = new Hashtable<String, DefaultVerifyRuleVO>();
		DefaultVerifyRuleVO rulevo = this.getVerifyRuleVO();
		rulevo.setM_verifyName("SAME_VERIFY");
		DefaultVerifyRuleVO rbrulevo = (DefaultVerifyRuleVO) rulevo.clone();
		rbrulevo.setM_verifyName("RB_VERIFY");
		ruleMap.put("SAME_VERIFY", rulevo);
		ruleMap.put("RB_VERIFY", rbrulevo);

		return ruleMap;
	}

	private boolean isJie(List<ArapBusiDataVO> listvo) {
		for (ArapBusiDataVO vo : listvo) {
			if (vo == null) {
				return false;
			}
			Integer int_fx = (Integer) vo.getAttributeValue(ArapBusiDataVO.DIRECTION);
			if (int_fx == null) {
				return false;
			}

			int fx = int_fx.intValue();

			return fx == 1;

		}
		return false;
	}

	/**
	 * @author 符耀铭
	 * @time 2019-5-15
	 * @param MapVOList
	 * @param com
	 * @param ruleVOMap
	 * @description 二开新加的方法,根据明源GUID核销物业付款单和应付单
	 */
	private void VerifyByGuid(AggregatedValueObject[] vos, VerifyCom com,
			Hashtable<String, DefaultVerifyRuleVO> ruleVOMap) {
		try {
			CircularlyAccessibleValueObject headValueObject = vos[0].getParentVO();
			Object pk_tradetype = headValueObject.getAttributeValue("pk_tradetype");
			List<String> pk_itemList = new ArrayList<String>();
			Object guid = null;
			String qryitemsql = "";

			UFBoolean iszhibaojin = UFBoolean.FALSE;
			if ("F3-Cxx-W01".equals(pk_tradetype)) {
				// def70是否质保金付款def8
				iszhibaojin = vos[0].getParentVO().getAttributeValue("def8") == null ? UFBoolean.FALSE
						: new UFBoolean(vos[0].getParentVO().getAttributeValue("def8").toString());
			} else {
				// def109是否含质保金付款def14
				iszhibaojin = vos[0].getParentVO().getAttributeValue("def14") == null ? UFBoolean.FALSE
						: new UFBoolean(vos[0].getParentVO().getAttributeValue("def14").toString());
			}

			if ("F3-Cxx-W01".equals(pk_tradetype)) {
				// def59 是否有票 def3
				Object def3 = headValueObject.getAttributeValue("def3");

				UFBoolean isticketpay = null == def3 ? UFBoolean.FALSE : new UFBoolean(def3.toString());

				if (!isticketpay.booleanValue() && iszhibaojin.booleanValue()) {
					// def73对应应付单guid def11
					guid = headValueObject.getAttributeValue("def11");
					qryitemsql = "select pah.pk_payablebill\n" + "  from ap_payablebill pah\n" + " where pah.def1 = '"
							+ guid + "'\n" + "   and nvl(pah.dr, 0) = 0\n" + "  and pah.def14='Y'\n";
				}
			} else if ("F1-Cxx-W01".equals(pk_tradetype) || "F1-Cxx-W02".equals(pk_tradetype)) {
				guid = headValueObject.getAttributeValue("def1");
				// def95 是否有票付款 def3
				Object def3 = headValueObject.getAttributeValue("def3");

				UFBoolean isticketpay = null == def3 ? UFBoolean.FALSE : new UFBoolean(def3.toString());

				if (isticketpay.booleanValue() && iszhibaojin.booleanValue()) {
					qryitemsql = "select p.pk_paybill\n" + "  from ap_paybill p\n" + " where p.def11 = '" + guid + "'\n"
							+ "   and nvl(p.dr, 0) = 0\n" + "  and p.def8='Y'\n";
				} else {
					// def60 明源GUID def1
					qryitemsql = "select p.pk_paybill\n" + "  from ap_paybill p\n" + " where p.def1 = '" + guid + "'\n"
							+ "   and nvl(p.dr, 0) = 0 \n" + "  and nvl(p.def3,'N')='N'";
				}
			} else {
				return;
			}
			pk_itemList.add(headValueObject.getPrimaryKey());

			if (qryitemsql == "") {
				return;
			}

			List<String> list = (List<String>) new BaseDAO().executeQuery(qryitemsql, new ColumnListProcessor());
			nc.vo.tmpub.util.ArrayUtil.addListToList(pk_itemList, list);

			String qrySql = new StringBuilder("money_bal <> 0 and pk_bill in ("
					+ SqlUtil.buildSqlConditionForIn(pk_itemList.toArray(new String[0])) + ")").toString();
			Map<String, String> busiDataTsMap = new HashMap<String, String>();
			List<ArapBusiDataVO> dataList = new ArrayList<ArapBusiDataVO>();
			List<ArapBusiDataVO> jfdataList = new ArrayList<ArapBusiDataVO>();
			List<ArapBusiDataVO> dfdataList = new ArrayList<ArapBusiDataVO>();
			NCObject[] ncObjects = MDPersistenceService.lookupPersistenceQueryService()
					.queryBillOfNCObjectByCond(ArapBusiDataVO.class, qrySql, false);
			if (!ArrayUtils.isEmpty(ncObjects)) {
				for (DefaultVerifyRuleVO rule : ruleVOMap.values()) {
					rule.setM_creditObjKeys(new String[] { ArapBusiDataVO.DEF1,ArapBusiDataVO.DEF19});//明源GUID和表体分摊期间做为核销的条件
					rule.setM_debtObjKeys(new String[] { ArapBusiDataVO.DEF1,ArapBusiDataVO.DEF25});//明源GUID和表体分摊期间做为核销的条件
				}
				for (NCObject obj : ncObjects) {
					ArapBusiDataVO dataVO = (ArapBusiDataVO) obj.getContainmentObject();
					dataList.add(dataVO);
					// 比较ts 使用
					busiDataTsMap.put(dataVO.getPk_busidata(), dataVO.getTs().toString());
					com.setBusiDataTsMap(busiDataTsMap);
				}
				// 借贷方分组
				for (ArapBusiDataVO datavo : dataList) {
					datavo.setAttributeValue(ArapBusiDataVO.SETT_MONEY, datavo.getOccupationmny());// 这里要设置结算金额,不然后面无法核销

					if (datavo.getCustomer() != null && datavo.getSupplier() == null) {
						datavo.setSupplier(datavo.getCustomer());
					}

					if (datavo.getDirection().intValue() == 1) {
						jfdataList.add(datavo);
						datavo.setDef1(guid.toString());// 通过应付单的pk进行绑定应付单和付款单
						datavo.setAttributeValue("SETT_MONEY", datavo.getMoney_bal());
					} else {
						dfdataList.add(datavo);
						datavo.setDef1(guid.toString());
						datavo.setAttributeValue("SETT_MONEY", datavo.getMoney_bal());
					}
				}
				Map<String, ArrayList<AggverifyVO>> aggMap = onVerify(com, ruleVOMap,
						jfdataList.toArray(new ArapBusiDataVO[0]), dfdataList.toArray(new ArapBusiDataVO[0]));
				ArrayList<AggverifyVO> aggVOList = getAggVerifyVO(aggMap);
				// 核销结果保存
				if (aggVOList != null && aggVOList.size() > 0) {
					NCLocator.getInstance().lookup(IArapVerifyLogPrivate.class).save(aggVOList, ruleVOMap, com);
				}
			}
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
	}

	private ArrayList<AggverifyVO> getAggVerifyVO(Map<String, ArrayList<AggverifyVO>> aggMap) throws BusinessException {
		ArrayList resultList = new ArrayList();
		if (aggMap == null) {
			return resultList;
		}
		for (String key : aggMap.keySet()) {
			List<VerifyDetailVO> detailVOList = new ArrayList<VerifyDetailVO>();
			ArrayList<AggverifyVO> arrayList = aggMap.get(key);
			if (arrayList != null) {
				for (AggverifyVO aggVO : arrayList) {
					VerifyDetailVO[] childrenVO = (VerifyDetailVO[]) aggVO.getChildrenVO();
					// 审核后自动核销，设置标志位 核销记录查询不出来
					for (VerifyDetailVO verifyvo : childrenVO) {
						verifyvo.setIsauto(UFBoolean.TRUE);
						detailVOList.add(verifyvo);
					}
				}
				// 组织聚合vo
				AggverifyVO aggVO = new AggverifyVO();
				aggVO.setChildrenVO(detailVOList.toArray(new VerifyDetailVO[0]));
				// 计算全局 集团本位币
				VerifyCom.calGroupAndGloablMny(aggVO);
				ArrayList<AggverifyVO> aggvolist = (ArrayList) VerifyCom.verifySumData(aggVO);

				resultList.addAll(aggvolist);
			}
		}
		return resultList;
	}
}

//nslGwwQRyySTBqdb6vgDeTX2flneCaaVP7NIdF4lqqHYeWcjsCkAJ3zO1zqNoOHrDD/sz60Weax087NE4mI8NA==