yanderong
2026-09-11 d7287e75168bec060c2ad8b6202d4df76ebc9cb4
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
package com.ruoyi.other.service.impl;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.other.api.domain.TStationCollect;
import com.ruoyi.other.api.domain.TStationInfo;
import com.ruoyi.other.mapper.TStationCollectMapper;
import com.ruoyi.other.mapper.TStationInfoMapper;
import com.ruoyi.other.query.StationCollectQuery;
import com.ruoyi.other.service.TStationCollectService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * 电站逆变器服务实现。
 */
@Service
public class TStationCollectServiceImpl
        extends ServiceImpl<TStationCollectMapper, TStationCollect>
        implements TStationCollectService {
 
    @Resource
    private TStationInfoMapper stationInfoMapper;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addStationCollect(TStationCollect stationCollect) {
        validate(stationCollect);
        stationCollect.setCollectId("1"+System.currentTimeMillis());
        stationCollect.setDataSource(1);
        fillDefaults(stationCollect);
        stationCollect.setId(null);
        stationCollect.setCreateTime(LocalDateTime.now());
        stationCollect.setUpdateTime(LocalDateTime.now());
        return save(stationCollect);
    }
 
    @Override
    public PageInfo<TStationCollect> pageList(StationCollectQuery query) {
        if (query == null) query = new StationCollectQuery();
        PageInfo<TStationCollect> page = new PageInfo<>(query.getPageCurr(), query.getPageSize());
        lambdaQuery()
                .eq(query.getPlatformId() != null, TStationCollect::getPlatformId, query.getPlatformId())
                .like(StringUtils.isNotBlank(query.getStationName()), TStationCollect::getStationName, query.getStationName())
                .like(StringUtils.isNotBlank(query.getCollectName()), TStationCollect::getCollectName, query.getCollectName())
                .like(StringUtils.isNotBlank(query.getDeviceModel()), TStationCollect::getDeviceModel, query.getDeviceModel())
                .like(StringUtils.isNotBlank(query.getInverterId()), TStationCollect::getInverterId, query.getInverterId())
                .eq(StringUtils.isNotBlank(query.getStatus()), TStationCollect::getStatus, query.getStatus())
                .in(StringUtils.isBlank(query.getStatus()) && Boolean.TRUE.equals(query.getAbnormalOnly()),
                        TStationCollect::getStatus, "2", "3")
                .orderByAsc(TStationCollect::getSortOrder).orderByDesc(TStationCollect::getCreateTime).page(page);
        fillStationAddress(page.getRecords());
        return page;
    }
 
    @Override
    public TStationCollect getStationCollectDetail(Long id) {
        if (id == null) {
            return null;
        }
        TStationCollect stationCollect = getById(id);
        if (stationCollect != null) {
            List<TStationCollect> stationCollectList = new ArrayList<>(1);
            stationCollectList.add(stationCollect);
            fillStationAddress(stationCollectList);
        }
        return stationCollect;
    }
 
    private void fillStationAddress(List<TStationCollect> stationCollectList) {
        if (stationCollectList == null || stationCollectList.isEmpty()) {
            return;
        }
        Set<String> stationIds = stationCollectList.stream()
                .map(TStationCollect::getStationId)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());
        if (stationIds.isEmpty()) {
            return;
        }
 
        List<TStationInfo> stationInfoList = stationInfoMapper.selectList(
                new LambdaQueryWrapper<TStationInfo>()
                        .select(TStationInfo::getStationId,
                                TStationInfo::getProvinceName,
                                TStationInfo::getCityName,
                                TStationInfo::getAreaName,
                                TStationInfo::getAddress)
                        .in(TStationInfo::getStationId, stationIds));
        Map<String, TStationInfo> stationInfoMap = stationInfoList.stream()
                .filter(item -> StringUtils.isNotBlank(item.getStationId()))
                .collect(Collectors.toMap(TStationInfo::getStationId,
                        Function.identity(), (first, ignored) -> first));
 
        for (TStationCollect stationCollect : stationCollectList) {
            TStationInfo stationInfo = stationInfoMap.get(stationCollect.getStationId());
            if (stationInfo != null) {
                stationCollect.setProvinceName(stationInfo.getProvinceName());
                stationCollect.setCityName(stationInfo.getCityName());
                stationCollect.setAreaName(stationInfo.getAreaName());
                stationCollect.setAddress(stationInfo.getAddress());
            }
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStationCollect(TStationCollect stationCollect) {
        if (stationCollect == null || stationCollect.getId() == null) {
            throw new ServiceException("逆变器记录ID不能为空");
        }
        if (getById(stationCollect.getId()) == null) {
            throw new ServiceException("逆变器记录不存在");
        }
        validate(stationCollect);
        if (lambdaQuery().eq(TStationCollect::getCollectId, stationCollect.getCollectId())
                .ne(TStationCollect::getId, stationCollect.getId()).count() > 0) {
            throw new ServiceException("逆变器ID已存在");
        }
        stationCollect.setCreateBy(null);
        stationCollect.setCreateTime(null);
        stationCollect.setDelFlag(null);
        stationCollect.setUpdateTime(LocalDateTime.now());
        return updateById(stationCollect);
    }
 
    /**
     * 将第三方逆变器基础数据转换为实体并批量保存。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCollectBaseList(JSONArray collectBaseList) {
        if (collectBaseList == null || collectBaseList.isEmpty()) {
            return false;
        }
 
        Set<String> existingKeys = getExistingCollectKeys(); // 数据库中存在的所有逆变器ID
        List<TStationCollect> stationCollectList = new ArrayList<>(collectBaseList.size());
        for (Object item : collectBaseList) {
            JSONObject jsonObject = JSONObject.parseObject(item.toString());
            TStationCollect stationCollect = buildStationCollect(jsonObject);
            if (existingKeys.contains(stationCollect.getCollectId())) {
                continue;
            }
            stationCollectList.add(stationCollect);
        }
        return !stationCollectList.isEmpty() && saveBatch(stationCollectList);
    }
 
    private TStationCollect buildStationCollect(JSONObject jsonObject) {
        String stationId = jsonObject.getString("stationId");
        String stationName = jsonObject.getString("stationName");
        String collectName = jsonObject.getString("collectName");
        TStationCollect stationCollect = new TStationCollect();
        stationCollect.setPlatformId(0L);
        stationCollect.setStationId(stationId);
        stationCollect.setStationName(stationName);
        stationCollect.setCollectId(jsonObject.getString("collectId"));
        stationCollect.setCollectName(collectName);
        stationCollect.setDeviceModel(jsonObject.getString("deviceModel"));
        stationCollect.setInverterId(jsonObject.getString("inverterId"));
        stationCollect.setInstalledCapacity(jsonObject.getString("capacity"));
        stationCollect.setPowerNum(parsePowerNum(jsonObject.getString("powerNum")));
        stationCollect.setProvinceName(jsonObject.getString("province"));
        stationCollect.setCityName(jsonObject.getString("city"));
        stationCollect.setAreaName(jsonObject.getString("district"));
        stationCollect.setAddress(jsonObject.getString("address"));
        stationCollect.setLatitude(jsonObject.getString("lat"));
        stationCollect.setLongitude(jsonObject.getString("lon"));
        stationCollect.setDataSource(2);
        stationCollect.setSyncTime(LocalDateTime.now());
        stationCollect.setCreateTime(parseDateTime(jsonObject.getString("saveTime")));
        stationCollect.setUpdateTime(LocalDateTime.now());
        fillDefaults(stationCollect);
        return stationCollect;
    }
 
    private Set<String> getExistingCollectKeys() {
        List<TStationCollect> existingList = lambdaQuery().select(TStationCollect::getCollectId).list();
        Set<String> existingKeys = new HashSet<>();
        for (TStationCollect stationCollect : existingList) {
            existingKeys.add(stationCollect.getCollectId());
        }
        return existingKeys;
    }
 
 
    private void validate(TStationCollect stationCollect) {
        if (stationCollect == null) {
            throw new ServiceException("电站逆变器参数不能为空");
        }
        if (stationCollect.getStationId() == null) {
            throw new ServiceException("电站ID不能为空");
        }
        if (StringUtils.isBlank(stationCollect.getStationName())) {
            throw new ServiceException("电站名称不能为空");
        }
        if (StringUtils.isBlank(stationCollect.getCollectName())) {
            throw new ServiceException("逆变器名称不能为空");
        }
    }
 
    private void fillDefaults(TStationCollect stationCollect) {
        stationCollect.setPlatformId(stationCollect.getPlatformId() == null ? 0L : stationCollect.getPlatformId());
        stationCollect.setPowerNum(stationCollect.getPowerNum() == null ? 0 : stationCollect.getPowerNum());
        stationCollect.setStatus(StringUtils.isBlank(stationCollect.getStatus()) ? "0" : stationCollect.getStatus());
        stationCollect.setSortOrder(stationCollect.getSortOrder() == null ? 0 : stationCollect.getSortOrder());
        stationCollect.setCreateBy(StringUtils.defaultString(stationCollect.getCreateBy()));
        stationCollect.setUpdateBy(StringUtils.defaultString(stationCollect.getUpdateBy()));
        stationCollect.setDelFlag("0");
    }
 
    private Long parseLong(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        try {
            return Long.valueOf(value);
        } catch (NumberFormatException exception) {
            return null;
        }
    }
 
    private BigDecimal parseBigDecimal(String value) {
        if (StringUtils.isBlank(value)) {
            return BigDecimal.ZERO;
        }
        try {
            return new BigDecimal(value);
        } catch (NumberFormatException exception) {
            return BigDecimal.ZERO;
        }
    }
 
    private Integer parsePowerNum(String value) {
        if (StringUtils.isBlank(value)) {
            return 0;
        }
        String number = value.replaceAll("[^0-9.]", "");
        if (StringUtils.isBlank(number)) {
            return 0;
        }
        try {
            return new BigDecimal(number).intValue();
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
 
    private Integer parseInteger(String value) {
        if (StringUtils.isBlank(value)) {
            return 0;
        }
        try {
            return Integer.valueOf(value);
        } catch (NumberFormatException exception) {
            return parsePowerNum(value);
        }
    }
 
    private LocalDateTime parseDateTime(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        try {
            return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } catch (DateTimeParseException exception) {
            return null;
        }
    }
 
    private String firstNotBlank(String preferred, String fallback) {
        return StringUtils.isNotBlank(preferred) ? preferred : fallback;
    }
 
 
    /**
     * 根据ids删除数据时,校验示范存在第三方同步的数据,第三方同步的数据不允许删除
     * @param ids 数据id
     * @return true可以删除,false不可以删除
     */
    public Boolean validateDelete(Long[] ids) {
        if(ids != null && ids.length > 0) {
            List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
            List<TStationCollect> infoList = lambdaQuery().eq(TStationCollect::getDataSource, 2).in(TStationCollect::getId, idList).list();
            if(CollectionUtils.isNotEmpty(infoList) && !infoList.isEmpty()) {
                return false;
            }
        }
        return true;
    }
 
    /**
     * 将华为 FusionSolar 设备列表转换为逆变器记录并批量保存。
     * devDn 作为设备唯一标识(接口未提供时使用 esnCode)。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCollectHuaWeiList(JSONArray devList) {
        if (devList == null || devList.isEmpty()) {
            return false;
        }
        Set<String> existingKeys = getExistingCollectKeys();
        Set<String> pendingKeys = new HashSet<>();
        List<TStationCollect> insertList = new ArrayList<>(devList.size());
        for (Object item : devList) {
            if (item == null) {
                continue;
            }
            JSONObject json = JSONObject.parseObject(item.toString());
            String collectId = firstNotBlank(json.getString("devDn"), json.getString("esnCode"));
            String stationId = json.getString("stationCode");
            if (StringUtils.isBlank(collectId) || StringUtils.isBlank(stationId)
                    || existingKeys.contains(collectId) || !pendingKeys.add(collectId)) {
                continue;
            }
            TStationCollect collect = new TStationCollect();
            collect.setPlatformId(1L);
            collect.setStationId(stationId);
            collect.setStationName(firstNotBlank(json.getString("stationName"), ""));
            collect.setCollectId(collectId);
            collect.setCollectName(firstNotBlank(json.getString("devName"), collectId));
            collect.setDeviceModel(firstNotBlank(json.getString("invType"), json.getString("model")));
            collect.setInverterId(json.getString("esnCode"));
            collect.setInstalledCapacity(firstNotBlank(json.getString("capacity"), "0"));
            collect.setPowerNum(parseInteger(json.getString("optimizerNumber")));
            collect.setLatitude(json.getString("latitude"));
            collect.setLongitude(json.getString("longitude"));
            collect.setStatus("1");
            collect.setDataSource(2);
            collect.setSyncTime(LocalDateTime.now());
            collect.setCreateTime(LocalDateTime.now());
            collect.setUpdateTime(LocalDateTime.now());
            fillDefaults(collect);
            insertList.add(collect);
        }
        return CollectionUtils.isNotEmpty(insertList) && saveBatch(insertList);
    }
}