gongchunyi
2 天以前 0a1f000d5031c090059d5ae960019825196d4ba9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package com.ruoyi.production.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.production.pojo.ProductMaterial;
import com.ruoyi.production.pojo.ProductMaterialSku;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.production.dto.BomImportDto;
import com.ruoyi.production.dto.ProductBomDto;
import com.ruoyi.production.dto.ProductStructureDto;
import com.ruoyi.production.mapper.ProductBomMapper;
import com.ruoyi.production.pojo.ProductBom;
import com.ruoyi.production.pojo.ProductProcess;
import com.ruoyi.production.pojo.ProductStructure;
import com.ruoyi.production.service.*;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * BOM主表 服务实现类
 * </p>
 *
 * @author 芯导软件(江苏)有限公司
 * @since 2026-01-15 09:59:27
 */
@Service
public class ProductBomServiceImpl extends ServiceImpl<ProductBomMapper, ProductBom> implements ProductBomService {
 
    @Autowired
    private ProductBomMapper productBomMapper;
 
    @Autowired
    private ProductStructureService productStructureService;
 
    @Autowired
    private ProductProcessService productProcessService;
 
    @Autowired
    private ProductMaterialService productMaterialService;
 
    @Autowired
    private ProductMaterialSkuService productMaterialSkuService;
 
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
 
    @Override
    public IPage<ProductBomDto> listPage(Page<ProductBom> page, ProductBomDto productBomDto) {
        return productBomMapper.listPage(page, productBomDto);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(ProductBom productBom) {
        if (productBom == null || productBom.getDictCode() == null) {
            throw new ServiceException("新增BOM失败,产品类型不能为空");
        }
 
        SysDictData sysDictData = sysDictDataMapper.selectDictDataById(productBom.getDictCode());
        if (sysDictData == null) {
            throw new ServiceException("新增BOM失败,产品类型不存在");
        }
 
        boolean save = productBomMapper.insert(productBom) > 0;
        if (save) {
            String no = "BM." + String.format("%05d", productBom.getId());
            productBom.setBomNo(no);
            productBomMapper.updateById(productBom);
 
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult uploadBom(MultipartFile file, Long dictCode) {
        if (dictCode == null) {
            return AjaxResult.error("导入失败,产品类型不能为空");
        }
        SysDictData sysDictData = sysDictDataMapper.selectDictDataById(dictCode);
        if (sysDictData == null) {
            return AjaxResult.error("导入失败,产品类型不存在");
        }
        ExcelUtil<BomImportDto> util = new ExcelUtil<>(BomImportDto.class);
        List<BomImportDto> list;
        try {
            list = util.importExcel(file.getInputStream());
        } catch (Exception e) {
            return AjaxResult.error("Excel解析失败");
        }
 
        if (list == null || list.isEmpty()) {
            return AjaxResult.error("数据为空");
        }
 
        list.forEach(dto -> {
            dto.setParentName(clean(dto.getParentName()));
            dto.setParentSpec(clean(dto.getParentSpec()));
            dto.setChildName(clean(dto.getChildName()));
            dto.setChildSpec(clean(dto.getChildSpec()));
            dto.setProcess(clean(dto.getProcess()));
        });
 
        Set<String> processNames = list.stream()
                .map(BomImportDto::getProcess)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());
 
        Map<String, Long> processMap = new HashMap<>();
        if (!processNames.isEmpty()) {
            List<ProductProcess> exists = productProcessService.list(
                    new LambdaQueryWrapper<ProductProcess>().in(ProductProcess::getName, processNames)
            );
            processMap = exists.stream().collect(Collectors.toMap(ProductProcess::getName, ProductProcess::getId, (k1, k2) -> k1));
 
            Map<String, Long> finalProcessMap = processMap;
            List<String> missingProcesses = processNames.stream()
                    .filter(n -> !finalProcessMap.containsKey(n))
                    .collect(Collectors.toList());
 
            if (!missingProcesses.isEmpty()) {
                throw new ServiceException("导入失败,以下工序不存在:" + String.join(", ", missingProcesses));
            }
        }
 
        Set<String> materialKeys = new HashSet<>();
        for (BomImportDto dto : list) {
            if (StringUtils.isNotBlank(dto.getParentName())) {
                materialKeys.add(dto.getParentName() + "|" + (dto.getParentSpec() == null ? "" : dto.getParentSpec()));
            }
            if (StringUtils.isNotBlank(dto.getChildName())) {
                materialKeys.add(dto.getChildName() + "|" + (dto.getChildSpec() == null ? "" : dto.getChildSpec()));
            }
        }
 
        Map<String, ProductMaterialSku> skuMap = validateAndGetSkuMap(materialKeys);
 
        ProductBom bom = new ProductBom();
        bom.setDictCode(dictCode);
        bom.setVersion("1.0");
        productBomMapper.insert(bom);
        bom.setBomNo("BM." + String.format("%05d", bom.getId()));
        productBomMapper.updateById(bom);
 
        //  记录已经插入结构的节点:Key = "名称+规格", Value = structure_id
        Map<String, Long> treePathMap = new HashMap<>();
 
        for (BomImportDto dto : list) {
            String parentName = dto.getParentName();
            String parentSpec = dto.getParentSpec();
            String childName = dto.getChildName();
            String childSpec = dto.getChildSpec();
 
            String parentKey = parentName + "|" + (parentSpec == null ? "" : parentSpec);
            String childKey = childName + "|" + (childSpec == null ? "" : childSpec);
 
            //  处理顶级节点 (子项及其规格均为空当作顶级节点定义)
            if (StringUtils.isBlank(childName) && StringUtils.isBlank(childSpec)) {
                if (!treePathMap.containsKey(parentKey)) {
                    ProductMaterialSku model = skuMap.get(parentKey);
                    ProductStructure node = saveStructure(bom.getId(), null, model, dto.getUnitQty(), null);
                    treePathMap.put(parentKey, node.getId());
                } else {
                    // 如果已经存在,仅在它是顶级节点时更新
                    Long structureId = treePathMap.get(parentKey);
                    ProductStructure node = productStructureService.getById(structureId);
                    if (node != null && node.getParentId() == null && dto.getUnitQty() != null) {
                        node.setUnitQuantity(dto.getUnitQty());
                        productStructureService.updateById(node);
                    }
                }
                continue;
            }
 
            //  处理父子层级关系
            Long parentStructureId = treePathMap.get(parentKey);
            if (parentStructureId == null) {
                // 如果 Map 里找不到父节点,视为顶级父节点
                ProductMaterialSku parentModel = skuMap.get(parentKey);
                ProductStructure parentNode = saveStructure(bom.getId(), null, parentModel, BigDecimal.ONE, null);
                parentStructureId = parentNode.getId();
                treePathMap.put(parentKey, parentStructureId);
            }
 
            //  获取子项模型信息
            ProductMaterialSku childModel = skuMap.get(childKey);
            Long processId = null;
            if (StringUtils.isNotBlank(dto.getProcess())) {
                processId = processMap.get(dto.getProcess());
            }
            // 插入子节点结构表
            ProductStructure childNode = saveStructure(bom.getId(), parentStructureId, childModel, dto.getUnitQty(), processId);
            // 把当前子项记录到 Map,作为以后更深层级的父项查找依据
            treePathMap.put(childKey, childNode.getId());
        }
 
        return AjaxResult.success("BOM导入成功");
    }
 
    /**
     * 保存结构节点
     */
    private ProductStructure saveStructure(Integer bomId, Long parentId, ProductMaterialSku model, BigDecimal qty, Long processId) {
        ProductStructure node = new ProductStructure();
        node.setBomId(bomId);
        node.setParentId(parentId);
        node.setProductModelId(model.getId());
        node.setUnitQuantity(qty != null ? qty : BigDecimal.ONE);
        ProductMaterial material = productMaterialService.getById(model.getProductId());
        node.setUnit(material != null ? material.getUnit() : null);
        node.setProcessId(processId);
        productStructureService.save(node);
        return node;
    }
 
 
    @Override
    public void exportBom(HttpServletResponse response, Integer bomId) {
        if (bomId == null) {
            return;
        }
 
        List<ProductStructureDto> treeData = productStructureService.listByBomId(bomId);
        if (treeData == null || treeData.isEmpty()) {
            return;
        }
 
        //  将树形结构扁平化 使用 BFS算法 导出,按层级顺序
        List<BomImportDto> exportList = new ArrayList<>();
 
        // Map<ID, Node> idMap 用于查找父节点
        Map<Long, ProductStructureDto> idMap = new HashMap<>();
        populateMap(treeData, idMap);
 
        //  treeData 的第一个是根节点
        for (ProductStructureDto root : treeData) {
            //  添加根节点
            BomImportDto rootRow = new BomImportDto();
            rootRow.setParentName(root.getProductName());
            rootRow.setParentSpec(root.getModel());
            rootRow.setUnitQty(root.getUnitQuantity());
            rootRow.setRemark("");
            exportList.add(rootRow);
 
            //  BFS 遍历-队列
            Queue<ProductStructureDto> queue = new LinkedList<>();
            if (root.getChildren() != null) {
                queue.addAll(root.getChildren());
            }
 
            while (!queue.isEmpty()) {
                ProductStructureDto child = queue.poll();
 
                // 查找父节点
                ProductStructureDto parent = idMap.get(child.getParentId());
                if (parent == null) {
                    // 除了最外层节点,其他节点的父类肯定是不会为空的
                    continue;
                }
 
                BomImportDto row = new BomImportDto();
                // 父类信息
                row.setParentName(parent.getProductName());
                row.setParentSpec(parent.getModel());
                // 子类信息
                row.setChildName(child.getProductName());
                row.setChildSpec(child.getModel());
                row.setUnitQty(child.getUnitQuantity());
                row.setProcess(child.getProcessName());
 
                exportList.add(row);
 
                //  将子节点的子节点加入队列-下一层
                if (child.getChildren() != null && !child.getChildren().isEmpty()) {
                    queue.addAll(child.getChildren());
                }
            }
        }
 
        ExcelUtil<BomImportDto> util = new ExcelUtil<>(BomImportDto.class);
        util.exportExcel(response, exportList, "BOM结构导出");
    }
 
    @Override
    public String strengthById(Long bomId) {
        if (bomId == null) {
            return null;
        }
        return baseMapper.selectStrengthById(bomId);
    }
 
    private void populateMap(List<ProductStructureDto> nodes, Map<Long, ProductStructureDto> map) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }
        for (ProductStructureDto node : nodes) {
            map.put(node.getId(), node);
            populateMap(node.getChildren(), map);
        }
    }
 
 
    /**
     * 批量验证并获取产品SKU信息
     */
    private Map<String, ProductMaterialSku> validateAndGetSkuMap(Set<String> materialKeys) {
        if (materialKeys == null || materialKeys.isEmpty()) {
            return Collections.emptyMap();
        }
 
        // 1. 获取所有产品名称并查询
        Set<String> productNames = materialKeys.stream()
                .map(k -> k.split("\\|")[0])
                .collect(Collectors.toSet());
 
        List<ProductMaterial> products = productMaterialService.list(
                new LambdaQueryWrapper<ProductMaterial>().in(ProductMaterial::getProductName, productNames)
        );
        Map<String, ProductMaterial> productMap = products.stream()
                .collect(Collectors.toMap(ProductMaterial::getProductName, p -> p, (k1, k2) -> k1));
 
        // 检查缺失的产品
        List<String> missingProducts = productNames.stream()
                .filter(n -> !productMap.containsKey(n))
                .collect(Collectors.toList());
        if (!missingProducts.isEmpty()) {
            throw new ServiceException("导入失败,以下产品未维护:" + String.join(", ", missingProducts));
        }
 
        // 2. 查询所有相关的 SKU
        // 构造查询:(productId = ? AND model = ?) OR (productId = ? AND model = ?) ...
        // 由于 MyBatis Plus 的 Or 嵌套可能较慢且此处数量通常可控,我们可以先查出所有这些 Product 的所有 SKU
        List<Long> productIds = products.stream().map(ProductMaterial::getId).collect(Collectors.toList());
        List<ProductMaterialSku> skus = productMaterialSkuService.list(
                new LambdaQueryWrapper<ProductMaterialSku>().in(ProductMaterialSku::getProductId, productIds)
        );
 
        // 构建 Map: "产品名称|规格" -> Sku
        Map<String, ProductMaterialSku> skuMap = new HashMap<>();
        for (ProductMaterialSku sku : skus) {
            ProductMaterial p = productMap.values().stream()
                    .filter(pm -> pm.getId().equals(sku.getProductId()))
                    .findFirst().orElse(null);
            if (p != null) {
                String key = p.getProductName() + "|" + (sku.getModel() == null ? "" : sku.getModel());
                skuMap.put(key, sku);
            }
        }
 
        // 检查缺失的规格
        List<String> missingSkus = materialKeys.stream()
                .filter(k -> !skuMap.containsKey(k))
                .map(k -> {
                    String[] parts = k.split("\\|");
                    return parts[0] + "[" + (parts.length > 1 ? parts[1] : "") + "]";
                })
                .collect(Collectors.toList());
 
        if (!missingSkus.isEmpty()) {
            throw new ServiceException("导入失败,以下产品规格未维护:" + String.join(", ", missingSkus));
        }
 
        return skuMap;
    }
 
    private String clean(String s) {
        if (s == null) return null;
        return s.replaceAll("[\\u00A0\\u3000]", "").trim();
    }
}