puzhibing
2026-09-03 121f555dd131687710dea6fc69c3e53aa3dde196
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
package com.ruoyi.order.service.impl;
 
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.account.api.feignClient.VinManagementClient;
import com.ruoyi.chargingPile.api.dto.GetSiteListDTO;
import com.ruoyi.chargingPile.api.feignClient.ChargingGunClient;
import com.ruoyi.chargingPile.api.feignClient.ChargingPileClient;
import com.ruoyi.chargingPile.api.feignClient.SiteClient;
import com.ruoyi.chargingPile.api.model.Site;
import com.ruoyi.chargingPile.api.model.TChargingGun;
import com.ruoyi.chargingPile.api.model.TChargingPile;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.integration.api.feignClient.SendMessageClient;
import com.ruoyi.integration.api.model.PlatformStopCharging;
import com.ruoyi.integration.api.model.UploadRealTimeMonitoringData;
import com.ruoyi.order.api.model.TVinChargingOrder;
import com.ruoyi.order.api.query.VinChargingOrderQuery;
import com.ruoyi.order.api.vo.ChargingOrderVO;
import com.ruoyi.order.api.vo.VinChargingStatusVO;
import com.ruoyi.order.dto.MyVinChargingOrderList;
import com.ruoyi.order.mapper.TVinChargingOrderMapper;
import com.ruoyi.order.service.TVinChargingOrderService;
import com.ruoyi.order.util.mongodb.service.UploadRealTimeMonitoringDataService;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
 
@Service
public class TVinChargingOrderServiceImpl extends ServiceImpl<TVinChargingOrderMapper, TVinChargingOrder>
        implements TVinChargingOrderService {
 
    @Resource
    private TokenService tokenService;
    @Resource
    private VinManagementClient vinManagementClient;
    @Resource
    private SiteClient siteClient;
    @Resource
    private ChargingGunClient chargingGunClient;
    @Resource
    private ChargingPileClient chargingPileClient;
    @Resource
    private SendMessageClient sendMessageClient;
    @Resource
    private UploadRealTimeMonitoringDataService monitoringDataService;
 
    @Override
    public PageInfo<ChargingOrderVO> pageList(VinChargingOrderQuery query) {
        int pageCurr = query.getPageCurr() == null || query.getPageCurr() < 1 ? 1 : query.getPageCurr();
        int pageSize = query.getPageSize() == null || query.getPageSize() < 1 ? 50 : query.getPageSize();
        setAuthSiteIds(query);
        PageInfo<ChargingOrderVO> page = new PageInfo<>(pageCurr, pageSize);
        long total = baseMapper.count(query);
        page.setTotal(total);
        List<ChargingOrderVO> records = total == 0 ? Collections.emptyList()
                : baseMapper.pageList(query, (long) (pageCurr - 1) * pageSize, pageSize);
        fillExtra(records);
        page.setRecords(records);
        return page;
    }
 
    @Override
    public PageInfo<MyVinChargingOrderList> pageAppletOrders(Integer pageCurr, Integer pageSize) {
        int current = pageCurr == null || pageCurr < 1 ? 1 : pageCurr;
        int size = pageSize == null || pageSize < 1 ? 10 : Math.min(pageSize, 100);
        PageInfo<MyVinChargingOrderList> page = new PageInfo<>(current, size);
        if (tokenService.getLoginUserApplet() == null || tokenService.getLoginUserApplet().getUserId() == null) {
            page.setTotal(0);
            page.setRecords(Collections.emptyList());
            return page;
        }
        Long apppUserId = tokenService.getLoginUserApplet().getUserId();
        R<List<Long>> vinIdResponse = vinManagementClient.getVinIdsByApppUserId(apppUserId);
        List<Long> vinIds = vinIdResponse == null ? Collections.emptyList()
                : Optional.ofNullable(vinIdResponse.getData()).orElse(Collections.emptyList());
        if (vinIds.isEmpty()) {
            page.setTotal(0);
            page.setRecords(Collections.emptyList());
            return page;
        }
        long total = baseMapper.countAppletOrders(vinIds);
        page.setTotal(total);
        List<MyVinChargingOrderList> records = total == 0 ? Collections.emptyList()
                : baseMapper.pageAppletOrders(vinIds, (long) (current - 1) * size, size);
        fillAppletExtra(records);
        page.setRecords(records);
        return page;
    }
 
    @Override
    public List<VinChargingStatusVO> getChargingVinStatus(List<Long> vinIds) {
        if (vinIds == null || vinIds.isEmpty()) {
            return Collections.emptyList();
        }
        List<Long> distinctVinIds = vinIds.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        return distinctVinIds.isEmpty() ? Collections.emptyList() : baseMapper.getChargingVinStatus(distinctVinIds);
    }
 
    @Override
    public List<ChargingOrderVO> exportList(VinChargingOrderQuery query) {
        setAuthSiteIds(query);
        long total = baseMapper.count(query);
        List<ChargingOrderVO> result = new ArrayList<>();
        for (long offset = 0; offset < total; offset += 5000) {
            List<ChargingOrderVO> batch = baseMapper.pageList(query, offset, 5000);
            if (batch == null || batch.isEmpty()) {
                break;
            }
            result.addAll(batch);
        }
        fillExtra(result);
        fillRealtimeData(result);
        return result;
    }
 
    @Override
    public Map<String, Object> summary(VinChargingOrderQuery query) {
        setAuthSiteIds(query);
        Map<String, Object> result = baseMapper.summary(query);
        return result == null ? new HashMap<>() : result;
    }
 
    @Override
    public Map<String, Object> detail(Long chargingOrderId) {
        TVinChargingOrder order = getAuthorizedOrder(chargingOrderId);
        if (order == null) {
            return Collections.emptyMap();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("id", order.getId() == null ? null : String.valueOf(order.getId()));
        result.put("code", order.getCode());
        result.put("vin", order.getActualVin());
        result.put("actualVin", order.getActualVin());
        result.put("expectedVin", order.getExpectedVin());
        result.put("plateNum", order.getPlateNum());
        result.put("phone", order.getPhone());
        result.put("status", order.getStatus());
        result.put("siteId", order.getSiteId());
        result.put("chargingPileId", order.getChargingPileId());
        result.put("chargingGunId", order.getChargingGunId());
        result.put("startTime", order.getStartTime());
        result.put("endTime", order.getEndTime());
        result.put("chargingCapacity", order.getChargingCapacity());
        result.put("paymentAmount", order.getPaymentAmount());
        result.put("electrovalence", order.getElectrovalence());
        result.put("serviceCharge", order.getServiceCharge());
        if (order.getStartTime() != null && order.getEndTime() != null) {
            result.put("chargingSecond", ChronoUnit.SECONDS.between(order.getStartTime(), order.getEndTime()));
        }
        List<Site> sites = order.getSiteId() == null ? Collections.emptyList()
                : Optional.ofNullable(siteClient.getSiteByIds(Collections.singletonList(order.getSiteId())).getData()).orElse(Collections.emptyList());
        Site site = sites.stream().findFirst().orElse(null);
        result.put("siteName", site == null ? null : site.getName());
        List<TChargingGun> guns = order.getChargingGunId() == null ? Collections.emptyList()
                : Optional.ofNullable(chargingGunClient.getChargingGunByIds(Collections.singletonList(order.getChargingGunId())).getData()).orElse(Collections.emptyList());
        TChargingGun gun = guns.stream().findFirst().orElse(null);
        result.put("terminalName", gun == null ? null : gun.getName());
        List<UploadRealTimeMonitoringData> monitoring = monitoringDataService.getDataByOrderCodeAsc(order.getCode());
        if (monitoring == null) {
            monitoring = Collections.emptyList();
        }
        for (UploadRealTimeMonitoringData data : monitoring) {
            if (data.getOutput_current() != null && data.getOutput_voltage() != null) {
                data.setPower(data.getOutput_voltage().multiply(data.getOutput_current()).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));
            }
        }
        UploadRealTimeMonitoringData latestMonitoring = monitoring.isEmpty() ? null : monitoring.get(monitoring.size() - 1);
        result.put("cdElectronic", latestMonitoring == null ? null : latestMonitoring.getOutput_current());
        result.put("cdVoltage", latestMonitoring == null ? null : latestMonitoring.getOutput_voltage());
        result.put("totalPower", latestMonitoring == null ? null : latestMonitoring.getPower());
        result.put("surplus", latestMonitoring == null ? null : latestMonitoring.getSoc());
        result.put("list", monitoring);
        result.put("list1", baseMapper.accountingStrategyList(order.getId()));
        return result;
    }
 
    @Override
    public AjaxResult stopCharging(String chargingOrderId, Integer chargingGunId) {
        Long orderId;
        try {
            orderId = Long.valueOf(chargingOrderId);
        } catch (NumberFormatException e) {
            return AjaxResult.error("VIN码充电订单ID无效");
        }
        TVinChargingOrder order = getAuthorizedOrder(orderId);
        if (order == null) {
            return AjaxResult.error("VIN码充电订单不存在或无权操作");
        }
        if (order.getChargingGunId() == null || !order.getChargingGunId().equals(chargingGunId)) {
            return AjaxResult.error("充电枪与订单不匹配");
        }
        Integer status = order.getStatus();
        if (status == null || !status.equals(3)) {
            return AjaxResult.error(status != null && (status.equals(4) || status.equals(5)) ? "不能重复操作" : "还未开始充电");
        }
        TChargingGun chargingGun = chargingGunClient.getChargingGunById(chargingGunId).getData();
        TChargingPile chargingPile = order.getChargingPileId() == null ? null
                : chargingPileClient.getChargingPileById(order.getChargingPileId()).getData();
        if (chargingGun == null || chargingPile == null) {
            return AjaxResult.error("未找到订单对应的充电设备");
        }
        order.setStatus(4);
        order.setEndMode(1);
        order.setEndTime(LocalDateTime.now());
        if (!updateById(order)) {
            return AjaxResult.error("更新VIN码充电订单状态失败");
        }
        PlatformStopCharging command = new PlatformStopCharging();
        command.setCharging_pile_code(chargingPile.getCode());
        command.setCharging_gun_code(chargingGun.getCode());
        sendMessageClient.platformStopCharging(command);
        return AjaxResult.success();
    }
 
    @Override
    public List<Map<String, Object>> accountingStrategyList(Long chargingOrderId) {
        TVinChargingOrder order = getAuthorizedOrder(chargingOrderId);
        return order == null ? Collections.emptyList() : baseMapper.accountingStrategyList(chargingOrderId);
    }
 
    private void setAuthSiteIds(VinChargingOrderQuery query) {
        List<Integer> authorizedSiteIds = getAuthorizedSiteIds();
        if (query.getSiteId() != null) {
            authorizedSiteIds = authorizedSiteIds.contains(query.getSiteId())
                    ? Collections.singletonList(query.getSiteId()) : Collections.singletonList(-1);
        }
        if (authorizedSiteIds.isEmpty()) {
            authorizedSiteIds = Collections.singletonList(-1);
        }
        query.setSiteIds(authorizedSiteIds);
    }
 
    private TVinChargingOrder getAuthorizedOrder(Long chargingOrderId) {
        if (chargingOrderId == null) {
            return null;
        }
        TVinChargingOrder order = getById(chargingOrderId);
        if (order == null || order.getSiteId() == null || !getAuthorizedSiteIds().contains(order.getSiteId())) {
            return null;
        }
        return order;
    }
 
    private List<Integer> getAuthorizedSiteIds() {
        Long userId = tokenService.getLoginUser().getUserid();
        if (userId == null) {
            return Collections.emptyList();
        }
        return Optional.ofNullable(siteClient.getSiteListByUserId(userId).getData())
                .orElse(Collections.emptyList()).stream().map(GetSiteListDTO::getId).collect(Collectors.toList());
    }
 
    private void fillAppletExtra(List<MyVinChargingOrderList> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<Integer> siteIds = list.stream().map(MyVinChargingOrderList::getSiteId)
                .filter(Objects::nonNull).distinct().collect(Collectors.toList());
        List<Integer> gunIds = list.stream().map(MyVinChargingOrderList::getChargingGunId)
                .filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<Integer, Site> sites = siteIds.isEmpty() ? Collections.emptyMap()
                : Optional.ofNullable(siteClient.getSiteByIds(siteIds).getData()).orElse(Collections.emptyList()).stream()
                .collect(Collectors.toMap(Site::getId, item -> item, (a, b) -> a));
        Map<Integer, TChargingGun> guns = gunIds.isEmpty() ? Collections.emptyMap()
                : Optional.ofNullable(chargingGunClient.getChargingGunByIds(gunIds).getData()).orElse(Collections.emptyList()).stream()
                .collect(Collectors.toMap(TChargingGun::getId, item -> item, (a, b) -> a));
        for (MyVinChargingOrderList item : list) {
            Site site = sites.get(item.getSiteId());
            item.setTitle(site == null ? "未知电站" : site.getName());
            TChargingGun gun = guns.get(item.getChargingGunId());
            item.setName(gun == null ? null : gun.getName());
        }
    }
 
    private void fillExtra(List<ChargingOrderVO> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<Long> orderIds = list.stream().map(ChargingOrderVO::getId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<Long, Integer> periodCounts = new HashMap<>();
        if (!orderIds.isEmpty()) {
            for (Map<String, Object> item : baseMapper.countAccountingStrategies(orderIds)) {
                Number chargingOrderId = (Number) item.get("chargingOrderId");
                Number periodCount = (Number) item.get("periodCount");
                if (chargingOrderId != null && periodCount != null) {
                    periodCounts.put(chargingOrderId.longValue(), periodCount.intValue());
                }
            }
        }
        List<Integer> siteIds = list.stream().map(ChargingOrderVO::getSiteId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        List<Integer> gunIds = list.stream().map(ChargingOrderVO::getChargingGunId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<Integer, Site> sites = siteIds.isEmpty() ? Collections.emptyMap()
                : Optional.ofNullable(siteClient.getSiteByIds(siteIds).getData()).orElse(Collections.emptyList()).stream()
                .collect(Collectors.toMap(Site::getId, item -> item, (a, b) -> a));
        Map<Integer, TChargingGun> guns = gunIds.isEmpty() ? Collections.emptyMap()
                : Optional.ofNullable(chargingGunClient.getChargingGunByIds(gunIds).getData()).orElse(Collections.emptyList()).stream()
                .collect(Collectors.toMap(TChargingGun::getId, item -> item, (a, b) -> a));
        for (ChargingOrderVO item : list) {
            Site site = sites.get(item.getSiteId());
            item.setSiteName(site == null ? null : site.getName());
            TChargingGun gun = guns.get(item.getChargingGunId());
            item.setTerminalName(gun == null ? null : gun.getName());
            if (item.getStartTime() != null && item.getEndTime() != null) {
                item.setChargingSecond(ChronoUnit.SECONDS.between(item.getStartTime(), item.getEndTime()));
            }
            item.setCount(periodCounts.getOrDefault(item.getId(), 0));
            item.setPlatformIncome(BigDecimal.ZERO);
            item.setPartnerIncome(BigDecimal.ZERO);
        }
    }
 
    private void fillRealtimeData(List<ChargingOrderVO> list) {
        for (ChargingOrderVO item : list) {
            if (item.getCode() == null || item.getCode().trim().isEmpty()) {
                continue;
            }
            UploadRealTimeMonitoringData data = monitoringDataService.getLastDataById(item.getCode());
            if (data == null) {
                continue;
            }
            item.setChargeCurrent(data.getOutput_current());
            item.setChargeVoltage(data.getOutput_voltage());
            BigDecimal power = data.getPower();
            if (power == null && data.getOutput_current() != null && data.getOutput_voltage() != null) {
                power = data.getOutput_current().multiply(data.getOutput_voltage())
                        .divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
            }
            item.setChargePower(power);
        }
    }
}