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

package nc.pubimpl.so.sobalance.arap.listener;

import com.yonyou.cloud.iuap.sagas.Sagas;
import com.yonyou.cloud.middleware.entity.SagasEntity;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nc.bs.businessevent.BdUpdateEvent;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.framework.common.NCLocator;
import nc.impl.pubapp.pattern.data.bill.BillQuery;
import nc.impl.so.m30.sobalance.maintain.IInsertBP;
import nc.impl.so.m30.sobalance.maintain.IUpdateBP;
import nc.impl.so.m30.sobalance.maintain.SobalanceBPFactoryForSoAuto;
import nc.itf.arap.forso.IDataFromF2ForM30;
import nc.pubitf.arap.pub.GetSODataByArapUtils;
import nc.vo.arap.gathering.AggGatheringBillVO;
import nc.vo.arap.gathering.GatheringBillItemVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.MathTool;
import nc.vo.scmpub.res.billtype.SOBillType;
import nc.vo.scmpub.util.SagasUtil;
import nc.vo.so.m30.entity.SaleOrderHVO;
import nc.vo.so.m30.entity.SaleOrderVO;
import nc.vo.so.m30.sobalance.entity.SoBalanceBVO;
import nc.vo.so.m30.sobalance.entity.SoBalanceHVO;
import nc.vo.so.m30.sobalance.entity.SoBalanceVO;
import nc.vo.so.m30.sobalance.enumeration.SoBalanceType;
import nccloud.pubitf.platform.businesslog.IBusinessLog;
import nccloud.pubitf.platform.businesslog.vo.SagasBusinessLog;

public class GatheringAddAfterListenerAction {
    Map<String, Collection<IDataFromF2ForM30>> insertDataMap;
    Map<String, Collection<IDataFromF2ForM30>> updateDataMap;
    Map<String, UFDateTime> tss = new HashMap();

    public GatheringAddAfterListenerAction() {
    }

    public void doAction(IBusinessEvent event) {
        Object value = null;
        if ("1004".equalsIgnoreCase(event.getEventType())) {
            BdUpdateEvent busievent = (BdUpdateEvent)event;
            value = busievent.getNewObject();
        } else {
            BusinessEvent busievent = (BusinessEvent)event;
            value = busievent.getObject();
        }

        AggGatheringBillVO[] billvos = this.constGatherBills(value);

        for(AggGatheringBillVO billvo : billvos) {
            GatheringBillItemVO[] bvos = billvo.getBodyVOs();

            for(GatheringBillItemVO bvo : bvos) {
                this.tss.put(bvo.getSrc_billid(), bvo.getTop_changets());
            }
        }

        IDataFromF2ForM30[] datas = (new GetSODataByArapUtils()).getIDataFromF2ForM30(event);
        Map<String, Collection<IDataFromF2ForM30>> dataMap = ArListenerUtils.getInstance().organizeDataMap(datas);
        String[] csaleorderids = (String[])dataMap.keySet().toArray(new String[dataMap.keySet().size()]);
        if (csaleorderids != null && csaleorderids.length != 0) {
            SoBalanceVO[] vos = null;

            try {
                vos = ArListenerUtils.getInstance().querySoBalanceVOByIDs(csaleorderids);
            } catch (BusinessException e) {
                ExceptionUtils.wrappException(e);
            }

            this.splitDataMap(vos, dataMap);

            try {
                if (this.insertDataMap.size() > 0) {
                    this.insertVO();
                }

                if (this.updateDataMap.size() > 0) {
                    this.updateVO(vos);
                }
            } catch (BusinessException e) {
                ExceptionUtils.wrappException(e);
            }

        }
    }

    private AggGatheringBillVO[] constGatherBills(Object value) {
        AggGatheringBillVO[] bills = null;
        if (value.getClass().isArray()) {
            AggregatedValueObject[] vos1 = (AggregatedValueObject[])value;
            bills = (AggGatheringBillVO[])Array.newInstance(vos1[0].getClass(), vos1.length);
            System.arraycopy(vos1, 0, bills, 0, vos1.length);
        } else {
            AggGatheringBillVO aggVO = (AggGatheringBillVO)value;
            bills = new AggGatheringBillVO[]{aggVO};
        }

        return bills;
    }

    private void checkGatheringAndSaleOrderConsistent(IDataFromF2ForM30[] datas, SaleOrderVO saleOrderVO) throws BusinessException {
        SaleOrderHVO head = saleOrderVO.getParentVO();
        String ccustomerid = head.getCcustomerid();
        String corigcurrencyid = head.getCorigcurrencyid();
        String cinvoicecustid = head.getCinvoicecustid();
        String carorgid = saleOrderVO.getChildrenVO()[0].getCarorgid();
        UFDouble ntotalorigmny = head.getNtotalorigmny();

        for(IDataFromF2ForM30 data : datas) {
            if (!ccustomerid.equals(data.getPayBillOrderCust())) {
                throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006011_0", "04006011-0193", (String)null, new String[]{head.getVbillcode()}));
            }

            if (!cinvoicecustid.equals(data.getPayBillCustomer())) {
                throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006011_0", "04006011-0194", (String)null, new String[]{head.getVbillcode()}));
            }

            if (!corigcurrencyid.equals(data.getPayBillCurID())) {
                throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006011_0", "04006011-0195", (String)null, new String[]{head.getVbillcode()}));
            }

            if (!carorgid.equals(data.getPayBillOrg())) {
                throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006011_0", "04006011-0196", (String)null, new String[]{head.getVbillcode()}));
            }

            if (MathTool.isDiffSign(ntotalorigmny, data.getPayBillmny())) {
                throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006011_0", "04006011-0412"));
            }
        }

    }

    private SoBalanceVO createInsertSoBalanceVO(IDataFromF2ForM30[] datas, SaleOrderVO saleOrderVO) {
        SoBalanceHVO headVO = ArListenerUtils.getInstance().createSoBalanceHVO(saleOrderVO);
        UFDouble ntotalorigmny = saleOrderVO.getParentVO().getNtotalorigmny();
        SoBalanceBVO[] bodyVOs = this.createSoBalanceBVOs(datas, ntotalorigmny, UFDouble.ZERO_DBL);
        SoBalanceVO retVO = new SoBalanceVO();
        retVO.setParentVO(headVO);
        retVO.setChildrenVO(bodyVOs);
        return retVO;
    }

    private SoBalanceBVO[] createSoBalanceBVOs(IDataFromF2ForM30[] datas, UFDouble ntotalorigmny, UFDouble ntotalpaymny) {
        SoBalanceBVO[] retBodyVOs = new SoBalanceBVO[datas.length];

        for(int i = 0; i < datas.length; ++i) {
            retBodyVOs[i] = new SoBalanceBVO();
            retBodyVOs[i].setCpaybillid(datas[i].getPayBillID());
            retBodyVOs[i].setCpaybillrowid(datas[i].getPayBillRowID());
            retBodyVOs[i].setVarbillcode(datas[i].getPayBillNo());
            retBodyVOs[i].setDarbilldate(datas[i].getPayBillDate());
            retBodyVOs[i].setDarbalancedate(AppContext.getInstance().getBusiDate());
            retBodyVOs[i].setCarorigcurrencyid(datas[i].getPayBillCurID());
            retBodyVOs[i].setCprodlineid(datas[i].getCprodlineID());
            retBodyVOs[i].setNorigarmny(datas[i].getPayBillmny());
            UFDouble canPayMny = MathTool.sub(ntotalorigmny, ntotalpaymny);
            if (MathTool.absCompareTo(canPayMny, datas[i].getPayBillmny()) > 0) {
                retBodyVOs[i].setNorigordbalmny(datas[i].getPayBillmny());
            } else {
                retBodyVOs[i].setNorigordbalmny(canPayMny);
            }

            retBodyVOs[i].setFibaltype(SoBalanceType.SOBALANCE_ORDERBAL.getIntValue());
            retBodyVOs[i].setBpreceiveflag(UFBoolean.valueOf(datas[i].isPrePay()));
            retBodyVOs[i].setDr(0);
            retBodyVOs[i].setStatus(2);
        }

        return retBodyVOs;
    }

    private SoBalanceVO createUpdateSoBalanceVO(IDataFromF2ForM30[] datas, SoBalanceVO oldSoBalanceVO) {
        SoBalanceHVO newHeadVO = (SoBalanceHVO)oldSoBalanceVO.getParentVO().clone();
        newHeadVO.setStatus(0);
        UFDouble ntotalorigtaxmny = newHeadVO.getNtotalorigtaxmny();
        UFDouble ntotalpaymny = newHeadVO.getNtotalpaymny();
        SoBalanceBVO[] oldBodyVOs = oldSoBalanceVO.getChildrenVO();
        Map<String, SoBalanceBVO> oldBodyMap = new HashMap();

        for(SoBalanceBVO oldBodyVO : oldBodyVOs) {
            oldBodyMap.put(oldBodyVO.getCpaybillrowid(), oldBodyVO);
        }

        Map<String, IDataFromF2ForM30> updateMap = new HashMap();
        List<IDataFromF2ForM30> newList = new ArrayList();

        for(IDataFromF2ForM30 data : datas) {
            String paybillrowid = data.getPayBillRowID();
            if (oldBodyMap.containsKey(paybillrowid)) {
                updateMap.put(data.getPayBillRowID(), data);
            } else {
                newList.add(data);
            }
        }

        List<SoBalanceBVO> bodyVOList = new ArrayList();
        SoBalanceBVO[] newBodyVOs = this.createSoBalanceBVOs((IDataFromF2ForM30[])newList.toArray(new IDataFromF2ForM30[newList.size()]), ntotalorigtaxmny, ntotalpaymny);
        if (newBodyVOs.length > 0) {
            for(SoBalanceBVO bodyvo : newBodyVOs) {
                bodyvo.setDr(0);
                bodyvo.setStatus(2);
                bodyvo.setCsobalanceid(newHeadVO.getPrimaryKey());
                bodyVOList.add(bodyvo);
            }
        }

        for(SoBalanceBVO oldBody : oldBodyVOs) {
            String paybillrowid = oldBody.getCpaybillrowid();
            if (updateMap.containsKey(paybillrowid)) {
                SoBalanceBVO newbodyvo = (SoBalanceBVO)oldBody.clone();
                newbodyvo.setNorigordbalmny(((IDataFromF2ForM30)updateMap.get(paybillrowid)).getPayBillmny());
                newbodyvo.setStatus(1);
                bodyVOList.add(newbodyvo);
            } else {
                SoBalanceBVO newbodyvo = (SoBalanceBVO)oldBody.clone();
                newbodyvo.setStatus(0);
                bodyVOList.add(newbodyvo);
            }
        }

        SoBalanceVO retSobalanceVO = new SoBalanceVO();
        retSobalanceVO.setParentVO(newHeadVO);
        retSobalanceVO.setChildrenVO((SoBalanceBVO[])bodyVOList.toArray(new SoBalanceBVO[bodyVOList.size()]));
        return retSobalanceVO;
    }

    private void insertVO() throws BusinessException {
        String[] csaleorderids = (String[])this.insertDataMap.keySet().toArray(new String[this.insertDataMap.keySet().size()]);
        BillQuery<SaleOrderVO> query = new BillQuery(SaleOrderVO.class);
        SaleOrderVO[] saleOrderVOs = (SaleOrderVO[])query.query(csaleorderids);
        if (this.insertDataMap.size() != saleOrderVOs.length) {
            throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006011_0", "04006011-0117"));
        } else {
            for(SaleOrderVO vo : saleOrderVOs) {
                if (!SagasUtil.isNccnativeMerged() && !this.isCheck()) {
                    break;
                }

                UFDateTime factTs = vo.getParentVO().getTs();
                if (this.tss.get(vo.getParentVO().getCsaleorderid()) != null && !((UFDateTime)this.tss.get(vo.getParentVO().getCsaleorderid())).equals(factTs)) {
                    String message = NCLangRes4VoTransl.getNCLangRes().getStrByID("4020003_0", "04020003-0086");
                    ExceptionUtils.wrappBusinessException(message);
                }
            }

            SoBalanceVO[] newSoBalanceVOs = new SoBalanceVO[this.insertDataMap.size()];

            for(int i = 0; i < saleOrderVOs.length; ++i) {
                String csaleorderid = saleOrderVOs[i].getParentVO().getCsaleorderid();
                List<IDataFromF2ForM30> dataList = (List)this.insertDataMap.get(csaleorderid);
                IDataFromF2ForM30[] datas = (IDataFromF2ForM30[])dataList.toArray(new IDataFromF2ForM30[dataList.size()]);
                this.checkGatheringAndSaleOrderConsistent(datas, saleOrderVOs[i]);
                newSoBalanceVOs[i] = this.createInsertSoBalanceVO(datas, saleOrderVOs[i]);
            }

            IInsertBP service = SobalanceBPFactoryForSoAuto.getInstance().getInsertBP();
            service.insert(newSoBalanceVOs);
        }
    }

    private void splitDataMap(SoBalanceVO[] vos, Map<String, Collection<IDataFromF2ForM30>> dataMap) {
        Set<String> csaleorderidSet = new HashSet();
        if (vos != null && vos.length > 0) {
            for(SoBalanceVO vo : vos) {
                csaleorderidSet.add(vo.getParentVO().getCsaleorderid());
            }
        }

        this.insertDataMap = new HashMap();
        this.updateDataMap = new HashMap();

        for(Map.Entry<String, Collection<IDataFromF2ForM30>> entry : dataMap.entrySet()) {
            if (csaleorderidSet.contains(entry.getKey())) {
                this.updateDataMap.put(entry.getKey(), entry.getValue());
            } else {
                this.insertDataMap.put(entry.getKey(), entry.getValue());
            }
        }

    }

    private void updateVO(SoBalanceVO[] oldSoBalanceVOs) throws BusinessException {
        String[] csaleorderids = (String[])this.updateDataMap.keySet().toArray(new String[this.updateDataMap.keySet().size()]);
        BillQuery<SaleOrderVO> query = new BillQuery(SaleOrderVO.class);
        SaleOrderVO[] saleOrderVOs = (SaleOrderVO[])query.query(csaleorderids);
        if (this.updateDataMap.size() != saleOrderVOs.length) {
            throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006011_0", "04006011-0117"));
        } else {
            for(SaleOrderVO vo : saleOrderVOs) {
                if (!SagasUtil.isNccnativeMerged() && !this.isCheck()) {
                    break;
                }

                UFDateTime factTs = vo.getParentVO().getTs();
                if (this.tss.get(vo.getParentVO().getCsaleorderid()) != null && !((UFDateTime)this.tss.get(vo.getParentVO().getCsaleorderid())).equals(factTs)) {
                    String message = NCLangRes4VoTransl.getNCLangRes().getStrByID("4020003_0", "04020003-0086");
                    ExceptionUtils.wrappBusinessException(message);
                }
            }

            SoBalanceVO[] newSoBalanceVOs = new SoBalanceVO[this.updateDataMap.size()];

            for(int i = 0; i < oldSoBalanceVOs.length; ++i) {
                String csaleorderid = oldSoBalanceVOs[i].getParentVO().getCsaleorderid();
                List<IDataFromF2ForM30> dataList = (List)this.updateDataMap.get(csaleorderid);
                IDataFromF2ForM30[] datas = (IDataFromF2ForM30[])dataList.toArray(new IDataFromF2ForM30[dataList.size()]);
                this.checkGatheringAndSaleOrderConsistent(datas, saleOrderVOs[i]);
                newSoBalanceVOs[i] = this.createUpdateSoBalanceVO(datas, oldSoBalanceVOs[i]);
                newSoBalanceVOs[i].setListenerflag(UFBoolean.TRUE);
            }

            SagasUtil.frozenAndAddSagaForHead(saleOrderVOs, SOBillType.Order.getCode());
            SagasUtil.frozenAndAddSagaForHead(oldSoBalanceVOs, SOBillType.Order.getCode());
            IUpdateBP mainservice = SobalanceBPFactoryForSoAuto.getInstance().getUpdateBP();
            mainservice.update(newSoBalanceVOs, oldSoBalanceVOs);
        }
    }

    private Boolean isCheck() {
        Boolean isCheck = true;
        SagasEntity sc = Sagas.getCurrentSagasInfo().getCurrent();
        IBusinessLog bl = (IBusinessLog)NCLocator.getInstance().lookup(IBusinessLog.class);

        try {
            SagasBusinessLog log = bl.queryByGtxid(sc.getGtxId());
            String billType = log.getBillType();
            if (billType.indexOf("30") != -1) {
                isCheck = false;
            }
        } catch (Exception e) {
            ExceptionUtils.wrappException(e);
        }

        return isCheck;
    }
}
