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.core.toolkit.CollectionUtils;
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;
/**
*
* BOM主表 服务实现类
*
*
* @author 芯导软件(江苏)有限公司
* @since 2026-01-15 09:59:27
*/
@Service
public class ProductBomServiceImpl extends ServiceImpl 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 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();
}
/**
* 递归保存 BOM:先保存父项 → 保存子项 → 建立关系 → 递归子项的子项
* @param children 当前父项的子项列表
* @return 保存后的父项产品ID
*/
private void saveBomRecursive(List children,ProductBom bom,ProductModel rootModel,Map processMap) {
// 1. 获取children中子项产品编号为空的数据
List parentChildren = children
.stream()
.filter(child -> StringUtils.isEmpty(child.getChildCode()))
.collect(Collectors.toList());
if(CollectionUtils.isEmpty(parentChildren)){
throw new ServiceException("请选择父项产品编号");
}
BomImportDto parentId = parentChildren.get(0); // 父级数据
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);
// 2. 遍历子项,逐个处理
for (BomImportDto child : children) {
// 跳过没有子项的父项
if(StringUtils.isEmpty(child.getChildCode())){
continue;
}
// 获取子项模型信息
ProductModel childModel = findModel(child.getChildName(), child.getChildSpec());
// 插入结构表
ProductStructure node = new ProductStructure();
node.setBomId(bom.getId());
node.setParentId(rootNode.getId()); // 父节点ID
node.setProductModelId(childModel.getId());
node.setUnitQuantity(child.getUnitQty());
node.setUnit(childModel.getUnit());
if (processMap.containsKey(child.getProcess())) {
node.setProcessId(processMap.get(child.getProcess()));
}
productStructureService.save(node);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public AjaxResult uploadBom(MultipartFile file) {
ExcelUtil util = new ExcelUtil<>(BomImportDto.class);
List 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 processMap = productProcessService.list().stream()
.collect(Collectors.toMap(ProductProcess::getName, ProductProcess::getId, (k1, k2) -> k1));
// 1. 按父项编码分组
Map> parentMap = list.stream()
.filter(bom -> StringUtils.isNotBlank(bom.getParentCode()))
.collect(Collectors.groupingBy(BomImportDto::getParentCode));
// 2. 遍历所有父项,递归保存
for (Map.Entry> entry : parentMap.entrySet()) {
// 创建 BOM 数据
BomImportDto first = entry.getValue().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);
// 处理bom子表数据
List children = entry.getValue();
saveBomRecursive(children,bom,rootModel,processMap);
}
return AjaxResult.success("BOM导入成功");
}
@Override
public void exportBom(HttpServletResponse response, Integer bomId) {
if (bomId == null) {
return;
}
List treeData = productStructureService.listBybomId(bomId);
if (treeData == null || treeData.isEmpty()) {
return;
}
// 将树形结构扁平化 使用 BFS算法 导出,按层级顺序
List exportList = new ArrayList<>();
// Map idMap 用于查找父节点
Map 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 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 util = new ExcelUtil<>(BomImportDto.class);
util.exportExcel(response, exportList, "BOM结构导出");
}
private void populateMap(List nodes, Map 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()
// .eq(Product::getProductName, name).last("limit 1"));
// if (product == null) throw new ServiceException("产品未维护:" + name);
ProductModel model = productModelService.getOne(new LambdaQueryWrapper()
// .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 list) {
Set processNames = list.stream()
.map(BomImportDto::getProcess)
.filter(StringUtils::isNotBlank)
.collect(Collectors.toSet());
if (processNames.isEmpty()) {
return;
}
List exists = productProcessService.list(
new LambdaQueryWrapper().in(ProductProcess::getName, processNames)
);
Set existNames = exists.stream()
.map(ProductProcess::getName)
.collect(Collectors.toSet());
List 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();
}
}