liding
2025-04-10 a3e0493b2f597e8c49ee80a0c7ab92bc30dc60a3
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
package com.ruoyi.basic.service.impl;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.dto.*;
import com.ruoyi.basic.excel.StructureTestObjectData;
import com.ruoyi.basic.service.*;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.QueryWrappers;
import com.ruoyi.basic.mapper.*;
import com.ruoyi.basic.pojo.*;
import com.ruoyi.common.utils.StringUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
/**
 * 检验项目参数(StructureItemParameter)表服务实现类
 *
 * @author makejava
 * @since 2024-02-26 16:21:17
 */
@Service
@AllArgsConstructor
public class CapacityScopeServiceImpl extends ServiceImpl<StructureItemParameterMapper, StructureItemParameter> implements CapacityScopeService {
 
    private StructureItemParameterMapper structureItemParameterMapper;
 
    private StructureTestObjectMapper structureTestObjectMapper;
 
    private ProductMapper productMapper;
 
    private ProductService productService;
 
    private StructureTestObjectService structureTestObjectService;
 
    private StructureTestObjectPartMapper structureTestObjectPartMapper;
 
    private ProductPartMapper productPartMapper;
 
    private StandardProductListService standardProductListService;
 
    private StandardTreeMapper standardTreeMapper;
 
    private StructureItemParameterService structureItemParameterService;
 
    private WorkShopMapper workShopMapper;
 
    private ModelMapper modelMapper;
 
    @Override
    public IPage<StructureItemParameter> selectItemParameterList(Page page, StructureItemParameter itemParameter) {
        return structureItemParameterMapper.selectItemParameterList(page, QueryWrappers.queryWrappers(itemParameter));
    }
 
    @Override
    public int addItemParameter(StructureItemParameter itemParameter) {
        if (itemParameter.getBsm().equals("") || itemParameter.getBsm() == null) {
            itemParameter.setBsm("0");
        }
        return structureItemParameterMapper.insert(itemParameter);
    }
 
    @Override
    public int delItemParameter(Integer id) {
        return structureItemParameterMapper.deleteById(id);
    }
 
    @Override
    public int upItemParameter(StructureItemParameter itemParameter) {
        return structureItemParameterMapper.updateById(itemParameter);
    }
 
    @Override
    public IPage<PageTestObjectDto> selectTestObjectList(Page page, PageTestObjectDto pageTestObjectDto) {
        String specimenName = pageTestObjectDto.getSample();
        pageTestObjectDto.setSample(null);
        return structureTestObjectMapper.selectTestObjectList(page, QueryWrappers.queryWrappers(pageTestObjectDto), specimenName);
    }
 
    @Override
    public int addTestObject(StructureTestObject testObject) {
        Long count = structureTestObjectMapper.selectCount(Wrappers.<StructureTestObject>lambdaQuery().eq(StructureTestObject::getSpecimenName, testObject.getSpecimenName()));
        if (count.compareTo(0L) > 0) {
            throw new BaseException("检验对象不能重复");
        }
 
        return structureTestObjectMapper.insert(testObject);
    }
 
    @Override
    public int delTestObject(Integer id) {
        // 产出检验对象产品维护
        structureTestObjectPartMapper.delete(Wrappers.<StructureTestObjectPart>lambdaQuery()
                .eq(StructureTestObjectPart::getTestObjectId, id));
 
        // 删除产品维护的零件绑定
        List<Product> products = productMapper.selectList(Wrappers.<Product>lambdaQuery()
                .eq(Product::getObjectId, id));
        List<Integer> productIds = products.stream().map(Product::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(productIds)) {
            productPartMapper.delete(Wrappers.<ProductPart>lambdaQuery()
                    .in(ProductPart::getProductId, productIds));
 
            // 删除产品维护
            productMapper.delete(Wrappers.<Product>lambdaQuery()
                    .in(Product::getId, productIds));
        }
 
        return structureTestObjectMapper.deleteById(id);
    }
 
    @Override
    public int upTestObject(StructureTestObject testObject) {
        // 查询旧的检验对象
        StructureTestObject oldTestObject = structureTestObjectMapper.selectById(testObject.getId());
 
        if (!oldTestObject.getSpecimenName().equals(testObject.getSpecimenName())) {
            // 查询所有对象一样的检验项目
            List<StandardProductList> standardProductLists = standardProductListService.list(Wrappers.<StandardProductList>lambdaUpdate()
                    .eq(StandardProductList::getSampleType, oldTestObject.getSpecimenName()));
            if (CollectionUtils.isNotEmpty(standardProductLists)) {
                for (StandardProductList standardProductList : standardProductLists) {
                    // 修改所有的对象名称和数型结构
                    standardProductList.setSampleType(testObject.getSpecimenName());
                    // 需要截取第三级, 避免三四级名称一样修改错误
                    String[] trees = standardProductList.getTree().split(" - ");
                    trees[2] = testObject.getSpecimenName();
                    List<String> list = CollUtil.newArrayList(trees);
                    String newName = CollUtil.join(list, " - ");
                    standardProductList.setTree(newName);
                }
                standardProductListService.updateBatchById(standardProductLists);
            }
            // 修改检验项目参数的检验对象
            // 拼接 ["object", 查询检验项目参数修改绑定的检验对象
            String format = "[\"{}\",";
            String sampleOld = StrUtil.format(format, oldTestObject.getSpecimenName());
            List<StructureItemParameter> itemParameterList = structureItemParameterService.list(Wrappers.<StructureItemParameter>lambdaQuery()
                    .like(StructureItemParameter::getSample, sampleOld));
            if (CollectionUtils.isNotEmpty(itemParameterList)) {
                for (StructureItemParameter structureItemParameter : itemParameterList) {
                    // 修改绑定的样品名称
                    String sampleNew = StrUtil.format(format, testObject.getSpecimenName());
                    String sampleUp = structureItemParameter.getSample().replace(sampleOld, sampleNew);
                    structureItemParameter.setSample(sampleUp);
                }
                structureItemParameterService.updateBatchById(itemParameterList);
            }
 
            // 修改树的型号
            standardTreeMapper.update(null, Wrappers.<StandardTree>lambdaUpdate()
                    .eq(StandardTree::getSampleType, oldTestObject.getSpecimenName())
                    .set(StandardTree::getSampleType, testObject.getSpecimenName()));
        }
 
        Long count = structureTestObjectMapper.selectCount(Wrappers.<StructureTestObject>lambdaQuery()
                .eq(StructureTestObject::getSpecimenName, testObject.getSpecimenName())
                .ne(StructureTestObject::getId, testObject.getId()));
        if (count.compareTo(0L) > 0) {
            throw new BaseException("检验对象不能重复");
        }
 
        return structureTestObjectMapper.updateById(testObject);
    }
 
    @Override
    public List<StructureTestObject> selectTestObjectByName() {
        return structureTestObjectMapper.selectList(Wrappers.<StructureTestObject>lambdaQuery().select(StructureTestObject::getSpecimenName, StructureTestObject::getId));
    }
 
    //设备里面选择检验项目(树形结构)
    @Override
    public List<Map<String, Object>> getInsProduction() {
        return structureItemParameterMapper.getInsProduction();
    }
 
    @Override
    public List<TestItemDto> getItemTree() {
        return structureItemParameterMapper.getItemTree();
    }
 
    @Override
    public List<TestItemDto> getItemTreeProduct(StructureTestObjectDto structureTestObjectDto) {
        return structureItemParameterMapper.getItemTreeProduct(structureTestObjectDto.getObjectType());
    }
 
    @Override
    public List<Model> getProductTypes(ModelDto modelDto) {
        return modelMapper.selectList(Wrappers.<Model>lambdaQuery().eq(Model::getProductId, modelDto.getProductId()));
    }
 
    @Override
    public List<ProductPart> getPartNoList(ProductPartDto productPartDto) {
        return productPartMapper.selectList(Wrappers.<ProductPart>lambdaQuery().eq(ProductPart::getProductId, productPartDto.getProductId()));
    }
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importPartExcel(List<StructureTestObjectData> list) {
        // 阶段2: 批量查询现有结构测试对象
        Map<String, StructureTestObject> existStructureTestObjects = structureTestObjectMapper.selectList(
                Wrappers.<StructureTestObject>lambdaQuery()
                        .in(StructureTestObject::getSpecimenName, list.stream().map(StructureTestObjectData::getSpecimenName).collect(Collectors.toSet()))
                        .in(StructureTestObject::getSpecimenNameEn, list.stream().map(StructureTestObjectData::getSpecimenNameEn).collect(Collectors.toSet()))
                        .in(StructureTestObject::getObjectType, list.stream().map(StructureTestObjectData::getObjectType).collect(Collectors.toSet()))
        ).stream().collect(Collectors.toMap(
                obj -> generateStructureKey(obj.getSpecimenName(), obj.getSpecimenNameEn(), obj.getObjectType()), // 统一键生成
                Function.identity(),
                (existing, replacement) -> existing
        ));
 
        // 阶段3: 预处理车间信息
        Set<String> workShopNames = list.stream()
                .map(StructureTestObjectData::getWorkShopName)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toSet());
 
        Map<String, WorkShop> workShopCache = workShopNames.isEmpty() ?
                Collections.emptyMap() :
                workShopMapper.selectList(Wrappers.<WorkShop>lambdaQuery()
                                .in(WorkShop::getName, workShopNames))
                        .stream()
                        .collect(Collectors.toMap(WorkShop::getName, Function.identity()));
 
        // 阶段4: 准备批量操作数据
        List<StructureTestObject> structureTestObjectsToInsert = new ArrayList<>();
        List<StructureTestObject> structureTestObjectsToUpdate = new ArrayList<>();
        List<Product> productsToInsert = new ArrayList<>();
        List<Product> productsToUpdate = new ArrayList<>();
 
        // 阶段5: 主处理逻辑(仅处理结构测试对象)
        List<StructureTestObjectData> pendingProducts = new ArrayList<>(); // 新增:暂存待处理的产品数据
 
        for (StructureTestObjectData i : list) {
            // 处理结构测试对象(逻辑不变)
            String specimenKey = i.getSpecimenName() + "|" + i.getSpecimenNameEn() + "|" + i.getObjectType();
            StructureTestObject structureTestObject = existStructureTestObjects.get(specimenKey);
 
            if (structureTestObject == null) {
                StructureTestObject newObj = createNewStructureTestObject(i, workShopCache); // 修改:传入车间缓存
                structureTestObjectsToInsert.add(newObj);
                existStructureTestObjects.put(specimenKey, newObj);
            } else {
                updateExistingStructureTestObject(structureTestObject, i);
                structureTestObjectsToUpdate.add(structureTestObject);
            }
 
            // 暂存产品处理数据(新增)
            pendingProducts.add(i);
        }
 
        // 阶段6: 先处理结构测试对象批量操作
        executeStructureTestObjectBatch(structureTestObjectsToInsert, structureTestObjectsToUpdate);
 
        // 阶段7: 更新缓存中的ID(关键新增步骤)
        refreshStructureTestObjectIds(existStructureTestObjects, structureTestObjectsToInsert);
 
        // 阶段8: 处理产品数据
        processProducts(pendingProducts, existStructureTestObjects, workShopCache,
                productsToInsert, productsToUpdate);
 
        // 阶段9: 执行产品批量操作
        executeProductBatch(productsToInsert, productsToUpdate);
    }
 
    // 更新现有结构测试对象
    private void updateExistingStructureTestObject(StructureTestObject obj, StructureTestObjectData data) {
        obj.setCode(data.getCode());
        obj.setLaboratoryId(9);
    }
 
    // 统一键生成方法
    private String generateStructureKey(String name, String nameEn, String objectType) {
        return name + "|" + nameEn + "|" + objectType;
    }
 
    // 处理产品数据
    private void processProductData(StructureTestObjectData data,
                                    Integer objectId,
                                    Map<String, WorkShop> workShopCache,
                                    List<Product> insertList,
                                    List<Product> updateList) {
        // 构建产品唯一标识
        String productKey = data.getName() + "|" + data.getNameEn() + "|" + data.getObjectType();
 
        // 检查内存中是否已处理过该产品
        Optional<Product> existingProduct = findProductInBatchLists(productKey, insertList, updateList);
 
        // 如果内存中不存在,查询数据库
        if (!existingProduct.isPresent()) {
            Product dbProduct = productMapper.selectOne(Wrappers.<Product>lambdaQuery()
                    .eq(Product::getName, data.getName())
                    .eq(Product::getNameEn, data.getNameEn())
                    .last("limit 1"));
            existingProduct = Optional.ofNullable(dbProduct);
        }
 
        // 创建或更新产品
        Product product = existingProduct.orElseGet(Product::new);
        boolean isNew = product.getId() == null;
 
        // 设置产品属性
        setupProduct(product, data, objectId, workShopCache);
 
        // 加入对应列表
        if (isNew) {
            insertList.add(product);
        } else {
            updateList.add(product);
        }
    }
 
    // 在产品批量列表中查找
    private Optional<Product> findProductInBatchLists(String productKey,
                                                      List<Product> insertList,
                                                      List<Product> updateList) {
        return Stream.concat(insertList.stream(), updateList.stream())
                .filter(p -> (p.getName() + "|" + p.getNameEn()).equals(productKey))
                .findFirst();
    }
 
    // 设置产品信息
    private void setupProduct(Product product,
                              StructureTestObjectData data,
                              Integer objectId,
                              Map<String, WorkShop> workShopCache) {
        product.setName(data.getName());
        product.setNameEn(data.getNameEn());
        product.setObjectId(objectId);
        // 处理车间信息
        if (StringUtils.isNotEmpty(data.getWorkShopName())) {
            WorkShop workShop = workShopCache.get(data.getWorkShopName());
            if (workShop == null) {
                throw new BaseException("车间信息未维护: " + data.getWorkShopName());
            }
            product.setWorkShopId(workShop.getId());
            product.setWorkShopName(data.getWorkShopName());
        }
    }
 
    // 创建结构测试对象(使用缓存车间信息)
    private StructureTestObject createNewStructureTestObject(StructureTestObjectData data,
                                                             Map<String, WorkShop> workShopCache) {
        StructureTestObject obj = new StructureTestObject();
        obj.setLaboratoryId(9);
        obj.setSpecimenName(data.getSpecimenName());
        obj.setSpecimenNameEn(data.getSpecimenNameEn());
        obj.setCode(data.getCode());
        obj.setObjectType(data.getObjectType());
 
        // 使用缓存获取车间信息
        if (StringUtils.isNotEmpty(data.getWorkShopName())) {
            WorkShop workShop = workShopCache.get(data.getWorkShopName());
            if (workShop == null) {
                throw new BaseException("车间信息未维护: " + data.getWorkShopName());
            }
            obj.setWorkShopId(workShop.getId());
            obj.setWorkShopName(data.getWorkShopName());
        } else {
            obj.setWorkShopName("");
        }
        return obj;
    }
 
    // 刷新结构测试对象ID(关键方法)
    private void refreshStructureTestObjectIds(
            Map<String, StructureTestObject> existStructureTestObjects,
            List<StructureTestObject> insertedObjects) {
 
        insertedObjects.forEach(obj -> {
            String key = obj.getSpecimenName() + "|" + obj.getSpecimenNameEn() + "|" + obj.getObjectType();
            existStructureTestObjects.get(key).setId(obj.getId()); // 更新缓存中的ID
        });
    }
 
    // 处理产品数据(独立方法)
    private void processProducts(List<StructureTestObjectData> pendingProducts,
                                 Map<String, StructureTestObject> structureTestObjectCache,
                                 Map<String, WorkShop> workShopCache,
                                 List<Product> insertList,
                                 List<Product> updateList) {
 
        // 阶段5原有产品处理逻辑迁移至此
        pendingProducts.forEach(i -> {
            String specimenKey = i.getSpecimenName() + "|" + i.getSpecimenNameEn() + "|" + i.getObjectType();
            StructureTestObject sto = structureTestObjectCache.get(specimenKey);
 
            processProductData(
                    i,
                    sto.getId(), // 此时ID已正确设置
                    workShopCache,
                    insertList,
                    updateList
            );
        });
    }
 
    // 分拆批量操作方法
    private void executeStructureTestObjectBatch(List<StructureTestObject> toInsert,
                                                 List<StructureTestObject> toUpdate) {
        if (!toInsert.isEmpty()) {
            structureTestObjectMapper.insertBatchSomeColumn(toInsert);
        }
        if (!toUpdate.isEmpty()) {
            structureTestObjectService.updateBatchById(toUpdate);
        }
    }
 
    private void executeProductBatch(List<Product> toInsert,
                                     List<Product> toUpdate) {
        if (!toInsert.isEmpty()) {
            productMapper.insertBatchSomeColumn(toInsert);
        }
        if (!toUpdate.isEmpty()) {
            productService.updateBatchById(toUpdate);
        }
    }
 
}