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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package com.ruoyi.business.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.entity.CoalField;
import com.ruoyi.basic.entity.CoalInfo;
import com.ruoyi.basic.entity.CoalValue;
import com.ruoyi.basic.entity.Supply;
import com.ruoyi.basic.mapper.CoalFieldMapper;
import com.ruoyi.basic.mapper.CoalInfoMapper;
import com.ruoyi.basic.mapper.CoalValueMapper;
import com.ruoyi.basic.mapper.SupplyMapper;
import com.ruoyi.business.dto.OfficialInventoryDto;
import com.ruoyi.business.dto.SalesRecordDto;
import com.ruoyi.business.entity.OfficialInventory;
import com.ruoyi.business.entity.SalesRecord;
import com.ruoyi.business.mapper.OfficialInventoryMapper;
import com.ruoyi.business.service.OfficialInventoryService;
import com.ruoyi.business.utils.DynamicExcelUtil;
import com.ruoyi.business.vo.OfficialInventoryExportVo;
import com.ruoyi.business.vo.OfficialInventoryVo;
import com.ruoyi.business.vo.SalesRecordExportVo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.SysUserMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 正式库存表 服务实现类
 * </p>
 *
 * @author ruoyi
 * @since 2025-06-04
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OfficialInventoryServiceImpl extends ServiceImpl<OfficialInventoryMapper, OfficialInventory> implements OfficialInventoryService {
 
    private final OfficialInventoryMapper officialInventoryMapper;
 
    private final CoalValueMapper coalValueMapper;
 
    private final CoalFieldMapper coalFieldMapper;
 
    private final CoalInfoMapper coalInfoMapper;
 
    private final SupplyMapper supplyMapper;
 
    private final SysUserMapper sysUserMapper;
 
 
    @Override
    public IPage<OfficialInventoryDto> selectOfficialInventoryList(Page<OfficialInventory> page, OfficialInventoryDto officialInventoryDto) {
 
        //  先查出原始数据(OfficialInventory)
        LambdaQueryWrapper<OfficialInventory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(OfficialInventory::getCreateTime);
        IPage<OfficialInventory> entityPage = officialInventoryMapper.selectPage(page, queryWrapper);
 
        //  创建一个新的 Dto 分页结果
        IPage<OfficialInventoryDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(entityPage, dtoPage);
 
        List<OfficialInventoryDto> dtoList = new ArrayList<>();
 
        List<Long> supplierIds = entityPage.getRecords().stream()
                .map(OfficialInventory::getSupplierId)
                .toList();
 
        List<Long> registrantIds = entityPage.getRecords().stream()
                .map(OfficialInventory::getRegistrantId)
                .toList();
 
        Map<Long, Supply> supplyMap;
        if (!supplierIds.isEmpty()) {
            List<Supply> infos = supplyMapper.selectList(new LambdaQueryWrapper<Supply>().in(Supply::getId, supplierIds));
            supplyMap = infos.stream().collect(Collectors.toMap(Supply::getId, Function.identity()));
        } else {
            supplyMap = new HashMap<>();
        }
 
        //登记人
        Map<Long, SysUser> userMap;
        if (!registrantIds.isEmpty()) {
            List<SysUser> sysUsers = sysUserMapper.selectList(registrantIds);
            userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
        } else {
            userMap = new HashMap<>();
        }
 
        //  查询所有可用字段(CoalField)
        List<CoalField> coalFields = coalFieldMapper.selectList(null);
        List<String> allFieldNames = coalFields.stream()
                .map(CoalField::getFields)
                .distinct()
                .toList();
 
        //查询煤种ids
        List<Long> coalIds = entityPage.getRecords().stream()
                .map(OfficialInventory::getCoalId)
                .distinct()
                .toList();
 
        // 批量查询CoalInfo
        Map<Long, CoalInfo> coalInfoMap;
        if (!coalIds.isEmpty()) {
            List<CoalInfo> coalInfos = coalInfoMapper.selectList(new LambdaQueryWrapper<CoalInfo>().in(CoalInfo::getId, coalIds));
            coalInfoMap = coalInfos.stream().collect(Collectors.toMap(CoalInfo::getId, Function.identity()));
        } else {
            coalInfoMap = new HashMap<>();
        }
 
        //  遍历每条记录,进行转换并填充 fields
        for (OfficialInventory entity : entityPage.getRecords()) {
            OfficialInventoryDto dto = new OfficialInventoryDto();
            BeanUtils.copyProperties(entity, dto);
 
            // 供应商信息
            Supply supply = supplyMap.get(entity.getSupplierId());
            if (supply != null) {
                dto.setSupplierName(supply.getSupplierName());
            }
 
            // 登记人
            SysUser sysUser = userMap.get(entity.getRegistrantId());
            if (sysUser != null) {
                dto.setRegistrant(sysUser.getNickName());
            }
 
            List<CoalValue> coalValues;
            if (entity.getMergeId() == null) {
                coalValues = coalValueMapper.selectList(new LambdaQueryWrapper<CoalValue>()
                        .eq(CoalValue::getPlanId, entity.getPendingId())
                        .and(wrapper -> wrapper.ne(CoalValue::getType, "2").or().isNull(CoalValue::getType))
                );
            } else {
                coalValues = coalValueMapper.selectList(new LambdaQueryWrapper<CoalValue>()
                        .eq(CoalValue::getPlanId, entity.getId())
                        .eq(CoalValue::getType, "2")
                );
            }
 
            //  构建 Map<fieldName, value>
            Map<String, String> fieldValueMap = coalValues.stream()
                    .collect(Collectors.toMap(
                            CoalValue::getFields,
                            CoalValue::getCoalValue,
                            (existing, replacement) -> existing // 重复字段保留第一个
                    ));
 
            // 构造最终 fields 列表,包含所有字段名,并设置默认值 "-"
            List<Map<String, String>> fields = new ArrayList<>();
            for (String field : allFieldNames) {
                Map<String, String> fieldMap = new HashMap<>();
                fieldMap.put(field, fieldValueMap.getOrDefault(field, "-"));
                fields.add(fieldMap);
            }
 
            // 设置Coal信息
            CoalInfo coalInfo = coalInfoMap.get(entity.getCoalId());
            if (coalInfo != null) {
                dto.setCoal(coalInfo.getCoal());
            }
 
            // 设置到 DTO 中
            dto.setFields(fields);
            dtoList.add(dto);
        }
 
        dtoPage.setRecords(dtoList); // 设置转换后的 DtoList
        return dtoPage;
    }
 
    @Override
    public int editOfficial(OfficialInventoryDto officialInventoryDto) {
        OfficialInventory officialInventory = new OfficialInventory();
        BeanUtils.copyProperties(officialInventoryDto, officialInventory);
 
        if (officialInventoryDto.getMergeId() != null) {
            // 1. 构建查询条件
            LambdaQueryWrapper<CoalValue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CoalValue::getPlanId, officialInventoryDto.getId())
                    .eq(CoalValue::getType, "2");
 
            // 2. 查询多个符合条件的CoalValue记录
            List<CoalValue> coalValues = coalValueMapper.selectList(queryWrapper);
 
            if (!CollectionUtils.isEmpty(coalValues) && !CollectionUtils.isEmpty(officialInventoryDto.getFields())) {
                // 3. 创建字段映射关系 (field key -> coal_value)
                Map<String, String> fieldValueMap = new HashMap<>();
                for (Map<String, String> fieldMap : officialInventoryDto.getFields()) {
                    fieldValueMap.putAll(fieldMap);
                }
 
                // 4. 更新
                for (CoalValue coalValue : coalValues) {
                    String fieldKey = coalValue.getFields(); // 数据库中的field key
                    if (fieldValueMap.containsKey(fieldKey)) {
                        String newValue = fieldValueMap.get(fieldKey);
                        if (!Objects.equals(coalValue.getCoalValue(), newValue)) {
                            coalValue.setCoalValue(newValue);
                            coalValueMapper.updateById(coalValue);
                        }
                    }
                }
            }
        } else {
            // 构建查询条件
            LambdaQueryWrapper<CoalValue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CoalValue::getPlanId, officialInventoryDto.getPendingId())
                    .eq(CoalValue::getType, "1");
 
            // 2. 查询多个符合条件的CoalValue记录
            List<CoalValue> coalValues = coalValueMapper.selectList(queryWrapper);
 
            if (!CollectionUtils.isEmpty(coalValues) && !CollectionUtils.isEmpty(officialInventoryDto.getFields())) {
                // 3. 创建字段映射关系 (field key -> coal_value)
                Map<String, String> fieldValueMap = new HashMap<>();
                for (Map<String, String> fieldMap : officialInventoryDto.getFields()) {
                    fieldValueMap.putAll(fieldMap);
                }
 
                // 4. 更新
                for (CoalValue coalValue : coalValues) {
                    String fieldKey = coalValue.getFields(); // 数据库中的field key
                    if (fieldValueMap.containsKey(fieldKey)) {
                        String newValue = fieldValueMap.get(fieldKey);
                        if (!Objects.equals(coalValue.getCoalValue(), newValue)) {
                            coalValue.setCoalValue(newValue);
                            coalValueMapper.updateById(coalValue);
                        }
                    }
                }
            }
        }
        return officialInventoryMapper.updateById(officialInventory);
    }
 
    @Override
    public List<OfficialInventoryVo> selectOfficialList(OfficialInventoryVo officialInventoryVo) {
        List<OfficialInventory> officialInventories = officialInventoryMapper.selectList(null);
        return officialInventories.stream()
                .map(OI -> {
                    OfficialInventoryVo vo = new OfficialInventoryVo();
                    BeanUtils.copyProperties(OI, vo);
                    CoalInfo coalInfo = coalInfoMapper.selectById(OI.getCoalId());
                    vo.setCoal(coalInfo.getCoal());
                    return vo;
                })
                .collect(Collectors.toList());
    }
 
    @Override
    public List<OfficialInventory> selectOfficialAll() {
        return officialInventoryMapper.selectList(null);
    }
 
    @Transactional
    @Override
    public int mergeAll(OfficialInventoryDto officialInventoryDto) {
        List<Long> ids = officialInventoryDto.getIds();
 
        // 校验参数
        if (CollectionUtils.isEmpty(ids) || ids.size() < 2) {
            throw new BaseException("请选中至少两条数据");
        }
        if (CollectionUtils.isEmpty(officialInventoryDto.getFields())) {
            throw new BaseException("字段值不能为空");
        }
 
        // 1. 批量标记删除旧数据
        LambdaUpdateWrapper<OfficialInventory> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(OfficialInventory::getId, ids)
                .set(OfficialInventory::getDeleted, 1);
        int rowsAffected = officialInventoryMapper.update(null, updateWrapper);
        if (rowsAffected == 0) {
            throw new BaseException("未找到匹配的数据,请确认选择是否正确");
        }
 
        // 2. 插入新库存记录
        OfficialInventory officialInventory = new OfficialInventory();
        BeanUtils.copyProperties(officialInventoryDto, officialInventory);
        officialInventory.setId(null);
        officialInventory.setMergeId(ids.toString());
        officialInventory.setSupplierId(officialInventoryDto.getSupplierId());
        officialInventory.setRegistrantId(SecurityUtils.getLoginUser().getUser().getUserId());
        if (officialInventoryMapper.insert(officialInventory) <= 0) {
            throw new BaseException("库存记录创建失败");
        }
 
        // 3. 批量处理字段值
        batchProcessCoalValues(officialInventory.getId(), officialInventoryDto.getFields());
 
        return rowsAffected;
    }
 
    private void batchProcessCoalValues(Long planId, List<Map<String, String>> fields) {
        // 1. 提取所有唯一字段标识
        Set<String> allFields = fields.stream()
                .flatMap(map -> map.keySet().stream())
                .collect(Collectors.toSet());
 
        // 2. 查询字段映射关系
        List<CoalField> coalFields = coalFieldMapper.selectList(
                new LambdaQueryWrapper<CoalField>().in(CoalField::getFields, allFields)
        );
 
        Map<String, String> fieldMap = coalFields.stream()
                .collect(Collectors.toMap(
                        CoalField::getFields,
                        CoalField::getFieldName
                ));
 
        // 3. 构造并插入每条记录
        CoalValue coalValueTemplate = new CoalValue();
        coalValueTemplate.setPlanId(planId);
        coalValueTemplate.setType("2");
 
        for (Map<String, String> fieldMapEntry : fields) {
            for (Map.Entry<String, String> entry : fieldMapEntry.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
 
                String fieldName = fieldMap.get(key);
                if (fieldName == null) {
                    throw new BaseException("字段名不存在: " + key);
                }
 
                CoalValue coalValue = new CoalValue();
                BeanUtils.copyProperties(coalValueTemplate, coalValue); // 复用模板属性
                coalValue.setId(null);
                coalValue.setCoalValue(value);
                coalValue.setType("2");
                coalValue.setPlanId(planId);
                coalValue.setFields(key);
                coalValue.setFieldName(fieldName);
 
                // 单条插入
                int result = coalValueMapper.insert(coalValue);
                if (result <= 0) {
                    throw new BaseException("字段值保存失败,字段:" + key);
                }
            }
        }
    }
 
    @Override
    public void officialInventoryExport(HttpServletResponse response, OfficialInventoryDto officialInventoryDto) {
        try {
            // 获取煤质字段配置
            List<CoalField> allCoalFields = coalFieldMapper.selectList(null);
            List<String> dynamicHeaders = allCoalFields.stream()
                    .map(CoalField::getFieldName)
                    .collect(Collectors.toList());
 
            // 获取数据
            List<OfficialInventory> list = officialInventoryDto.getExportIds() != null && !officialInventoryDto.getExportIds().isEmpty()
                    ? officialInventoryMapper.selectByIds(officialInventoryDto.getExportIds())
                    : officialInventoryMapper.selectList(null);
 
            // 转换为导出VO
            List<OfficialInventoryExportVo> exportData = convertToExportVo(list, allCoalFields);
 
            // 使用增强的Excel工具导出
            DynamicExcelUtil<OfficialInventoryExportVo> util =
                    new DynamicExcelUtil<>(OfficialInventoryExportVo.class, dynamicHeaders);
 
            // 导出Excel
            util.exportExcel(response, exportData, "库存数据");
 
        } catch (Exception e) {
            log.error("库存导出失败", e);
            // 可以考虑返回更友好的错误信息给前端
            throw new RuntimeException("导出失败: " + e.getMessage());
        }
    }
 
    private List<OfficialInventoryExportVo> convertToExportVo(List<OfficialInventory> list, List<CoalField> coalFields) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
 
        // 收集所有需要查询的ID
        Set<Long> coalIds = list.stream()
                .map(OfficialInventory::getCoalId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
 
        Set<Long> supplierIds = list.stream()
                .map(OfficialInventory::getSupplierId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
 
        Set<Long> registrantIds = list.stream()
                .map(OfficialInventory::getRegistrantId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
 
        Set<Long> planIds = list.stream()
                .map(OfficialInventory::getCoalPlanId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
 
        // 批量查询关联数据
        Map<Long, CoalInfo> coalInfoMap = getCoalInfoMap(coalIds);
        Map<Long, Supply> supplyMap = getSupplyMap(supplierIds);
        Map<Long, SysUser> userMap = getUserMap(registrantIds);
        Map<Long, List<CoalValue>> coalValuesMap = getCoalValuesMap(planIds);
 
        // 构建字段ID到字段名称的映射,提高查找效率
        Map<String, String> fieldIdToNameMap = coalFields.stream()
                .collect(Collectors.toMap(CoalField::getFields, CoalField::getFieldName));
 
        // 转换数据
        return list.stream().map(record -> {
            OfficialInventoryExportVo vo = new OfficialInventoryExportVo();
            vo.initDynamicFields(); // 初始化
 
            // 设置基础属性
            BeanUtils.copyProperties(record, vo);
 
            // 设置关联信息
            setCoalInfo(vo, record.getCoalId(), coalInfoMap);
            setSupplierInfo(vo, record.getSupplierId(), supplyMap);
            setUserMapInfo(vo, record.getRegistrantId(), userMap);
 
            // 动态字段处理
            if (record.getCoalPlanId() != null) {
                List<CoalValue> values = coalValuesMap.getOrDefault(record.getCoalPlanId(), Collections.emptyList());
                setDynamicFields(vo, values, fieldIdToNameMap);
            }
 
            return vo;
        }).collect(Collectors.toList());
    }
 
    private void setCoalInfo(OfficialInventoryExportVo vo, Long coalId, Map<Long, CoalInfo> coalInfoMap) {
        if (coalId != null && coalInfoMap.containsKey(coalId)) {
            vo.setCoal(coalInfoMap.get(coalId).getCoal());
        }
    }
 
    private void setSupplierInfo(OfficialInventoryExportVo vo, Long supplierId, Map<Long, Supply> supplyMap) {
        if (supplierId != null && supplyMap.containsKey(supplierId)) {
            vo.setSupplierName(supplyMap.get(supplierId).getSupplierName());
        }
    }
 
    private void setUserMapInfo(OfficialInventoryExportVo vo, Long registrantId, Map<Long, SysUser> userMap) {
        if (registrantId != null && userMap.containsKey(registrantId)) {
            vo.setRegistrant(userMap.get(registrantId).getNickName());
        }
    }
 
    private void setDynamicFields(OfficialInventoryExportVo vo, List<CoalValue> values, Map<String, String> fieldIdToNameMap) {
        for (CoalValue value : values) {
            String fieldName = fieldIdToNameMap.get(value.getFields());
            if (fieldName != null) {
                vo.getCoalQualityProperties().put(fieldName, value.getCoalValue());
            }
        }
    }
 
    private Map<Long, List<CoalValue>> getCoalValuesMap(Set<Long> planIds) {
        if (CollectionUtils.isEmpty(planIds)) {
            return Collections.emptyMap();
        }
 
        List<CoalValue> allValues = coalValueMapper.selectList(
                new LambdaQueryWrapper<CoalValue>()
                        .in(CoalValue::getPlanId, planIds));
 
        return allValues.stream()
                .collect(Collectors.groupingBy(CoalValue::getPlanId));
    }
 
    private Map<Long, CoalInfo> getCoalInfoMap(Set<Long> coalIds) {
        if (CollectionUtils.isEmpty(coalIds)) {
            return Collections.emptyMap();
        }
        return coalInfoMapper.selectByIds(coalIds).stream()
                .collect(Collectors.toMap(CoalInfo::getId, Function.identity()));
    }
 
    private Map<Long, Supply> getSupplyMap(Set<Long> supplierIds) {
        if (CollectionUtils.isEmpty(supplierIds)) {
            return Collections.emptyMap();
        }
        return supplyMapper.selectByIds(supplierIds).stream()
                .collect(Collectors.toMap(Supply::getId, Function.identity()));
    }
 
    private Map<Long, SysUser> getUserMap(Set<Long> registrantIds) {
        if (CollectionUtils.isEmpty(registrantIds)) {
            return Collections.emptyMap();
        }
        return sysUserMapper.selectBatchIds(registrantIds).stream()
                .collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
    }
 
    @Override
    public List<OfficialInventoryDto> coalBlendingList() {
        // 1. 查询基础库存数据
        List<OfficialInventory> officialInventories = officialInventoryMapper.selectList(null);
        // 2. 收集所有需要查询的ID
        Set<Long> coalIds = new HashSet<>();
        Set<Long> supplierIds = new HashSet<>();
        Set<Long> planIds = new HashSet<>();
 
        officialInventories.forEach(inventory -> {
            coalIds.add(inventory.getCoalId());
            supplierIds.add(inventory.getSupplierId());
            planIds.add(inventory.getCoalPlanId());
        });
        // 3. 批量查询关联数据
        Map<Long, CoalInfo> coalInfoMap;
        if (!coalIds.isEmpty()) {
            coalInfoMap = coalInfoMapper.selectByIds(coalIds).stream()
                    .collect(Collectors.toMap(CoalInfo::getId, Function.identity()));
        } else {
            coalInfoMap = new HashMap<>();
        }
 
        Map<Long, Supply> supplyMap;
        if (!supplierIds.isEmpty()) {
            supplyMap = supplyMapper.selectByIds(supplierIds).stream()
                    .collect(Collectors.toMap(Supply::getId, Function.identity()));
        } else {
            supplyMap = new HashMap<>();
            log.warn("supplierIds 为空,跳过查询 Supply");
        }
 
        Map<Long, List<CoalValue>> coalValuesMap;
        if (!planIds.isEmpty()) {
            coalValuesMap = coalValueMapper.selectList(
                            new LambdaQueryWrapper<CoalValue>().in(CoalValue::getPlanId, planIds))
                    .stream()
                    .collect(Collectors.groupingBy(CoalValue::getPlanId));
        } else {
            coalValuesMap = new HashMap<>();
            log.warn("planIds 为空,跳过查询 CoalValue");
        }
        // 4. 组装DTO
        return officialInventories.stream()
                .map(inventory -> {
                    OfficialInventoryDto dto = new OfficialInventoryDto();
                    BeanUtils.copyProperties(inventory, dto);
                    // 设置煤种信息
                    CoalInfo coalInfo = coalInfoMap.get(inventory.getCoalId());
                    Supply supply = supplyMap.get(inventory.getSupplierId());
                    if (coalInfo != null && supply != null) {
                        dto.setSupplierCoal(supply.getSupplierName() + " - " + coalInfo.getCoal());
                    }
                    // 设置煤质数据
                    dto.setCoalValues(coalValuesMap.getOrDefault(inventory.getCoalPlanId(), Collections.emptyList())
                            .stream()
                            .map(coalValue -> {
                                Map<String, String> map = new HashMap<>();
                                map.put("fieldName", coalValue.getFieldName());
                                map.put("coalValue", coalValue.getCoalValue());
                                return map;
                            })
                            .collect(Collectors.toList()));
                    return dto;
                })
                .collect(Collectors.toList());
    }
 
    @Override
    public Map<String, BigDecimal> selectOfficialAllInfo() {
        // 1. 查询 official_inventory 表数据
        List<OfficialInventory> officialInventories = officialInventoryMapper.selectList(null);
 
        // 用于存储最终结果,key 为煤种名称,value 为库存数量拼接“吨”
        Map<String, BigDecimal> resultMap = new LinkedHashMap<>();
 
        // 2. 遍历查询结果,关联 coalInfo 获取煤种名称并组装数据
        for (OfficialInventory inventory : officialInventories) {
            Long coalId = inventory.getCoalId();
            // 根据 coalId 到 coalInfoMapper 查询煤种名称
            CoalInfo coalInfo = coalInfoMapper.selectById(coalId);
            if (coalInfo != null) {
                String coalName = coalInfo.getCoal(); // 假设 CoalInfo 有 getCoalName 方法获取煤种名称
                BigDecimal quantity = inventory.getInventoryQuantity();
                resultMap.put(coalName, quantity);
            }
        }
        return resultMap;
    }
 
}