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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package com.ruoyi.stock.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.dto.ProductDto;
import com.ruoyi.basic.dto.ProductTreeDto;
import com.ruoyi.basic.mapper.ProductMapper;
import com.ruoyi.basic.mapper.ProductModelMapper;
import com.ruoyi.basic.pojo.Product;
import com.ruoyi.common.enums.StockInQualifiedRecordTypeEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.domain.R;
import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
import com.ruoyi.stock.dto.StockInRecordDto;
import com.ruoyi.stock.dto.StockInventoryDto;
import com.ruoyi.stock.dto.StockOutRecordDto;
import com.ruoyi.stock.execl.StockInventoryExportData;
import com.ruoyi.stock.mapper.StockInventoryMapper;
import com.ruoyi.stock.pojo.StockInventory;
import com.ruoyi.stock.service.StockInRecordService;
import com.ruoyi.stock.service.StockInventoryService;
import com.ruoyi.stock.service.StockOutRecordService;
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.*;
 
/**
 * <p>
 * 库存表 服务实现类
 * </p>
 *
 * @author 芯导软件(江苏)有限公司
 * @since 2026-01-21 04:16:36
 */
@Service
public class StockInventoryServiceImpl extends ServiceImpl<StockInventoryMapper, StockInventory> implements StockInventoryService {
 
    @Autowired
    private  StockInventoryMapper stockInventoryMapper;
    @Autowired
    private StockInRecordService stockInRecordService;
    @Autowired
    private StockOutRecordService stockOutRecordService;
    @Autowired
    private SalesLedgerProductMapper salesLedgerProductMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductModelMapper productModelMapper;
 
 
    @Override
    public IPage<StockInventoryDto> pagestockInventory(Page page, StockInventoryDto stockInventoryDto) {
        return stockInventoryMapper.pagestockInventory(page, stockInventoryDto);
    }
 
    //入库调用
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addstockInventory(StockInventoryDto stockInventoryDto) {
        //新增入库记录再添加库存
        if (stockInventoryDto.getRecordType() != null) {
            StockInRecordDto stockInRecordDto = new StockInRecordDto();
            stockInRecordDto.setRecordId(stockInventoryDto.getRecordId());
            stockInRecordDto.setRecordType(stockInventoryDto.getRecordType());
            stockInRecordDto.setStockInNum(stockInventoryDto.getQualitity());
            stockInRecordDto.setProductModelId(stockInventoryDto.getProductModelId());
            stockInRecordDto.setType("0");
            stockInRecordDto.setBatchNo(stockInventoryDto.getBatchNo());
            stockInRecordDto.setCustomer(stockInventoryDto.getCustomer());
            stockInRecordService.add(stockInRecordDto);
        }
        //再进行新增库存数量库存
        //先查询库存表中的产品是否存在,不存在新增,存在更新
        StockInventory oldStockInventory = stockInventoryMapper.selectOne(new QueryWrapper<StockInventory>().lambda()
                .eq(StockInventory::getProductModelId, stockInventoryDto.getProductModelId())
                .eq(StockInventory::getBatchNo, stockInventoryDto.getBatchNo())
                .eq(StockInventory::getCustomer, stockInventoryDto.getCustomer())
        );
        if (ObjectUtils.isEmpty(oldStockInventory)) {
            StockInventory newStockInventory = new StockInventory();
            newStockInventory.setProductModelId(stockInventoryDto.getProductModelId());
            newStockInventory.setQualitity(stockInventoryDto.getQualitity());
            newStockInventory.setVersion(1);
            newStockInventory.setRemark(stockInventoryDto.getRemark());
            newStockInventory.setLockedQuantity(stockInventoryDto.getLockedQuantity());
            newStockInventory.setWarnNum(stockInventoryDto.getWarnNum());
            newStockInventory.setBatchNo(stockInventoryDto.getBatchNo());
            newStockInventory.setCustomer(stockInventoryDto.getCustomer());
            stockInventoryMapper.insert(newStockInventory);
        }else {
             stockInventoryMapper.updateAddStockInventory(stockInventoryDto);
        }
        return true;
    }
 
    //出库调用
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean subtractStockInventory(StockInventoryDto stockInventoryDto) {
        //  新增出库记录
        if (stockInventoryDto.getRecordType() != null) {
            StockOutRecordDto stockOutRecordDto = new StockOutRecordDto();
            stockOutRecordDto.setRecordId(stockInventoryDto.getRecordId());
            stockOutRecordDto.setRecordType(stockInventoryDto.getRecordType());
            stockOutRecordDto.setStockOutNum(stockInventoryDto.getQualitity());
            stockOutRecordDto.setProductModelId(stockInventoryDto.getProductModelId());
            stockOutRecordDto.setBatchNo(stockInventoryDto.getBatchNo());
            stockOutRecordDto.setCustomer(stockInventoryDto.getCustomer());
            stockOutRecordDto.setType("0");
            stockOutRecordService.add(stockOutRecordDto);
        }
        StockInventory oldStockInventory = stockInventoryMapper.selectOne(new QueryWrapper<StockInventory>().lambda()
                .eq(StockInventory::getProductModelId, stockInventoryDto.getProductModelId())
                .eq(StockInventory::getBatchNo, stockInventoryDto.getBatchNo())
                .eq(StockInventory::getCustomer, stockInventoryDto.getCustomer())
        );
        if (ObjectUtils.isEmpty(oldStockInventory)) {
            throw new RuntimeException("产品库存不存在");
        }
        BigDecimal lockedQty = oldStockInventory.getLockedQuantity();
        if (lockedQty == null) {
            lockedQty = BigDecimal.ZERO;
        }
        if (stockInventoryDto.getQualitity().compareTo(oldStockInventory.getQualitity().subtract(lockedQty)) > 0) {
            throw new RuntimeException("库存不足无法出库");
        }
 
        stockInventoryMapper.updateSubtractStockInventory(stockInventoryDto);
        return true;
    }
 
    @Override
    public R importStockInventory(MultipartFile file) {
        try {
            // 查询所有的产品
            List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectProduct();
 
            ExcelUtil<StockInventoryExportData> util = new ExcelUtil<StockInventoryExportData>(StockInventoryExportData.class);
            List<StockInventoryExportData> list = util.importExcel(file.getInputStream());
 
            // 记录未找到匹配项的数据
            List<String> unmatchedRecords = new ArrayList<>();
 
            list.forEach(dto -> {
                boolean matched = false;
                for (SalesLedgerProduct item : salesLedgerProducts) {
                    if (item.getProductCategory().equals(dto.getProductName()) &&
                            item.getSpecificationModel().equals(dto.getModel())) {
                        StockInventoryDto stockInventoryDto = new StockInventoryDto();
                        stockInventoryDto.setRecordId(0L);
                        stockInventoryDto.setRecordType(StockInQualifiedRecordTypeEnum.CUSTOMIZATION_STOCK_IN.getCode());
                        stockInventoryDto.setQualitity(dto.getQualitity());
                        stockInventoryDto.setRemark(dto.getRemark());
                        stockInventoryDto.setWarnNum(dto.getWarnNum());
                        if (ObjectUtils.isNotEmpty(dto.getLockedQuantity())&&dto.getLockedQuantity().compareTo(dto.getQualitity())>0) {
                            throw new RuntimeException("冻结数量不能超过本次导入的库存数量");
                        }
                        stockInventoryDto.setLockedQuantity(dto.getLockedQuantity());
                        stockInventoryDto.setProductModelId(item.getProductModelId());
                        this.addstockInventory(stockInventoryDto);
                        matched = true;
                        break; // 找到匹配项后跳出循环
                    }
                }
                if (!matched) {
                    // 记录未匹配的数据
                    String unmatchedInfo = String.format("产品名称:%s,规格型号:%s",
                            dto.getProductName(), dto.getModel());
                    unmatchedRecords.add(unmatchedInfo);
                }
            });
            // 构建返回信息
            StringBuilder message = new StringBuilder();
            if (!unmatchedRecords.isEmpty()) {
                message.append("以下产品未找到匹配项:\n");
                for (String record : unmatchedRecords) {
                    message.append(record).append("\n");
                }
                throw new RuntimeException(message.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("导入失败:" + e.getMessage());
        }
        return R.ok("导入成功");
    }
 
 
    @Override
    public void exportStockInventory(HttpServletResponse response, StockInventoryDto stockInventoryDto) {
 
        List<StockInventoryExportData> list = stockInventoryMapper.listStockInventoryExportData(stockInventoryDto);
        ExcelUtil<StockInventoryExportData> util = new ExcelUtil<>(StockInventoryExportData.class);
        util.exportExcel(response,list, "库存信息");
    }
 
    @Override
    public IPage<StockInRecordDto> stockInventoryPage(StockInventoryDto stockInventoryDto, Page page) {
        return stockInventoryMapper.stockInventoryPage(stockInventoryDto,page);
    }
 
    @Override
    public IPage<StockInventoryDto> stockInAndOutRecord(StockInventoryDto stockInventoryDto, Page page) {
        return stockInventoryMapper.stockInAndOutRecord(stockInventoryDto,page);
    }
 
    @Override
    public Boolean frozenStock(StockInventoryDto stockInventoryDto) {
        StockInventory stockInventory = stockInventoryMapper.selectById(stockInventoryDto.getId());
        if (stockInventory.getQualitity().compareTo(stockInventoryDto.getLockedQuantity())<0) {
            throw new RuntimeException("冻结数量不能超过库存数量");
        }
        if (ObjectUtils.isEmpty(stockInventory.getLockedQuantity())) {
            stockInventory.setLockedQuantity(stockInventoryDto.getLockedQuantity());
        }else {
            stockInventory.setLockedQuantity(stockInventory.getLockedQuantity().add(stockInventoryDto.getLockedQuantity()));
        }
        return this.updateById(stockInventory);
    }
 
    @Override
    public Boolean thawStock(StockInventoryDto stockInventoryDto) {
        StockInventory stockInventory = stockInventoryMapper.selectById(stockInventoryDto.getId());
        if (stockInventory.getLockedQuantity().compareTo(stockInventoryDto.getLockedQuantity())<0) {
            throw new RuntimeException("解冻数量不能超过冻结数量");
        }
        stockInventory.setLockedQuantity(stockInventory.getLockedQuantity().subtract(stockInventoryDto.getLockedQuantity()));
        return this.updateById(stockInventory);
    }
 
    @Override
    public List<StockInventoryDto> getMaterials(StockInventoryDto stockInventoryDto) {
        return stockInventoryMapper.getMaterials(stockInventoryDto);
    }
 
    @Override
    public List<ProductTreeDto> getStockInventoryAll(ProductDto productDto) {
        // 查询库存列表
        List<StockInventoryDto> stockList = stockInventoryMapper.getStockInventoryAll(productDto);
 
        if (CollectionUtils.isEmpty(stockList)) {
            return new ArrayList<>();
        }
 
        // 构建产品树(基于产品表的父子关系)
        Map<Long, ProductTreeDto> productNodeMap = buildProductTree(stockList);
 
        // 将库存数据(型号->批次->客户)挂载到对应的产品节点下
        attachStockDataToProduct(productNodeMap, stockList);
 
        // 返回根节点
        List<ProductTreeDto> tree = new ArrayList<>();
        for (ProductTreeDto node : productNodeMap.values()) {
            if (node.getParentId() == null || node.getParentId() == 0) {
                tree.add(node);
            }
        }
 
        return tree;
    }
 
    /**
     * 构建产品树(自动递归查询所有父级,包含根节点)
     */
    private Map<Long, ProductTreeDto> buildProductTree(List<StockInventoryDto> stockList) {
        // 1. 收集所有需要加载的产品ID
        Set<Long> needQueryIds = new HashSet<>();
        for (StockInventoryDto stock : stockList) {
            if (stock.getProductId() != null) {
                needQueryIds.add(stock.getProductId());
            }
        }
 
        // 递归查询所有节点(直到根节点)
        Set<Long> allAncestors = getAllAncestorIds(needQueryIds);
        needQueryIds.addAll(allAncestors);
 
        // 批量查询所有产品(包含完整层级)
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Product::getId, needQueryIds);
        List<Product> products = productMapper.selectList(wrapper);
 
        // 构建节点Map
        Map<Long, ProductTreeDto> nodeMap = new HashMap<>();
        for (Product product : products) {
            ProductTreeDto node = new ProductTreeDto();
            node.setId(product.getId());
            node.setParentId(product.getParentId());
            node.setProductName(product.getProductName());
            node.setLabel(product.getProductName());
            node.setNodeType("product");
            node.setChildren(new ArrayList<>());
            nodeMap.put(product.getId(), node);
        }
 
        // 构建父子关系
        for (ProductTreeDto node : nodeMap.values()) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0 && nodeMap.containsKey(parentId)) {
                nodeMap.get(parentId).getChildren().add(node);
            }
        }
 
        return nodeMap;
    }
 
    /**
     * 递归查询所有产品的祖先ID(直到根节点)
     */
    private Set<Long> getAllAncestorIds(Set<Long> productIds) {
        Set<Long> ancestorIds = new HashSet<>();
        Queue<Long> queue = new LinkedList<>(productIds);
 
        while (!queue.isEmpty()) {
            Long currentId = queue.poll();
            Product product = productMapper.selectById(currentId);
            if (product == null) continue;
 
            Long parentId = product.getParentId();
            if (parentId != null && parentId != 0 && !ancestorIds.contains(parentId)) {
                ancestorIds.add(parentId);
                queue.add(parentId);
            }
        }
        return ancestorIds;
    }
 
    /**
     * 将库存数据(型号->批次->客户)挂载到产品节点下
     */
    private void attachStockDataToProduct(Map<Long, ProductTreeDto> productNodeMap,
                                          List<StockInventoryDto> stockList) {
        for (StockInventoryDto stock : stockList) {
            Long productId = stock.getProductId();
            if (productId == null || !productNodeMap.containsKey(productId)) {
                continue;
            }
 
            ProductTreeDto productNode = productNodeMap.get(productId);
 
            // 构建该产品的库存树(型号 -> 批次 -> 客户)
            ProductTreeDto stockTree = buildStockTree(stock);
 
            // 合并到产品节点的 children 中
            mergeStockTree(productNode.getChildren(), stockTree);
        }
    }
 
    /**
     * 构建单个库存的树结构(型号 -> 批次 -> 客户)
     */
    private ProductTreeDto buildStockTree(StockInventoryDto stock) {
        // 型号节点
        ProductTreeDto modelNode = new ProductTreeDto();
        modelNode.setModel(stock.getModel());
        modelNode.setUidNo(stock.getUidNo());
        modelNode.setUnit(stock.getUnit());
        modelNode.setProductModelId(stock.getProductModelId());
        modelNode.setLabel(stock.getModel());
        modelNode.setNodeType("model");
        modelNode.setChildren(new ArrayList<>());
 
        // 批次节点
        ProductTreeDto batchNode = new ProductTreeDto();
        String batchNo = StringUtils.isBlank(stock.getBatchNo()) ? "无批次" : stock.getBatchNo();
        batchNode.setBatchNo(batchNo);
        batchNode.setLabel("批次: " + batchNo);
        batchNode.setNodeType("batch");
        batchNode.setChildren(new ArrayList<>());
 
        // 客户节点
        ProductTreeDto customerNode = new ProductTreeDto();
        String customer = StringUtils.isBlank(stock.getCustomer()) ? "无客户" : stock.getCustomer();
        customerNode.setCustomer(customer);
        customerNode.setLabel(customer);
        customerNode.setNodeType("customer");
        customerNode.setChildren(new ArrayList<>());
 
        batchNode.getChildren().add(customerNode);
        modelNode.getChildren().add(batchNode);
 
        return modelNode;
    }
 
    /**
     * 合并库存树到产品节点的 children 中
     */
    private void mergeStockTree(List<ProductTreeDto> children, ProductTreeDto newStockTree) {
        if (children == null) {
            return;
        }
 
        // 查找是否已有相同型号的节点
        ProductTreeDto existingModelNode = null;
        for (ProductTreeDto child : children) {
            if (child.getNodeType().equals("model") &&
                    child.getModel() != null &&
                    child.getModel().equals(newStockTree.getModel())) {
                existingModelNode = child;
                break;
            }
        }
 
        if (existingModelNode == null) {
            // 没有相同型号,直接添加
            children.add(newStockTree);
        } else {
            // 有相同型号,合并批次节点
            ProductTreeDto newBatchNode = newStockTree.getChildren().get(0);
 
            // 查找是否已有相同批次
            ProductTreeDto existingBatchNode = null;
            for (ProductTreeDto batchChild : existingModelNode.getChildren()) {
                if (batchChild.getNodeType().equals("batch") &&
                        batchChild.getBatchNo() != null &&
                        batchChild.getBatchNo().equals(newBatchNode.getBatchNo())) {
                    existingBatchNode = batchChild;
                    break;
                }
            }
 
            if (existingBatchNode == null) {
                existingModelNode.getChildren().add(newBatchNode);
            } else {
                // 合并客户节点
                ProductTreeDto newCustomerNode = newBatchNode.getChildren().get(0);
                boolean customerExists = false;
                for (ProductTreeDto customerChild : existingBatchNode.getChildren()) {
                    if (customerChild.getNodeType().equals("customer") &&
                            customerChild.getCustomer() != null &&
                            customerChild.getCustomer().equals(newCustomerNode.getCustomer())) {
                        customerExists = true;
                        break;
                    }
                }
                if (!customerExists) {
                    existingBatchNode.getChildren().add(newCustomerNode);
                }
            }
        }
    }
}