liding
2025-04-03 dc4d7386937447cc1e9ecfb3cd65966cc5d21aa1
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
package com.ruoyi.basic.service.impl;
 
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
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.common.utils.QueryWrappers;
import com.ruoyi.basic.mapper.StandardMethodMapper;
import com.ruoyi.basic.mapper.StandardProductListMapper;
import com.ruoyi.basic.mapper.StructureItemParameterMapper;
import com.ruoyi.basic.pojo.StandardMethod;
import com.ruoyi.basic.pojo.StandardProductList;
import com.ruoyi.basic.pojo.StructureItemParameter;
import com.ruoyi.basic.service.StandardMethodService;
import com.ruoyi.basic.service.StandardProductListService;
import com.ruoyi.basic.service.StructureItemParameterService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
 
/**
 * @author Administrator
 * @description 针对表【standard_method(标准方法)】的数据库操作Service实现
 * @createDate 2024-03-03 19:21:41
 */
@Service
@AllArgsConstructor
public class StandardMethodServiceImpl extends ServiceImpl<StandardMethodMapper, StandardMethod>
        implements StandardMethodService {
 
 
    private StandardMethodMapper standardMethodMapper;
 
    StandardProductListMapper standardProductListMapper;
    StandardProductListService standardProductListService;
 
    StructureItemParameterMapper structureItemParameterMapper;
    StructureItemParameterService structureItemParameterService;
 
    @Override
    public IPage<StandardMethod> selectStandardMethodList(Page page, StandardMethod standardMethod) {
        return standardMethodMapper.selectStandardMethodList(page, QueryWrappers.queryWrappers(standardMethod));
    }
 
    @Override
    public List<StandardMethod> selectStandardMethods() {
        return standardMethodMapper.selectList(Wrappers.<StandardMethod>lambdaQuery().select(StandardMethod::getId, StandardMethod::getCode, StandardMethod::getName).ne(StandardMethod::getId, 0));
    }
 
    @Override
    public int addStandardMethod(StandardMethod standardMethod) {
        int insert = standardMethodMapper.insert(standardMethod);
        return insert;
    }
 
    @Override
    public int delStandardMethod(Integer id) {
        int i = standardMethodMapper.deleteById(id);
        return i;
    }
 
    @Override
    public int upStandardMethod(StandardMethod standardMethod) {
        StandardMethod oldStandardMethod = standardMethodMapper.selectById(standardMethod.getId());
        if (!oldStandardMethod.getCode().equals(standardMethod.getCode())) {
            CompletableFuture.supplyAsync(() -> replaceMethod(oldStandardMethod.getCode(), standardMethod.getCode()));
        }
        int i = standardMethodMapper.updateById(standardMethod);
        return i;
    }
 
    //编辑method后全部替换
    public String replaceMethod(String oldCode, String code) {
        //查询StandardProductList中所有Method如果包含之前的则替换
        List<StandardProductList> standardProductLists = standardProductListMapper.selectList(null);
        for (StandardProductList standardProductList : standardProductLists) {
            if (standardProductList.getMethod().contains(oldCode)) {
                String[] split = standardProductList.getMethod().split(",");
                String a = null;
                for (int i = 0; i < split.length; i++) {
                    String methodName = split[i].substring(1, split[i].length() - 1);
                    if (i == 0) {
                        methodName = split[i].substring(2, split[i].length() - 1);
                    } else if (i == split.length - 1) {
                        methodName = split[i].substring(1, split[i].length() - 2);
                    }
                    if (methodName.equals(oldCode)) {
                        methodName = code;
                    }
                    a += "\"" + methodName + "\",";
                }
                String method = "[\"" + a.substring(0, a.length() - 1) + "\"]";
                standardProductList.setMethod(method);
            }
        }
        standardProductListService.updateBatchById(standardProductLists);
        //查询StructureItemParameter中所有Method如果包含之前的则替换
        List<StructureItemParameter> structureItemParameters = structureItemParameterMapper.selectList(null);
        for (StructureItemParameter structureItemParameter : structureItemParameters) {
            if (structureItemParameter.getMethod().contains(oldCode)) {
                String[] split = structureItemParameter.getMethod().split(",");
                String a = null;
                for (int i = 0; i < split.length; i++) {
                    String methodName = split[i].substring(1, split[i].length() - 1);
                    if (i == 0) {
                        methodName = split[i].substring(2, split[i].length() - 1);
                    } else if (i == split.length - 1) {
                        methodName = split[i].substring(1, split[i].length() - 2);
                    }
                    if (methodName.equals(oldCode)) {
                        methodName = code;
                    }
                    a += "\"" + methodName + "\",";
                }
                String method = "[\"" + a.substring(0, a.length() - 1) + "\"]";
                structureItemParameter.setMethod(method);
            }
        }
        structureItemParameterService.updateBatchById(structureItemParameters);
        return "替换完毕!";
    }
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inputExcel(MultipartFile file) throws IOException {
 
        // 存储检测对象List
        Set<Object> structureTestObjectIdSet = new HashSet<>();
        List<StandardMethod> result = new ArrayList<>();
 
        EasyExcel.read(file.getInputStream(), StandardMethod.class, new AnalysisEventListener<StandardMethod>() {
            @Override
            public void invoke(StandardMethod data, AnalysisContext context) {
                // 去除第一行表头,EasyExcel 自动处理表头,这里无需额外处理
                // 存储唯一检测对象
                String structureTestObjectId = data.getStructureTestObjectId();
                Object idObj = getFirstIdFromJson(structureTestObjectId);
                if (idObj != null) {
                    structureTestObjectIdSet.add(idObj);
                }
                result.add(data);
            }
 
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 解析完成后执行添加操作
                addStructureTest(new ArrayList<>(structureTestObjectIdSet), result);
            }
        }).sheet().doRead();
    }
 
    private Object getFirstIdFromJson(String json) {
        // 简单解析 JSON 数组获取第一个元素
        if (json != null && json.startsWith("[") && json.contains(",")) {
            return json.substring(2, json.indexOf(","));
        } else if (json != null && json.startsWith("[")) {
            return json.substring(1, json.length() - 1);
        }
        return null;
    }
 
    public void addStructureTest(List<Object> structureTestObjectIdList, List<StandardMethod> standardMethodList) {
        // 用于存储新增、更新和删除的数据
        List<StandardMethod> updateList = new ArrayList<>();
        List<Integer> deleteListId = new ArrayList<>();
        List<StandardMethod> addList = new ArrayList<>();
 
        // 先将 Excel 数据按 code 分组,并合并 field
        Map<String, StandardMethod> excelDataMap = new HashMap<>();
        for (StandardMethod excelMethod : standardMethodList) {
            String key = generateKey(excelMethod);
            if (excelDataMap.containsKey(key)) {
                // 如果已存在相同的 code,则合并 field
                StandardMethod existingMethod = excelDataMap.get(key);
                String mergedField = mergeFields(existingMethod.getField(), excelMethod.getField());
                existingMethod.setField(mergedField);
            } else {
                // 否则直接添加到 map 中
                excelDataMap.put(key, excelMethod);
            }
        }
 
        // 查询数据库中的分组数据
        List<StandardMethod> allDbMethods = new ArrayList<>();
        for (Object j : structureTestObjectIdList) {
            List<StandardMethod> standardMethods = baseMapper.selectList(
                    new LambdaQueryWrapper<StandardMethod>()
                            .apply("JSON_CONTAINS(structure_test_object_id, {0})", j) // MySQL JSON 查询
            );
            allDbMethods.addAll(standardMethods);
        }
 
        // 将数据库数据按 code 分组,并合并 field
        Map<String, StandardMethod> dbDataMap = new HashMap<>();
        for (StandardMethod dbMethod : allDbMethods) {
            String key = generateKey(dbMethod);
            if (dbDataMap.containsKey(key)) {
                // 如果已存在相同的 code,则合并 field
                StandardMethod existingMethod = dbDataMap.get(key);
                String mergedField = mergeFields(existingMethod.getField(), dbMethod.getField());
                existingMethod.setField(mergedField);
            } else {
                // 否则直接添加到 map 中
                dbDataMap.put(key, dbMethod);
            }
        }
 
        // 处理更新和新增
        for (Map.Entry<String, StandardMethod> entry : excelDataMap.entrySet()) {
            String key = entry.getKey();
            StandardMethod excelMethod = entry.getValue();
            StandardMethod dbMethod = dbDataMap.get(key);
            if (dbMethod != null) {
                // 更新
                excelMethod.setId(dbMethod.getId());
                updateList.add(excelMethod);
            } else {
                // 新增
                addList.add(excelMethod);
            }
        }
 
        // 处理删除
        for (Map.Entry<String, StandardMethod> entry : dbDataMap.entrySet()) {
            String key = entry.getKey();
            if (!excelDataMap.containsKey(key)) {
                StandardMethod dbMethod = entry.getValue();
                deleteListId.add(dbMethod.getId());
            }
        }
 
            // 执行批量操作
        if (!addList.isEmpty()) {
            // 新增
            baseMapper.insertBatchSomeColumn(addList);
        }
 
        if (!deleteListId.isEmpty()) {
            // 删除
            baseMapper.deleteBatchIds(deleteListId);
        }
 
        if (!updateList.isEmpty()) {
            // 更新
            updateList.forEach(i -> {
                baseMapper.updateById(i);
            });
        }
    }
 
    private String mergeFields(String field1, String field2) {
        if (field1 == null || field1.isEmpty()) {
            return field2;
        }
        if (field2 == null || field2.isEmpty()) {
            return field1;
        }
 
        // 使用 Set 去重
        String[] fields1 = field1.split(",");
        String[] fields2 = field2.split(",");
        Set<String> uniqueFields = new HashSet<>(Arrays.asList(fields1));
        uniqueFields.addAll(Arrays.asList(fields2));
 
        // 返回逗号拼接的结果
        return String.join(",", uniqueFields);
    }
 
    private String generateKey(StandardMethod method) {
        return method.getCode();
    }
 
    // 格式化数据
    public StandardMethod formatData(List<Object> list) {
        StandardMethod standardMethod = new StandardMethod();
        standardMethod.setField(list.get(1).toString());
        // 造格式
        List<List<Object>> structureTestObjectId = new ArrayList<>();
        if (ObjectUtils.isEmpty(list.get(3))) {
            structureTestObjectId.add(Arrays.asList(list.get(2)));
        } else {
            structureTestObjectId.add(Arrays.asList(list.get(2), list.get(3)));
        }
        standardMethod.setStructureTestObjectId(JSONUtil.toJsonStr(structureTestObjectId));
        standardMethod.setCode(list.get(4).toString());
        standardMethod.setName(list.get(5).toString());
        standardMethod.setNameEn(list.get(6).toString());
        if (!Objects.equals(list.get(7), null)) {
            standardMethod.setRemark(list.get(7).toString());
        }
        standardMethod.setQualificationId(list.get(8).toString());
        if (ObjectUtils.isNotEmpty(list.get(9))) {
            if (list.get(9).equals("是")) {
                standardMethod.setIsProduct(1);
            } else if (list.get(9).equals("否")) {
                standardMethod.setIsProduct(0);
            }
        }
        if (ObjectUtils.isNotEmpty(list.get(10))) {
            if (list.get(10).equals("是")) {
                standardMethod.setIsUse(1);
            } else if (list.get(9).equals("否")) {
                standardMethod.setIsUse(0);
            }
        }
        return standardMethod;
    }
 
}