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

package nc.bs.mmpub.setanalysis.bp.multistorey;

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

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.mmpub.setanalysis.bp.SaMonolayerBP;
import nc.bs.mmpub.setanalysis.bp.demand.SaDemandInsertBP;
import nc.bs.mmpub.setanalysis.bp.demand.SaDemandQueryBP;
import nc.bs.mmpub.setanalysis.bp.log.SaLogInsertBP;
import nc.bs.mmpub.setanalysis.bp.utils.SaArrayUtil;
import nc.bs.mmpub.setanalysis.bp.utils.SaBooleanUtils;
import nc.bs.mmpub.setanalysis.bp.utils.SaLogger;
import nc.bs.mmpub.setanalysis.bp.utils.SaVOUtils;
import nc.impl.pubapp.pattern.data.vo.VOUpdate;
import nc.impl.pubapp.pattern.data.vo.VOUpdateTS;
import nc.util.mmf.framework.base.MMNumberUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.vo.mmpub.setanalysis.entity.AggAnalysisVO;
import nc.vo.mmpub.setanalysis.entity.SaAnalysisVO;
import nc.vo.mmpub.setanalysis.entity.SaContext;
import nc.vo.mmpub.setanalysis.entity.SaDemandVO;
import nc.vo.mmpub.setanalysis.entity.SaMatchVO;
import nc.vo.mmpub.setanalysis.enumeration.SaDemandType;
import nc.vo.mmpub.setanalysis.enumeration.SaMatchType;
import nc.vo.mmpub.setanalysis.utils.SaMeasureUtil;
import nc.vo.mmpub.setanalysis.utils.SaValidateUtil;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.pub.MapList;
import nc.vo.pubapp.pattern.pub.MathTool;
import nccloud.baseapp.core.log.NCCForUAPLogger;

/**
 * 齐套率回写流程生产订单
 * 2005适配2312
 *
 * @author mzr
 * @date 2025/3/26
 */
public class SaMultiStoreyBP {
    private SaContext sc;
    private List<SaMatchVO> smVO;
    private MapList<String, SaDemandVO> demand;
    private Map<String, SaDemandVO> demandPkMap;
    private Map<String, AggAnalysisVO> aggPkMap;
    private int maxLevel = 0;
    private SaAlgorithmBP algorithm;

    public SaMultiStoreyBP(SaContext sc) {
        SaLogger.debug("3.1.反算齐套初始化开始");
        this.algorithm = new SaAlgorithmBP();
        this.setSc(sc);
        List<SaDemandVO> sdList = SaVOUtils.getDemandList(sc.getSdVO());
        this.maxLevel = SaDemandQueryBP.getMaxLevelCode(sdList);
        this.setDemand(SaVOUtils.getSortMapList(sdList, "levelcode"));
        if (!MMValueCheck.isEmpty(sc.getSdVO())) {
            sc.getSdVO().toMap().clear();
        }

        this.smVO = new ArrayList();
        this.demandPkMap = new HashMap();
        this.demandPkMap = this.algorithm.demandGroupForPk(sdList);
        this.aggPkMap = new HashMap();
        this.aggPkMap = this.algorithm.aggGroupForPk(this.sc.getAggs());
    }

    public void doMultiStorey() {
        SaLogger.debug("3.2.反算齐套开始计算");
        if (!MMValueCheck.isEmpty(this.demand)) {
            for(int curLevel = this.maxLevel; curLevel > 0; --curLevel) {
                List<SaDemandVO> sdList = this.demand.get(Integer.toString(curLevel));
                if (!MMValueCheck.isEmpty(sdList)) {
                    for(SaDemandVO sa : sdList) {
                        this.algorithm.setNum(sa);
                    }

                    this.setDemandForAnalysis(sdList, Integer.toString(curLevel));
                    SaLogger.debug("3.3.反算齐套层码" + Integer.toString(curLevel));
                }
            }
        }

        this.insert();
    }

    private void setDemandForAnalysis(List<SaDemandVO> sdList, String key) {
        if (!MMValueCheck.isEmpty(sdList)) {
            MapList<String, SaDemandVO> demandMap = SaVOUtils.getSortMapList(sdList, "pk_analysis");
            if (!MMValueCheck.isEmpty(demandMap)) {
                for(Map.Entry<String, List<SaDemandVO>> entry : demandMap.toMap().entrySet()) {
                    List<SaDemandVO> demandList = (List)entry.getValue();
                    this.setDemandForFatherid(demandList, key);
                }
            }

        }
    }

    private void setDemandForFatherid(List<SaDemandVO> sdList, String key) {
        if (!MMValueCheck.isEmpty(sdList)) {
            MapList<String, SaDemandVO> demandMap = SaVOUtils.getSortMapList(sdList, "vfatherid");
            if (!MMValueCheck.isEmpty(demandMap)) {
                for(Map.Entry<String, List<SaDemandVO>> entry : demandMap.toMap().entrySet()) {
                    List<SaDemandVO> demandList = SaArrayUtil.getMultiDemandSort((List)entry.getValue());
                    SaDemandVO nsetsnum = new SaDemandVO();
                    if (MMValueCheck.isNotEmpty(demandList)) {
                        if (SaBooleanUtils.isReplace(demandList)) {
                            SaRaplaceItemBP raplaceBP = new SaRaplaceItemBP(demandList);
                            List<SaDemandVO> raplaceList = raplaceBP.getRaplaceItem();
                            List<SaDemandVO> materialList = raplaceBP.getMaterialItem();
                            if (!MMValueCheck.isEmpty(raplaceList)) {
                                nsetsnum = this.algorithm.getReplaceNum(raplaceList);
                            }

                            new SaDemandVO();
                            if (!MMValueCheck.isEmpty(raplaceList)) {
                                SaDemandVO material = this.setMatchFatherid(materialList, key);
                                if (!MMValueCheck.isEmpty(material)) {
                                    nsetsnum.setNsetsnum(nsetsnum.getNsetsnum().add(material.getNsetsnum()));
                                }
                            }
                        } else {
                            nsetsnum = this.setMatchFatherid(demandList, key);
                        }
                    }

                    if (MMValueCheck.isNotEmpty(nsetsnum.getNsetsnum()) && nsetsnum.getNsetsnum().compareTo(UFDouble.ZERO_DBL) > 0 || MMValueCheck.isNotEmpty(nsetsnum.getNreplacesetsnum()) && nsetsnum.getNreplacesetsnum().compareTo(UFDouble.ZERO_DBL) > 0) {
                        this.setRewriteNmaterialnum(key, nsetsnum, false);
                    }
                }
            }

        }
    }

    private SaDemandVO setMatchFatherid(List<SaDemandVO> sdList, String key) {
        if (MMValueCheck.isEmpty(sdList)) {
            return null;
        } else {
            UFDouble nsetsnumsum = new UFDouble();
            SaDemandVO nsetsnum = new SaDemandVO();
            int num = (int) sdList.stream()
                    .filter(saDemandVO -> MathTool.compareTo(saDemandVO.getNmaterialnum(), saDemandVO.getNdemandnum()) >= 0)
                    .count();
            MapList<String, SaDemandVO> demandMap = SaVOUtils.getSortMapList(sdList, "vmatchfatherid");
            if (!MMValueCheck.isEmpty(demandMap)) {
                for(Map.Entry<String, List<SaDemandVO>> entry : demandMap.toMap().entrySet()) {
                    List<SaDemandVO> demandList = (List)entry.getValue();
                    if (((SaDemandVO)demandList.get(0)).getFmatchtype().equals(SaMatchType.PD.toIntValue()) && ((SaDemandVO)demandList.get(0)).getFdemandtype().equals(SaDemandType.NR.toIntValue())) {
                        nsetsnum = this.algorithm.minDemand((SaDemandVO[])demandList.toArray(new SaDemandVO[0]));
                        // 设置物料的总行数、满足齐套的物料的行数
                        nsetsnum.setGoodsnum(new UFDouble(sdList.size()));
                        nsetsnum.setPass_goodsnum(new UFDouble(num));
                        this.setRewriteNmaterialnum(key, nsetsnum, false);
                        this.setRewriteNmaterialnum(key, nsetsnum, true);
                        nsetsnumsum = nsetsnumsum.add(nsetsnum.getNsetsnum());
                        break;
                    }
                }

                for(Map.Entry<String, List<SaDemandVO>> entry : demandMap.toMap().entrySet()) {
                    List<SaDemandVO> demandList = (List)entry.getValue();
                    if (!((SaDemandVO)demandList.get(0)).getFdemandtype().equals(SaDemandType.NR.toIntValue()) && demandList.size() > 0) {
                        nsetsnum = this.algorithm.minDemand((SaDemandVO[])demandList.toArray(new SaDemandVO[0]));
                        // 设置物料的总行数、满足齐套的物料的行数
                        nsetsnum.setGoodsnum(new UFDouble(sdList.size()));
                        nsetsnum.setPass_goodsnum(new UFDouble(num));
                        this.setRewriteNmaterialnum(key, nsetsnum, true);
                        nsetsnumsum = SaValidateUtil.add(nsetsnumsum, nsetsnum.getNsetsnum());
                    }
                }
            }

            if (!MMValueCheck.isEmpty(nsetsnumsum)) {
                nsetsnum.setNsetsnum(nsetsnumsum);
            }

            return nsetsnum;
        }
    }

    private void setRewriteNmaterialnum(String key, SaDemandVO nsetsnum, boolean isUpdateMatch) {
        if (!MMValueCheck.isEmpty(nsetsnum)) {
            int level = this.getLevel(key);
            if (level == 0) {
                if (this.aggPkMap != null) {
                    AggAnalysisVO agg = (AggAnalysisVO)this.aggPkMap.get(nsetsnum.getVfatherid());
                    if (agg != null) {
                        SaAnalysisVO analysis = agg.getParentVO();
                        analysis.setNsetsnum(MMNumberUtil.add(new UFDouble[]{nsetsnum.getNsetsnum(), nsetsnum.getNreplacesetsnum()}));
                        if (isUpdateMatch) {
                            // 流程生产订单表体主键
                            String cdemandbillbid = analysis.getCdemandbillbid();
                            // 物料的总行数
                            UFDouble goodsnum = nsetsnum.getGoodsnum().setScale(2, UFDouble.ROUND_HALF_UP);
                            // 满足齐套的物料的行数
                            UFDouble pass_goodsnum = nsetsnum.getPass_goodsnum().setScale(2, UFDouble.ROUND_HALF_UP);
                            // 齐套率计算=满足的/总数量
                            UFDouble rate = pass_goodsnum.div(goodsnum, 2, UFDouble.ROUND_HALF_UP);
                            // 修改流程生产订单的齐套率、物料的总行数、满足齐套的物料的行数
                            String sql = String.format("update mm_mo set vdef12 = '%s',vdef11 = '%s',vdef4 = '%s' where cmoid = '%s'",
                                    goodsnum, pass_goodsnum, rate.toString(), cdemandbillbid);
                            updateDef4(sql);
                        }
                    }
                }
            } else if (this.demandPkMap != null) {
                new SaDemandVO();
                SaDemandVO var7 = (SaDemandVO)this.demandPkMap.get(nsetsnum.getVfatherid());
                if (!isUpdateMatch) {
                    UFDouble nmatch = MMNumberUtil.add(new UFDouble[]{var7.getNmatchnum(), nsetsnum.getNsetsnum()});
                    var7.setNmaterialnum(nmatch);
                    var7.setNreplacesetsnum(nsetsnum.getNreplacesetsnum());
                } else {
                    this.updateNmaterialnum(nsetsnum, var7);
                }
            }

        }
    }

    private int updateDef4(String sql) {
        try {
            NCCForUAPLogger.debug("sql = " + sql);
            BaseDAO baseDAO = new BaseDAO();
            return baseDAO.executeUpdate(sql);
        } catch (DAOException e) {
            NCCForUAPLogger.debug("setRewriteNmaterialnum-exp:" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    private int getLevel(String key) {
        return key.length() == 0 ? 0 : Integer.parseInt(key) - 1;
    }

    private void insert() {
        (new SaLogInsertBP(this.sc)).insertLog();
        SaDemandInsertBP sdi = new SaDemandInsertBP();
        List<SaDemandVO> sdList = SaVOUtils.getDemandList(this.demand);
        if (!MMValueCheck.isEmpty(sdList)) {
            SaLogger.debug("3.4.反算持久化(相关需求，分析对象)" + sdList.size());
            sdi.insertDemand((SaDemandVO[])sdList.toArray(new SaDemandVO[0]), this.sc);
            SaAnalysisVO[] sas = SaVOUtils.construcVOs(this.getSc().getAggs());
            SaMeasureUtil.setAnalysisNum(sas);
            VOUpdate<SaAnalysisVO> voup = new VOUpdate();
            voup.update(sas, new String[]{"nsetsnum", "nremainnum", "nsetsasnum", "nassremainnum"});
            this.updateMatch();
            SaLogger.debug("3.5.反算持久化结束");
        }
    }

    private void updateNmaterialnum(SaDemandVO saDemand, SaDemandVO hDemand) {
        if (!saDemand.getVfatherid().equals(saDemand.getVmatchfatherid()) && (saDemand.getFmatchtype().equals(SaMatchType.PICK.value()) || saDemand.getFmatchtype().equals(SaMatchType.PD.value()) || saDemand.getFmatchtype().equals(SaMatchType.MREQ.value()))) {
            SaMatchVO sm = new SaMatchVO();
            sm.setPk_match(saDemand.getVmatchfatherid());
            sm.setNmaterialnum(saDemand.getNsetsnum());
            UFDouble nsetsnum = SaMonolayerBP.getNsetsnum(hDemand, saDemand.getNsetsnum(), (UFDouble)null);
            sm.setNsetsnum(nsetsnum);
            this.getSmVO().add(sm);
        }

    }

    private void updateMatch() {
        SaMatchVO[] sms = (SaMatchVO[])this.getSmVO().toArray(new SaMatchVO[0]);
        if (!MMValueCheck.isEmpty(sms)) {
            VOUpdateTS<SaMatchVO> voQuery = new VOUpdateTS();
            voQuery.update(sms);
            VOUpdate<SaMatchVO> voup = new VOUpdate();
            voup.update(sms, new String[]{"nmaterialnum", "nsetsnum"});
        }

    }

    public int getMaxLevel() {
        return this.maxLevel;
    }

    public void setMaxLevel(int maxLevel) {
        this.maxLevel = maxLevel;
    }

    public MapList<String, SaDemandVO> getDemand() {
        return this.demand;
    }

    public void setDemand(MapList<String, SaDemandVO> demand) {
        this.demand = demand;
    }

    public SaContext getSc() {
        return this.sc;
    }

    public void setSc(SaContext sc) {
        this.sc = sc;
    }

    public List<SaMatchVO> getSmVO() {
        return this.smVO;
    }

    public void setSmVO(List<SaMatchVO> smVO) {
        this.smVO = smVO;
    }

    public SaAlgorithmBP getAlgorithm() {
        return this.algorithm;
    }

    public void setAlgorithm(SaAlgorithmBP algorithm) {
        this.algorithm = algorithm;
    }

    public Map<String, SaDemandVO> getDemandPkMap() {
        return this.demandPkMap;
    }

    public void setDemandPkMap(Map<String, SaDemandVO> demandPkMap) {
        this.demandPkMap = demandPkMap;
    }

    public Map<String, AggAnalysisVO> getAggPkMap() {
        return this.aggPkMap;
    }

    public void setAggPkMap(Map<String, AggAnalysisVO> aggPkMap) {
        this.aggPkMap = aggPkMap;
    }
}
