//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package nccloud.impl.fbm.gather.excel;

import java.util.Collection;
import java.util.HashMap;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.sec.esapi.NCESAPI;
import nc.itf.bd.bankdoc.IBankdocQueryService;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.pubitf.bd.accessor.GeneralAccessorFactory;
import nc.pubitf.bd.accessor.IGeneralAccessor;
import nc.vo.bd.accessor.IBDData;
import nc.vo.bd.accessor.bankaccsub.BankaccSubAccessorFactory;
import nc.vo.bd.accessor.bankaccsub.BankaccSubGeneralAccessor;
import nc.vo.bd.bankaccount.BankAccbasVO;
import nc.vo.bd.bankdoc.BankdocVO;
import nc.vo.bd.cust.CustSupplierVersionVO;
import nc.vo.fbm.pub.action.ActionVO;
import nc.vo.fbm.pub.util.FbmCommonTools;
import nc.vo.fbm.pub.util.FbmPublicUtil;
import nc.vo.fbm.register.AggRegisterVO;
import nc.vo.fbm.register.RegisterVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.tmpub.util.StringUtil;
import nc.vo.tmpub.util.TMCustSupUtil;
import nc.vo.tmpub.validator.ExcelImportUtil;
import nc.vo.trade.pub.HYBillVO;
import nc.vo.uap.pf.PFBatchExceptionInfo;
import nc.vo.uap.pf.PfProcessBatchRetObject;
import nccloud.bs.excel.IXChangeContext;
import nccloud.bs.excel.plugin.AbstractImportProceeWithContext;
import nccloud.pubitf.riart.pflow.CloudPFlowContext;
import nccloud.pubitf.riart.pflow.ICloudScriptPFlowService;

public class GatherExcelImport4NCCImpl extends AbstractImportProceeWithContext {
	public GatherExcelImport4NCCImpl() {
	}

	protected void processBillWithContext(Object vo, IXChangeContext changcontext) throws BusinessException {
		CircularlyAccessibleValueObject regvo = ((HYBillVO) vo).getParentVO();
		AggRegisterVO aggvo = new AggRegisterVO();
		aggvo.setParentVO(regvo);
		this.check(aggvo);
		Object[] results = this.doSave(aggvo);
		Object[] var6 = results;
		int var7 = results.length;

		for (int var8 = 0; var8 < var7; ++var8) {
			Object obj = var6[var8];
			if (obj instanceof PfProcessBatchRetObject batchObj) {
				PFBatchExceptionInfo exceptionInfo = batchObj.getExceptionInfo();
				throw new BusinessException(exceptionInfo.getErrorMessage());
			}
		}

	}

	private Object[] doSave(AggRegisterVO aggVO) throws BusinessException {
		this.doBeforeSave(aggVO);
		CloudPFlowContext context = new CloudPFlowContext();
		context.setActionName("SAVEBASE");
		context.setBillType("36H1");
		context.setBillVos(new AggRegisterVO[] { aggVO });
		Object[] objects = ((ICloudScriptPFlowService) NCLocator.getInstance().lookup(ICloudScriptPFlowService.class))
				.exeScriptPFlow(context);
		return objects;
	}

	private void doBeforeSave(AggRegisterVO aggvo) throws BusinessException {
		RegisterVO pvo = aggvo.getparentVO();
		UFDateTime businessTime = new UFDateTime(InvocationInfoProxy.getInstance().getBizDateTime());
		pvo.setPk_group(InvocationInfoProxy.getInstance().getGroupId());
		pvo.setBillmaker(InvocationInfoProxy.getInstance().getUserId());
		pvo.setCreationtime(businessTime);
		pvo.setDoperatedate(new UFDate(InvocationInfoProxy.getInstance().getBizDateTime()));
		pvo.setCreationtime(businessTime);
		pvo.setCreator(InvocationInfoProxy.getInstance().getUserId());
		pvo.setPk_billtypecode("36H1");
		pvo.setGathertype("input");
		UFBoolean initflag = pvo.getInitflag();
		if (StringUtil.isNull(initflag)) {
			pvo.setInitflag(UFBoolean.FALSE);
		}

		pvo.setSfflag(UFBoolean.FALSE);
		pvo.setRegisterstatus("on_gather");
		pvo.setVbillstatus(-1);
		pvo.setRelatedrecbill(UFBoolean.FALSE);
		UFBoolean disableflag = pvo.getDisableflag();
		if (disableflag == null || !disableflag.booleanValue()) {
			pvo.setDisableflag(UFBoolean.FALSE);
		}

		pvo.setBookflag(UFBoolean.FALSE);
		pvo.setPlanflag(UFBoolean.FALSE);
		String pk_org = pvo.getPk_org();
		if (StringUtil.isNotNull(pvo.getReceiveaccount())) {
			BankAccbasVO accbasVO = this.getBankAccbasVOByReceiveaccount(pvo);
			String var10002;
			if (accbasVO.getEnablestate() != 2) {
				var10002 = pvo.getFbmbillno();
				throw new BusinessException(
						var10002 + NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0078"));
			}
//zhangxinah 去掉银行账户是否电票签约账户的校验
//			if (!accbasVO.getIsenableelecbill().booleanValue()) {
//				var10002 = pvo.getFbmbillno();
//				throw new BusinessException(
//						var10002 + NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0079"));
//			}

			BankdocVO bankdoc = this.getBanktypeByReceiveaccount(pvo.getReceiveaccount());
			pvo.setPk_banktype(bankdoc.getPk_banktype());
			pvo.setReceiveaccountname(bankdoc.getName());
		}

		IGeneralAccessor bankdocAccessor = GeneralAccessorFactory.getAccessor("bf5aeed4-6b35-4a2e-b750-b9aabce59e21");
		BankaccSubGeneralAccessor bankaccsubAccessor = (BankaccSubGeneralAccessor) (new BankaccSubAccessorFactory())
				.getAccessor("9e10ef4a-0be9-482b-880f-871e5b0504b7");
		IGeneralAccessor assLineNumAccessor = GeneralAccessorFactory
				.getAccessor("7b6c7dc0-db78-4bef-9cca-f5af4008f893");
		TMCustSupUtil.setCustSupPk(aggvo, "paybillunit_v", "paybillunit", "hidepaybillunit");
		CustSupplierVersionVO custSupVO;
		if (StringUtil.isNotNull(pvo.getPayunit())) {
			custSupVO = TMCustSupUtil.getCustSupplierVersionVOByNameAndDate(pvo.getPayunit(), pvo.getGatherdate());
			if (custSupVO != null) {
				pvo.setHidepayunit(custSupVO.getPk_cust_sup());
				pvo.setHidepayunit_v(custSupVO.getPk_cust_sup_v());
			}
		}

		if (StringUtil.isNotNull(pvo.getReceiveunit())) {
			custSupVO = TMCustSupUtil.getCustSupplierVersionVOByNameAndDate(pvo.getReceiveunit(), pvo.getGatherdate());
			if (custSupVO != null) {
				pvo.setHidereceiveunit(custSupVO.getPk_cust_sup());
				pvo.setHidereceiveunit_v(custSupVO.getPk_cust_sup_v());
			}
		}

		if (StringUtil.isNotNull(pvo.getReceivebankacc())) {
			IBDData cussup = bankaccsubAccessor.getDocByAccnum(pvo.getReceivebankacc(), pvo.getPk_curr());
			if (cussup != null) {
				pvo.setHidereceivebankacc(cussup.getPk());
			}
		}

		if (StringUtil.isNotNull(pvo.getReceivebank())) {
			IBDData cussup = bankdocAccessor.getDocByNameWithMainLang(pk_org, pvo.getReceivebank());
			if (cussup != null) {
				pvo.setHidereceivebank(cussup.getPk());
			}
		}

		boolean busType = FbmPublicUtil.isBusType(pvo.getFbmbilltype());
		IBDData cussup = null;
		if (busType) {
			if (StringUtil.isNotNull(pvo.getAcceptorname())) {
				custSupVO = TMCustSupUtil.getCustSupplierVersionVOByNameAndDate(pvo.getAcceptorname(),
						pvo.getGatherdate());
				if (custSupVO != null) {
					pvo.setPk_signagrbank(custSupVO.getPk_cust_sup());
					pvo.setPk_signagrbank_v(custSupVO.getPk_cust_sup_v());
				}
			}
		} else if (StringUtil.isNotNull(pvo.getAcceptorname())) {
			cussup = bankdocAccessor.getDocByNameWithMainLang(pk_org, pvo.getAcceptorname());
			if (cussup != null) {
				pvo.setSignagrbank(cussup.getPk());
			}
		}

		if (StringUtil.isNotNull(pvo.getSignagrbanknum())) {
			cussup = assLineNumAccessor.getDocByCode(pk_org, pvo.getSignagrbanknum());
			if (cussup != null) {
				pvo.setAcceptorbankaccount(cussup.getPk());
			}
		}

		if (StringUtil.isNotNull(pvo.getSignagrbankname())) {
			cussup = bankdocAccessor.getDocByNameWithMainLang(pk_org, pvo.getSignagrbankname());
			if (cussup != null) {
				pvo.setAcceptorbank(cussup.getPk());
			}
		}

		UFBoolean subcontractCirculation = pvo.getSubcontractcirculation();
		boolean ifBelongNewbillSys = FbmCommonTools.ifBelongNewBillSystem(pvo.getFbmbillno());
		if (ifBelongNewbillSys && subcontractCirculation != null && subcontractCirculation.booleanValue()) {
			String var10001 = pvo.getBillrangestart();
			pvo.setBillrange(var10001 + "-" + pvo.getBillrangeend());
		} else if (ifBelongNewbillSys) {
			if (!"0".equals(pvo.getBillrangestart()) || !"0".equals(pvo.getBillrangeend())) {
				throw new BusinessException("票据[" + pvo.getFbmbillno() + "]为新一代票且不可分包流转，子票区间开始和结束应为0！");
			}

			pvo.setBillrange(String.valueOf("0"));
		} else {
			pvo.setBillrange((String) null);
		}

		pvo.setBillsystype(FbmCommonTools.getBillSysTypeByFbmBillNo(pvo.getFbmbillno()));
		UFDouble availablemoney = pvo.getAvailablemoney();
		if (availablemoney == null) {
			pvo.setAvailablemoney(pvo.getMoney());
		}

		HashMap<String, String> voFieldsMap = new HashMap();
		voFieldsMap.put("groupField", "pk_group");
		voFieldsMap.put("orgField", "pk_org");
		voFieldsMap.put("currField", "pk_curr");
		voFieldsMap.put("rateField", "olcrate");
		voFieldsMap.put("custsupField", "paybillunit");
		voFieldsMap.put("dateField", "gatherdate");
		FbmPublicUtil.setOlcRate4Import(aggvo, voFieldsMap);
		voFieldsMap.put("rateField", "glcrate");
		FbmPublicUtil.setGlcRate4Import(aggvo, voFieldsMap);
		voFieldsMap.put("rateField", "gllcrate");
		FbmPublicUtil.setGllcRate4Import(aggvo, voFieldsMap);
		GatherReCaculateMnyUtil.recaculate(false, new AggRegisterVO[] { aggvo });
		ExcelImportUtil.validateOlcratetype(pvo.getOlcratetype(), pvo.getOlcratecategory());
	}

	private void check(AggRegisterVO aggvo) throws BusinessException {
		RegisterVO registerVO = aggvo.getparentVO();
		String fbmbillno = registerVO.getFbmbillno();
		UFBoolean cyberbankflag = registerVO.getCyberbankflag();
		if (cyberbankflag != null && !cyberbankflag.booleanValue()) {
			String pk_bankdoc = registerVO.getPk_bankdoc();
			if (!StringUtil.isNull(pk_bankdoc)) {
				throw new BusinessException(
						fbmbillno + NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0042"));
			}
		}

		UFDate gatherdate = registerVO.getGatherdate();
		UFDate invoicedate = registerVO.getInvoicedate();
		if (gatherdate != null && invoicedate != null
				&& gatherdate.toStdString().compareTo(invoicedate.toStdString()) < 0) {
			throw new BusinessException(
					fbmbillno + NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0043"));
		} else {
			UFDouble money = registerVO.getMoney();
			if (money != null && money.doubleValue() < 0.0) {
				throw new BusinessException(
						fbmbillno + NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0080"));
			} else {
				UFDate enddate = registerVO.getEnddate();
				if (enddate != null && invoicedate != null
						&& enddate.toStdString().compareTo(invoicedate.toStdString()) < 0) {
					throw new BusinessException(
							fbmbillno + NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0046"));
				} else {
					String fbmbilltype = registerVO.getFbmbilltype();
					String receiveaccount = registerVO.getReceiveaccount();
					boolean isEbill = FbmCommonTools.isEBill(fbmbilltype);
					if (isEbill) {
						if (StringUtil.isNull(receiveaccount)) {
							throw new BusinessException(fbmbillno
									+ NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0051"));
						}
					} else {
						UFBoolean onlinebankflag = registerVO.getOnlinebankflag();
						if (onlinebankflag != null && onlinebankflag.booleanValue()) {
							throw new BusinessException(fbmbillno
									+ NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0072"));
						}
					}

					FbmCommonTools.validBillRange(registerVO, isEbill);
					FbmCommonTools.billNoValication(fbmbillno);
					this.checkIsReturnedBill(registerVO);
				}
			}
		}
	}

	private void checkIsReturnedBill(RegisterVO registerVO) throws BusinessException {
		StringBuffer whereSql = new StringBuffer();
		whereSql.append(" pk_org = '").append(registerVO.getPk_org()).append("' ");
		whereSql.append(" and fbmbillno = '").append(registerVO.getFbmbillno()).append("' ");
		if (StringUtil.isNull(registerVO.getBillrangestart())) {
			whereSql.append(" and isnull(billrangestart, '0') = '0' ");
		} else {
			whereSql.append(" and billrangestart <= '").append(registerVO.getBillrangestart()).append("' ");
		}

		if (StringUtil.isNull(registerVO.getBillrangeend())) {
			whereSql.append(" and isnull(billrangeend, '0') = '0' ");
		} else {
			whereSql.append(" and billrangeend >= '").append(registerVO.getBillrangeend()).append("' ");
		}

		whereSql.append(" and ( endstatus = 'register' or endstatus = 'has_paybill' ) ");
		Collection<ActionVO> actionVOs = ((IMDPersistenceQueryService) NCLocator.getInstance()
				.lookup(IMDPersistenceQueryService.class))
				.queryBillOfVOByCond(ActionVO.class, whereSql.toString(), false);
		boolean returnedBill = false;
		if (null != actionVOs && actionVOs.size() > 0) {
			returnedBill = true;
		}
		registerVO.setReturnedbill(UFBoolean.valueOf(returnedBill));
	}

	private BankAccbasVO getBankAccbasVOByReceiveaccount(RegisterVO pvo) throws BusinessException {
		StringBuffer whereSql = new StringBuffer();
		whereSql.append(" pk_bankaccbas =  (select pk_bankaccbas from bd_bankaccsub where pk_bankaccsub = '");
		whereSql.append(NCESAPI.sqlEncode(pvo.getReceiveaccount()));
		whereSql.append("' ) ");
		IMDPersistenceQueryService service = (IMDPersistenceQueryService) NCLocator.getInstance()
				.lookup(IMDPersistenceQueryService.class);
		Collection<BankAccbasVO> accbasVOs = service.queryBillOfVOByCond(BankAccbasVO.class, whereSql.toString(),
				false);
		if (accbasVOs != null && accbasVOs.size() > 0
				&& ((BankAccbasVO[]) accbasVOs.toArray(new BankAccbasVO[0]))[0] != null) {
			return ((BankAccbasVO[]) accbasVOs.toArray(new BankAccbasVO[0]))[0];
		} else {
			String var10002 = pvo.getFbmbillno();
			throw new BusinessException(
					var10002 + NCLangRes4VoTransl.getNCLangRes().getStrByID("3618ncc_0", "03618ncc-0077"));
		}
	}

	private BankdocVO getBanktypeByReceiveaccount(String receiveaccount) throws BusinessException {
		StringBuffer whereSql = new StringBuffer();
		whereSql.append(" pk_bankdoc = (select pk_bankdoc from bd_bankaccbas where pk_bankaccbas = ");
		whereSql.append("(select pk_bankaccbas from bd_bankaccsub where pk_bankaccsub = '");
		whereSql.append(NCESAPI.sqlEncode(receiveaccount));
		whereSql.append("') ) ");
		BankdocVO[] bankdocVO = ((IBankdocQueryService) NCLocator.getInstance().lookup(IBankdocQueryService.class))
				.queryBankdocVOsByCon(whereSql.toString());
		return bankdocVO != null && bankdocVO.length != 0 ? bankdocVO[0] : null;
	}
}
