basic-server/src/main/java/com/ruoyi/basic/service/impl/StandardProductListServiceImpl.java
@@ -1,7 +1,6 @@
package com.ruoyi.basic.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -10,7 +9,6 @@
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.basic.dto.CopyStandardProductListDto;
import com.ruoyi.basic.dto.InsSampleReceiveDto;
import com.ruoyi.basic.dto.ProductDto;
import com.ruoyi.basic.dto.ResetTreeDragDTO;
import com.ruoyi.basic.mapper.IfsInventoryQuantityMapper;
import com.ruoyi.basic.mapper.StandardProductListMapper;
@@ -18,8 +16,9 @@
import com.ruoyi.basic.mapper.StandardTreeMapper;
import com.ruoyi.basic.pojo.StandardProductList;
import com.ruoyi.basic.pojo.StandardProductListSupplierAsk;
import com.ruoyi.basic.pojo.StandardTree;
import com.ruoyi.basic.service.StandardProductListService;
import com.ruoyi.basic.utils.StandardTreePath;
import com.ruoyi.basic.utils.StandardTreePathParser;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -57,13 +56,36 @@
    @Override
    public List<StandardProductList> selectStandardProductList(InsSampleReceiveDto insSample) {
        // 是否没有产品
        if (insSample == null || insSample.getStandardMethodListId() == null) {
            throw new BaseException("检验标准不能为空");
        }
        // 新疆新聚两级树优先按“行业 + 标准”规范路径查询;无法解析时保留历史五级逻辑。
        boolean twoLevelOrder = false;
        boolean isNoSample = false;
//        String[] models = insSample.getModel().split("-(?=[^-]*$)");//拆分最后一个【-】
        String model = insSample.getModel();
        String modelNum = insSample.getModelNum();
        List<StandardProductList> list = standardProductListMapper.selectDetail(insSample.getStandardMethodListId(), 1, model, insSample.getIsCableTag());
        if (list.size() == 0) {
        List<StandardProductList> list = Collections.emptyList();
        if (StringUtils.isNotBlank(insSample.getFactory())) {
            try {
                StandardTreePath path = StandardTreePathParser.parse(insSample.getFactory());
                if (path.getStandard() != null) {
                    String canonicalTree = StandardTreePathParser.canonical(path.getIndustry(), path.getStandard());
                    list = standardProductListMapper.selectDetail2(
                            insSample.getStandardMethodListId(), 1, canonicalTree, insSample.getIsCableTag());
                    insSample.setLaboratory(path.getIndustry());
                    insSample.setSampleType(null);
                    insSample.setSample(path.getStandard());
                    insSample.setModel(null);
                    twoLevelOrder = true;
                }
            } catch (BaseException ignored) {
                // 历史五级路径继续走原有兼容查询。
            }
        }
        if (!twoLevelOrder) {
            list = standardProductListMapper.selectDetail(insSample.getStandardMethodListId(), 1, model, insSample.getIsCableTag());
        }
        if (!twoLevelOrder && list.size() == 0) {
            if (Objects.equals(insSample.getFactory(), "") || insSample.getFactory() == null) {
                return null;
            }
@@ -85,8 +107,8 @@
                }
            }
        }
        if (!twoLevelOrder && !isNoSample) {
        String[] split1 = insSample.getFactory().split(" - ");
        if (!isNoSample) {
            //判断长度
            if (split1.length > 4) {
                if (ObjectUtils.isNotEmpty(split1[3])) {
@@ -96,9 +118,14 @@
                }
            }
        }
        final boolean currentTwoLevelOrder = twoLevelOrder;
        list = list.stream().filter(a -> {
                    try {
                        if (a.getSection() != null && !Objects.equals(a.getSection(), "")) {
                            // 两级下单不再输入型号,不能因无法计算型号区间而丢弃整个检验项。
                            if (currentTwoLevelOrder && StringUtils.isBlank(modelNum)) {
                                return true;
                            }
                            List<String> sections = JSON.parseArray(a.getSection(), String.class);// 区间
                            List<String> cores = JSON.parseArray(a.getCores(), String.class); // 芯数
                            List<String> conductorMaterials = JSON.parseArray(a.getConductorMaterial(), String.class); // 导体材质
@@ -256,234 +283,151 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> selectStandardProductListByMethodId(Integer id, String tree) {
        // 将“工厂 - 实验室 - 样品类别 - 样品 - 型号”路径拆成各级节点。
        String[] trees = tree.split(" - ");
        // 四级及以上节点需要按数据库中已保存的 sort 排序返回。
        boolean isDrag = false;
        // 存放根据结构参数表重新生成的检验项目。
        List<StandardProductList> list = new ArrayList<>();
        if (trees.length == 3) {
            // 三级节点只定位到样品类别,需要继续展开该类别下的样品和型号。
            List<StandardTree> treeList = new ArrayList<>();
            StandardTree standardTree = new StandardTree();
            standardTree.setFactory(trees[0]);
            standardTree.setLaboratory(trees[1]);
            standardTree.setSampleType(trees[2]);
            // 查询该样品类别关联的产品(样品)名称。
            List<ProductDto> pList = standardTreeMapper.selectPList(trees[2]);
            if (pList.isEmpty() || pList.get(0) == null) {
                // 没有产品时,直接使用该实验室和样品类别已配置的标准树节点。
                List<StandardTree> treeList1 = standardTreeMapper.selectList(Wrappers.<StandardTree>lambdaQuery().eq(StandardTree::getLaboratory, trees[1]).eq(StandardTree::getSampleType, trees[2]));
                if (treeList1.isEmpty()) {
                    // 标准树也不存在时,保留三级节点作为兜底查询条件。
                    treeList.add(standardTree);
                } else {
                    treeList.addAll(treeList1);
    public Map<String, Object> selectStandardProductListByMethodId(Integer id, String tree, Integer page, String keyword) {
        if (id == null) {
            throw new BaseException("检验标准不能为空");
                }
            } else {
                // 按产品逐个查找已配置的型号;未配置时创建一个只有样品信息的兜底节点。
                for (ProductDto p : pList) {
                    standardTree.setSample(p.getName());
                    List<StandardTree> treeList1 = standardTreeMapper.selectList(Wrappers.<StandardTree>lambdaQuery().eq(StandardTree::getLaboratory, trees[1]).eq(StandardTree::getSampleType, trees[2]).eq(StandardTree::getSample, p.getName()));
                    if (treeList1.isEmpty()) {
                        treeList.add(JSON.parseObject(JSON.toJSONString(standardTree), StandardTree.class));
                    } else {
                        treeList.addAll(treeList1);
        StandardTreePath path = StandardTreePathParser.parse(tree);
        if (path.getStandard() == null) {
            throw new BaseException("请选择标准节点");
                    }
                }
            }
            // 为每个展开后的“样品 + 型号”节点查询适用的检验项目。
            for (StandardTree standardTree2 : treeList) {
                String tree2 = trees[0] + " - " + trees[1] + " - " + trees[2] + " - " + standardTree2.getSample() + " - " + standardTree2.getModel();
                // 查询适用于样品类别的通用项目及当前样品/型号的项目。
                list.addAll(standardTreeMapper.selectStandardProductListByTree("\"" + trees[2] + "\"", standardTree2.getSample(), standardTree2.getModel(), tree2, trees[1]));
                // 查询同时限定样品类别和样品名称的项目。
                list.addAll(standardTreeMapper.selectStandardProductListByTree2("\"" + trees[2] + "\",\"" + standardTree2.getSample() + "\"", standardTree2.getSample(), standardTree2.getModel(), tree2, trees[1]));
            }
        } else if (trees.length == 4) {
            // 四级节点已定位到样品,后续按已保存的 sort 排序返回。
            isDrag = true;
            // 查询该样品已配置的型号节点。
            List<StandardTree> treeList = standardTreeMapper.selectList(Wrappers.<StandardTree>lambdaQuery().eq(StandardTree::getLaboratory, trees[1]).eq(StandardTree::getSampleType, trees[2]).eq(StandardTree::getSample, trees[3]));
            if (treeList.isEmpty()) {
                // 没有型号配置时,创建不含型号的节点,仍可查询通用项目。
                StandardTree standardTree = new StandardTree();
                standardTree.setFactory(trees[0]);
                standardTree.setLaboratory(trees[1]);
                standardTree.setSampleType(trees[2]);
                standardTree.setSample(trees[3]);
                treeList.add(standardTree);
            }
            // 针对样品的每个型号,合并通用项目和样品专属项目。
            for (StandardTree standardTree : treeList) {
                String str = tree + " - " + standardTree.getModel();
                list.addAll(standardTreeMapper.selectStandardProductListByTree("\"" + trees[2] + "\"", standardTree.getSample(), standardTree.getModel(), str, trees[1]));
                list.addAll(standardTreeMapper.selectStandardProductListByTree2("\"" + trees[2] + "\",\"" + trees[3] + "\"", standardTree.getSample(), standardTree.getModel(), str, trees[1]));
            }
        } else {
            // 五级节点已明确样品和型号,直接查询该节点适用的项目。
            isDrag = true;
            list.addAll(standardTreeMapper.selectStandardProductListByTree("\"" + trees[2] + "\"", trees[3].equals("null") ? null : trees[3], trees[4], tree, trees[1]));
            list.addAll(standardTreeMapper.selectStandardProductListByTree2("\"" + trees[2] + "\",\"" + trees[3] + "\"", trees[3].equals("null") ? null : trees[3], trees[4], tree, trees[1]));
        }
        // 为新生成的项目预先分配雪花 ID;匹配到旧配置后会替换为旧记录 ID。
        for (StandardProductList productList : list) {
            productList.setId(IdWorker.getId());
        }
        List<StandardProductList> standardProductLists;
        if (isDrag) {
            // 查询当前节点及其子节点的旧配置,并按 sort 读取以保留拖拽后的顺序。
            standardProductLists = standardProductListMapper.selectList(Wrappers.<StandardProductList>lambdaQuery()
        String canonicalTree = StandardTreePathParser.canonical(path.getIndustry(), path.getStandard());
        List<StandardProductList> generated = standardTreeMapper.selectStandardProductListByIndustry(
                path.getIndustry(), path.getStandard(), canonicalTree);
        List<StandardProductList> saved = standardProductListMapper.selectList(
                Wrappers.<StandardProductList>lambdaQuery()
                    .eq(StandardProductList::getStandardMethodListId, id)
                    .like(StandardProductList::getTree, tree)
                        .eq(StandardProductList::getTree, canonicalTree)
                    .orderByAsc(StandardProductList::getSort));
        } else {
            // 三级节点没有拖拽顺序,只读取用于覆盖默认值的旧配置。
            standardProductLists = standardProductListMapper.selectList(Wrappers.<StandardProductList>lambdaQuery()
                    .eq(StandardProductList::getStandardMethodListId, id)
                    .like(StandardProductList::getTree, tree));
        }
        // 将旧项目中人工维护的配置覆盖到本次重新生成的对应项目。
        for (StandardProductList sp : standardProductLists) {
            for (StandardProductList pl : list) {
                // 半径候选值只有一个时,将其作为默认半径。
                String radiusList = pl.getRadiusList();
                if (StringUtils.isNotBlank(radiusList) && !radiusList.equals("null") && !radiusList.equals("\"\"")) {
                    JSONArray jsonArray = JSON.parseArray(radiusList);
                    List<String> radius = jsonArray.toJavaList(String.class);
                    if (CollectionUtils.isNotEmpty(radius) && radius.size() == 1) {
                        pl.setRadius(radius.get(0));
        Map<Integer, StandardProductList> savedByParameterId = new HashMap<>();
        for (StandardProductList item : saved) {
            if (item.getStructureItemParameterId() != null) {
                savedByParameterId.put(item.getStructureItemParameterId(), item);
                    }
                }
                // 以检验项目、子项、型号、样品和结构参数 ID 判断新旧项目是否对应。
                if (Objects.equals(sp.getInspectionItem(), pl.getInspectionItem())
                        && Objects.equals((sp.getInspectionItemSubclass() == null) ? "" : sp.getInspectionItemSubclass(), pl.getInspectionItemSubclass() == null ? "" : pl.getInspectionItemSubclass())
//                        && Objects.equals(sp.getSample(), pl.getSample())
                        && Objects.equals(sp.getModel(), pl.getModel())
                        && sp.getTree().indexOf(pl.getSample() == null ? "null" : pl.getSample()) > -1
                        && Objects.equals(sp.getStructureItemParameterId(), pl.getStructureItemParameterId())) {
                    // 复用旧 ID 和排序,确保本次同步后原有配置仍关联到同一条项目记录。
                    pl.setId(sp.getId());
                    pl.setSort(sp.getSort());
                    // 旧记录存在值时优先保留;状态为空时按标准 ID 设置默认状态。
                    if (sp.getState() != null && !sp.getState().equals("")) {
                        pl.setState(sp.getState());
                    } else {
                        pl.setState(id == 0 ? 1 : 0);
                    }
                    if (sp.getMethodS() != null && !sp.getMethodS().equals("")) {
                        pl.setMethod(sp.getMethodS());
                    }
                    if (sp.getRadius() != null && !sp.getRadius().equals("")) {
                        pl.setRadius(sp.getRadius());
                    }
                    if (sp.getRates() != null && !sp.getRates().equals("")) {
                        pl.setRates(sp.getRates());
                    }
                    if (sp.getAsk() != null && !sp.getAsk().equals("")) {
                        pl.setAsk(sp.getAsk());
                    }
                    if (sp.getTell() != null && !sp.getTell().equals("")) {
                        pl.setTell(sp.getTell());
                    }
                    if (sp.getPrice() != null && !sp.getPrice().equals("")) {
                        pl.setPrice(sp.getPrice());
                    }
                    if (sp.getManHour() != null && !sp.getManHour().equals("")) {
                        pl.setManHour(sp.getManHour());
                    }
                    if (sp.getSection() != null && !sp.getSection().equals("")) {
                        pl.setSection(sp.getSection());
                    }
                    if (sp.getCores() != null && !sp.getCores().equals("")) {
                        pl.setCores(sp.getCores());
                    }
                    if (sp.getConductorMaterial() != null && !sp.getConductorMaterial().equals("")) {
                        pl.setConductorMaterial(sp.getConductorMaterial());
                    }
                    if (sp.getConductorType() != null && !sp.getConductorType().equals("")) {
                        pl.setConductorType(sp.getConductorType());
                    }
                    if (sp.getTemplateId() != null && !sp.getTemplateId().equals("")) {
                        pl.setTemplateId(sp.getTemplateId());
                    }
                    break;
                }
            }
        }
        // 记录本次同步的创建人和更新人。
        Integer userId = SecurityUtils.getUserId().intValue();
        if (trees.length == 5) {
            // 五级节点只重建当前精确路径的数据。
            standardProductListMapper.delete(Wrappers.<StandardProductList>lambdaUpdate()
                    .eq(StandardProductList::getStandardMethodListId, id)
                    .eq(StandardProductList::getTree, tree));
        for (StandardProductList item : generated) {
            applySingleRadiusDefault(item);
            StandardProductList old = savedByParameterId.get(item.getStructureItemParameterId());
            if (old != null && sameInspectionItem(old, item)) {
                mergeSavedConfiguration(old, item);
        } else {
            // 三级、四级节点重建当前路径及其所有子节点的数据。
            standardProductListMapper.delete(Wrappers.<StandardProductList>lambdaUpdate()
                item.setId(IdWorker.getId());
                item.setState(id == 0 ? 1 : 0);
            }
            item.setFactory(null);
            item.setLaboratory(path.getIndustry());
            item.setSampleType(null);
            item.setSample(path.getStandard());
            item.setModel(null);
            item.setTree(canonicalTree);
            item.setCreateUser(userId);
            item.setUpdateUser(userId);
            item.setStandardMethodListId(id);
        }
        standardProductListMapper.delete(Wrappers.<StandardProductList>lambdaQuery()
                    .eq(StandardProductList::getStandardMethodListId, id)
                    .like(StandardProductList::getTree, tree));
                .eq(StandardProductList::getTree, canonicalTree));
        if (CollectionUtils.isNotEmpty(generated)) {
            baseMapper.saveBatchProductLists(generated);
        }
        // 补齐批量保存所需的树节点、用户和检验标准字段。
        List<StandardProductList> productLists = list.stream().map(a -> {
            a.setFactory(trees[0]);
            a.setLaboratory(trees[1]);
            a.setSampleType(trees[2]);
            a.setCreateUser(userId);
            a.setUpdateUser(userId);
            a.setStandardMethodListId(id);
            return a;
        }).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(productLists)) {
            // 批量写入重新生成后的检验项目。
            baseMapper.saveBatchProductLists(productLists);
        generated.sort((left, right) -> {
            int leftSort = left.getSort() == null ? Integer.MAX_VALUE : left.getSort();
            int rightSort = right.getSort() == null ? Integer.MAX_VALUE : right.getSort();
            if (leftSort != rightSort) {
                return Integer.compare(leftSort, rightSort);
        }
        // 先按工时分组中的数字升序排列;空分组排到最后。
        Collections.sort(list, (o1, o2) -> {
            String field1 = o1.getManHourGroup();
            String field2 = o2.getManHourGroup();
            boolean isEmpty1 = field1 == null || field1.isEmpty();
            boolean isEmpty2 = field2 == null || field2.isEmpty();
            if (isEmpty1 && isEmpty2) {
                return 0;
            } else if (isEmpty1) {
                return 1;
            } else if (isEmpty2) {
                return -1;
            } else {
                int num1 = extractNumber(field1);
                int num2 = extractNumber(field2);
                return Integer.compare(num1, num2);
            }
            return compareManHourGroup(left.getManHourGroup(), right.getManHourGroup());
        });
        if (isDrag) {
            // 四级、五级节点最终按已保存的拖拽排序覆盖工时分组排序。
            list.sort((o1, o2) -> (o1.getSort() == null ? 0 : o1.getSort())
                    - (o2.getSort() == null ? 0 : o2.getSort()));
        }
        // 按前端约定返回项目列表和数量。
        String search = keyword == null ? "" : keyword.trim().toLowerCase(Locale.ROOT);
        List<StandardProductList> filtered = generated.stream()
                .filter(item -> search.isEmpty()
                        || containsIgnoreCase(item.getInspectionItem(), search)
                        || containsIgnoreCase(item.getInspectionItemSubclass(), search))
                .collect(Collectors.toList());
        int total = filtered.size();
        int currentPage = page == null || page < 1 ? 1 : page;
        int fromIndex = Math.min((currentPage - 1) * 100, total);
        int toIndex = Math.min(fromIndex + 100, total);
        Map<String, Object> map = new HashMap<>();
        map.put("productList", list);
        map.put("total", list.size());
        map.put("productList", new ArrayList<>(filtered.subList(fromIndex, toIndex)));
        map.put("total", total);
        return map;
    }
    private int extractNumber(String s) {
        // 从字符串中提取数字的逻辑,这里假设字段的格式是 "text<number>"
        String number = s;
        if (!s.matches("\\d+")) {
            number = s.replaceAll("\\D", "");
    private boolean sameInspectionItem(StandardProductList left, StandardProductList right) {
        return Objects.equals(left.getInspectionItem(), right.getInspectionItem())
                && Objects.equals(defaultString(left.getInspectionItemSubclass()), defaultString(right.getInspectionItemSubclass()));
        }
    private void applySingleRadiusDefault(StandardProductList item) {
        String radiusList = item.getRadiusList();
        if (StringUtils.isBlank(radiusList) || "null".equals(radiusList) || "\"\"".equals(radiusList)) {
            return;
        }
        try {
            List<String> values = JSON.parseArray(radiusList, String.class);
            if (values != null && values.size() == 1) {
                item.setRadius(values.get(0));
            }
        } catch (Exception ignored) {
            // 历史脏数据不影响检验项列表生成。
        }
    }
    private void mergeSavedConfiguration(StandardProductList old, StandardProductList target) {
        target.setId(old.getId());
        target.setSort(old.getSort());
        target.setState(old.getState() == null ? 0 : old.getState());
        if (StringUtils.isNotBlank(old.getMethodS())) {
            target.setMethodS(old.getMethodS());
            target.setMethod(old.getMethodS());
        }
        if (StringUtils.isNotBlank(old.getRadius())) target.setRadius(old.getRadius());
        if (StringUtils.isNotBlank(old.getRates())) target.setRates(old.getRates());
        if (StringUtils.isNotBlank(old.getAsk())) target.setAsk(old.getAsk());
        if (StringUtils.isNotBlank(old.getTell())) target.setTell(old.getTell());
        if (StringUtils.isNotBlank(old.getPrice())) target.setPrice(old.getPrice());
        if (StringUtils.isNotBlank(old.getManHour())) target.setManHour(old.getManHour());
        if (StringUtils.isNotBlank(old.getSection())) target.setSection(old.getSection());
        if (StringUtils.isNotBlank(old.getCores())) target.setCores(old.getCores());
        if (StringUtils.isNotBlank(old.getConductorMaterial())) target.setConductorMaterial(old.getConductorMaterial());
        if (StringUtils.isNotBlank(old.getConductorType())) target.setConductorType(old.getConductorType());
        if (old.getTemplateId() != null) target.setTemplateId(old.getTemplateId());
    }
    private int compareManHourGroup(String left, String right) {
        boolean leftEmpty = StringUtils.isBlank(left);
        boolean rightEmpty = StringUtils.isBlank(right);
        if (leftEmpty && rightEmpty) return 0;
        if (leftEmpty) return 1;
        if (rightEmpty) return -1;
        return Integer.compare(extractNumber(left), extractNumber(right));
    }
    private boolean containsIgnoreCase(String value, String search) {
        return value != null && value.toLowerCase(Locale.ROOT).contains(search);
    }
    private String defaultString(String value) {
        return value == null ? "" : value;
    }
    private int extractNumber(String s) {
        String number = s == null ? "" : s.replaceAll("\\D", "");
        if (number.isEmpty()) {
            return Integer.MAX_VALUE;
        }
        try {
        return Integer.parseInt(number);
        } catch (NumberFormatException ignored) {
            return Integer.MAX_VALUE;
        }
    }
    @Override