lyh
15 小时以前 78aeb8a8c97a884a640d46755e4be706bde48b7d
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
package com.lxzn.base.controller;
 
import com.lxzn.base.service.impl.DataImportService;
import com.lxzn.framework.domain.nc.*;
import com.lxzn.framework.domain.ucenter.User;
import com.lxzn.framework.model.response.CommonCode;
import com.lxzn.framework.model.response.ResponseResult;
import com.lxzn.nc.service.*;
import com.lxzn.ucenter.service.IUserService;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
@RestController
@RequestMapping("/receiver")
public class DataReceiverController {
 
    private static final Logger logger = LoggerFactory.getLogger(DataReceiverController.class);
 
    // 服务地址配置
    @Value("${dnc.server.url}")
    private String serverUrl;
 
    @Autowired
    private RestTemplate restTemplate;
 
    @Autowired
    private DataImportService dataImportService;
 
    @Autowired
    private IProductInfoService iProductInfoService;
    @Autowired
    private IComponentInfoService iComponentInfoService;
    @Autowired
    private IPartsInfoService iPartsInfoService;
    @Autowired
    private IProcessInfoService iProcessInfoService;
    @Autowired
    private IProcessStreamService iProcessStreamService;
    @Autowired
    private IDocInfoService iDocInfoService;
    @Autowired
    private IDocFileService iDocFileService;
    @Autowired
    private IProductPermissionService productPermissionService;
    @Autowired
    private IComponentPermissionService componentPermissionService;
    @Autowired
    private IPartsPermissionService partsPermissionService;
    @Autowired
    private IPermissionStreamService permissionStreamService;
    @Autowired
    private IUserService iUserService;
    // 数据类型映射
    private static final Map<String, Class<?>> DATA_TYPE_MAPPING = new HashMap<>();
    static {
        DATA_TYPE_MAPPING.put("productInfoList", ProductInfo.class);
        DATA_TYPE_MAPPING.put("componentInfoList", ComponentInfo.class);
        DATA_TYPE_MAPPING.put("partsInfoList", PartsInfo.class);
        DATA_TYPE_MAPPING.put("processStreamList", ProcessStream.class);
        DATA_TYPE_MAPPING.put("processInfoList", ProcessInfo.class);
        DATA_TYPE_MAPPING.put("docInfoList", DocInfo.class);
        DATA_TYPE_MAPPING.put("docFileList", DocFile.class);
    }
 
    @GetMapping("/syncData")
    public ResponseResult syncData() {
        try {
            // 1. 获取原始数据
            Map<String, List<?>> rawData = fetchDataFromServer();
            User user=iUserService.findByUsername("admin");
            // 2. 并行处理每个数据集
            rawData.forEach((dataType, rawList) -> {
                Class<?> targetType = DATA_TYPE_MAPPING.get(dataType);
                if (targetType != null) {
                    try {
                        List<?> convertedList = TypeConverter.convertList(rawList, targetType);
                        switch (dataType){
                            case "productInfoList":
                                List<ProductInfo> list = (List<ProductInfo>) convertedList;
                                //添加用户权限
                                for (ProductInfo productInfo : list) {
                                    ProductPermission productPermission = new ProductPermission();
                                    productPermission.setUserId(user.getUserId());
                                    productPermission.setProductId(productInfo.getProductId());
                                    productPermissionService.save(productPermission);
                                    PermissionStream stream = new PermissionStream();
                                    stream.setProductId(productInfo.getProductId());
                                    stream.setUserId(user.getUserId());
                                    permissionStreamService.save(stream);
                                }
                                iProductInfoService.saveBatch(list);
                                break;
                            case "componentInfoList":
                                List<ComponentInfo> list1 = (List<ComponentInfo>) convertedList;
                                iComponentInfoService.saveBatch(list1);
                                //添加用户权限
                                for (ComponentInfo componentInfo : list1) {
                                    ComponentPermission componentPermission = new ComponentPermission();
                                    componentPermission.setUserId(user.getUserId());
                                    componentPermission.setComponentId(componentInfo.getComponentId());
                                    componentPermissionService.save(componentPermission);
                                    PermissionStream stream = new PermissionStream();
                                    stream.setProductId(componentInfo.getProductId());
                                    stream.setComponentId(componentInfo.getComponentId());
                                    stream.setUserId(user.getUserId());
                                    permissionStreamService.save(stream);
                                }
                                break;
                            case "partsInfoList":
                                List<PartsInfo> list2 = (List<PartsInfo>) convertedList;
                                //添加用户权限
                                for (PartsInfo partsInfo : list2) {
                                    PartsPermission partsPermission = new PartsPermission();
                                    partsPermission.setUserId(user.getUserId());
                                    partsPermission.setPartsId(partsInfo.getPartsId());
                                    partsPermissionService.save(partsPermission);
                                    PermissionStream stream = new PermissionStream();
                                    stream.setProductId(partsInfo.getProductId());
                                    stream.setComponentId(partsInfo.getComponentId());
                                    stream.setPartsId(partsInfo.getPartsId());
                                    stream.setUserId(user.getUserId());
                                    permissionStreamService.save(stream);
                                }
                                iPartsInfoService.saveBatch(list2);
                                break;
                            case "processStreamList":
                                List<ProcessStream> list3 = (List<ProcessStream>) convertedList;
                                iProcessStreamService.saveBatch(list3);
                                break;
                            case "processInfoList":
                                List<ProcessInfo> list4 = (List<ProcessInfo>) convertedList;
                                iProcessInfoService.saveBatch(list4);
                                break;
                            case "docInfoList":
                                List<DocInfo> list5 = (List<DocInfo>) convertedList;
                                iDocInfoService.saveBatch(list5);
                                break;
                            case "docFileList":
                                List<DocFile> list6 = (List<DocFile>) convertedList;
                                iDocFileService.saveBatch(list6);
                                break;
                        }
                        logger.info("成功同步 {} 条 {} 数据", convertedList.size(), dataType);
                    } catch (TypeConverter.TypeConversionException e) {
                        logger.error("数据类型 {} 转换失败: {}", dataType, e.getMessage());
                    }
                }
            });
 
        } catch (Exception e) {
            logger.error("数据同步失败: {}", e.getMessage(), e);
            throw new RuntimeException("数据同步失败", e);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }
 
 
    private Map<String, List<?>> fetchDataFromServer() {
        String apiUrl = serverUrl + "/outer/fileNcSendData";
        ParameterizedTypeReference<Map<String, List<?>>> typeRef =
                new ParameterizedTypeReference<Map<String, List<?>>>() {};
 
        ResponseEntity<Map<String, List<?>>> response =
                restTemplate.exchange(apiUrl, HttpMethod.GET, null, typeRef);
 
        if (!response.getStatusCode().is2xxSuccessful()) {
            throw new RuntimeException("调用服务端接口失败");
        }
        return response.getBody();
    }
 
    private ImportResult processDataSet(String dataType, List<?> rawList) {
        try {
            Class<T> targetClass = (Class<T>) DATA_TYPE_MAPPING.get(dataType);
 
            if (targetClass == null) {
                return ImportResult.error("未知数据类型");
            }
            // 2. 类型安全转换
            List<T> entities = convertList(rawList, targetClass);
            // 3. 执行批量插入
            int count = dataImportService.batchInsert(entities, targetClass);
            return ImportResult.success(count);
        } catch (Exception e) {
            logger.error("{} 数据处理失败", dataType, e);
            return ImportResult.error(e.getMessage());
        }
    }
 
    @SuppressWarnings("unchecked")
    private <T> List<T> convertList(List<?> rawList, Class<T> targetClass) {
        return rawList.stream()
                .map(item -> {
                    if (targetClass.isInstance(item)) {
                        return targetClass.cast(item);
                    }
                    throw new ClassCastException("类型转换失败: "
                            + item.getClass() + " -> " + targetClass);
                })
                .collect(Collectors.toList());
    }
 
    // 导入结果封装
    public static class ImportResult {
        private boolean success;
        private String message;
        private int count;
 
        public static ImportResult success(int count) {
            ImportResult result = new ImportResult();
            result.success = true;
            result.count = count;
            result.message = "成功插入 " + count + " 条记录";
            return result;
        }
 
        public static ImportResult error(String message) {
            ImportResult result = new ImportResult();
            result.success = false;
            result.message = message;
            return result;
        }
    }
}