zss
2 天以前 0a73b4d40662ea554bdf80b22966901da1abb424
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
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.basic.pojo.Product;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.basic.service.IProductModelService;
import com.ruoyi.basic.service.IProductService;
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.ProductBomService;
import com.ruoyi.production.service.ProductProcessService;
import com.ruoyi.production.service.ProductStructureService;
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 IProductService productService;
 
    @Autowired
    private ProductBomMapper productBomMapper;
 
 
    @Autowired
    private IProductModelService productModelService;
 
    @Autowired
    private ProductStructureService productStructureService;
 
    @Autowired
    private ProductProcessService productProcessService;
 
    @Override
    public IPage<ProductBomDto> listPage(Page page, ProductBomDto productBomDto) {
        return productBomMapper.listPage(page, productBomDto);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(ProductBom productBom) {
        boolean save = productBomMapper.insert(productBom) > 0;
        if (save) {
            String no = "BM." + String.format("%05d", productBom.getId());
            productBom.setBomNo(no);
            productBomMapper.updateById(productBom);
 
            //  查询出产品模型信息
            if (productBom.getProductModelId() == null) {
                throw new ServiceException("请选择产品模型");
            }
 
            ProductModel productModel = productModelService.getById(productBom.getProductModelId());
            if (productModel == null) {
                throw new ServiceException("选择的产品模型不存在");
            }
 
            //  添加初始的产品结构
            ProductStructure productStructure = new ProductStructure();
            productStructure.setProductModelId(productBom.getProductModelId());
            productStructure.setUnit(productModel.getUnit());
            productStructure.setUnitQuantity(BigDecimal.valueOf(1));
            productStructure.setBomId(productBom.getId());
 
            productStructureService.save(productStructure);
 
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult uploadBom(MultipartFile file) {
        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()));
        });
        handleProcess(list);
        Map<String, Long> processMap = productProcessService.list().stream()
                .collect(Collectors.toMap(ProductProcess::getName, ProductProcess::getId, (k1, k2) -> k1));
 
        //  创建 BOM 数据
        BomImportDto first = list.get(0);
        ProductModel rootModel = findModel(first.getParentName(), first.getParentSpec());
        ProductBom bom = new ProductBom();
        bom.setProductModelId(rootModel.getId());
        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 (int i = 0; i < list.size(); i++) {
            BomImportDto dto = list.get(i);
            String parentKey = dto.getParentName() + "|" + dto.getParentSpec();
            String childKey = dto.getChildName() + "|" + dto.getChildSpec();
 
            //处理根节点,第一行且子项为空
            if (i == 0 && StringUtils.isBlank(dto.getChildName())) {
                ProductStructure rootNode = new ProductStructure();
                rootNode.setBomId(bom.getId());
                rootNode.setParentId(null); // 顶层没有父节点
                rootNode.setProductModelId(rootModel.getId());
                rootNode.setUnitQuantity(BigDecimal.ONE);
                rootNode.setUnit(rootModel.getUnit());
                productStructureService.save(rootNode);
 
                treePathMap.put(parentKey, rootNode.getId());
                continue;
            }
 
            //  处理子层级节点
            //  找到父节点在数据库里的 ID
            Long parentStructureId = treePathMap.get(parentKey);
            if (parentStructureId == null) {
                // 如果 Map 里找不到,说明 Excel 顺序乱了或者数据有误
                throw new ServiceException("导入失败: 父项[" + dto.getParentName() + "]必须在其子项之前定义");
            }
 
            //  获取子项模型信息
            ProductModel childModel = findModel(dto.getChildName(), dto.getChildSpec());
 
            //  插入结构表
            ProductStructure node = new ProductStructure();
            node.setBomId(bom.getId());
            node.setParentId(parentStructureId); // 父节点ID
            node.setProductModelId(childModel.getId());
            node.setUnitQuantity(dto.getUnitQty());
            node.setUnit(childModel.getUnit());
            if (processMap.containsKey(dto.getProcess())) {
                node.setProcessId(processMap.get(dto.getProcess()));
            }
            productStructureService.save(node);
 
            //  把当前子项记录到 Map,作为以后更深层级的父项查找依据
            //  同一父项下的同名子项不需要重复记录
            treePathMap.put(childKey, node.getId());
        }
 
        return AjaxResult.success("BOM导入成功");
    }
 
 
    @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结构导出");
    }
 
    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);
        }
    }
 
    private ProductModel findModel(String name, String spec) {
        Product product = productService.getOne(new LambdaQueryWrapper<Product>()
                .eq(Product::getProductName, name).last("limit 1"));
        if (product == null) throw new ServiceException("产品未维护:" + name);
 
        ProductModel model = productModelService.getOne(new LambdaQueryWrapper<ProductModel>()
                .eq(ProductModel::getProductId, product.getId())
                .eq(ProductModel::getModel, spec).last("limit 1"));
        if (model == null) throw new ServiceException("规格未维护:" + name + "[" + spec + "]");
        return model;
    }
 
    private void handleProcess(List<BomImportDto> list) {
 
        Set<String> processNames = list.stream()
                .map(BomImportDto::getProcess)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());
 
        if (processNames.isEmpty()) {
            return;
        }
 
        List<ProductProcess> exists = productProcessService.list(
                new LambdaQueryWrapper<ProductProcess>().in(ProductProcess::getName, processNames)
        );
 
        Set<String> existNames = exists.stream()
                .map(ProductProcess::getName)
                .collect(Collectors.toSet());
 
        List<ProductProcess> needSave = processNames.stream()
                .filter(n -> !existNames.contains(n))
                .map(n -> {
                    ProductProcess p = new ProductProcess();
                    p.setName(n);
                    return p;
                })
                .collect(Collectors.toList());
 
        if (!needSave.isEmpty()) {
            productProcessService.saveBatch(needSave);
            needSave.forEach(p -> p.setNo("GX" + String.format("%08d", p.getId())));
            productProcessService.updateBatchById(needSave);
        }
    }
 
    private String clean(String s) {
        if (s == null) return null;
        return s.replaceAll("[\\u00A0\\u3000]", "").trim();
    }
}