puzhibing
2026-03-10 487ebcc3b2db366ad7bfb6f34bd11f4ffec9e11e
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
package com.xiaopeng.maintenance.schedule;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaopeng.api.feignClient.account.XpOperationUserClient;
import com.xiaopeng.api.feignClient.vehicleConvoy.XpVehicleClient;
import com.xiaopeng.api.model.account.XpOperationsRole;
import com.xiaopeng.api.model.maintenance.XpTask;
import com.xiaopeng.api.model.maintenance.XpTaskRule;
import com.xiaopeng.api.model.maintenance.XpTaskRuleRole;
import com.xiaopeng.api.model.vehicleConvoy.XpVehicle;
import com.xiaopeng.api.vo.automaticPilot.VehiclePosition;
import com.xiaopeng.common.core.domain.R;
import com.xiaopeng.maintenance.constant.TaskScheduleConstants;
import com.xiaopeng.maintenance.mapper.XpTaskMapper;
import com.xiaopeng.maintenance.mapper.XpTaskRuleMapper;
import com.xiaopeng.maintenance.mapper.XpTaskRuleRoleMapper;
import com.xiaopeng.maintenance.utils.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
 
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 运营车辆电量检测定时任务
 * <p>
 * 根据任务规则配置的充电阈值,从MongoDB读取低电量车辆位置数据,
 * 创建充电类型任务并下发给配置角色对应的运维人员。
 * </p>
 *
 * @author mitao
 * @since 2026-03-10
 */
@Component
public class VehicleChargingScheduleTask {
 
    private static final Logger log = LoggerFactory.getLogger(VehicleChargingScheduleTask.class);
 
    /**
     * 任务名称
     */
    private static final String TASK_NAME = "运营车辆电量检测定时任务";
 
    @Autowired
    private XpTaskRuleMapper taskRuleMapper;
 
    @Autowired
    private XpTaskRuleRoleMapper taskRuleRoleMapper;
 
    @Autowired
    private XpTaskMapper taskMapper;
 
    @Autowired
    private XpVehicleClient xpVehicleClient;
 
    @Autowired
    private XpOperationUserClient xpOperationUserClient;
 
    @Autowired
    private MongoTemplate mongoTemplate;
 
    /**
     * 每分钟执行一次电量检测
     */
    @Scheduled(cron = "0 * * * * ?")
    public void executeChargingDetectionTask() {
        log.info("========== 开始执行{}检查 ==========", TASK_NAME);
 
        // 1. 获取任务规则配置
        XpTaskRule taskRule = getTaskRule();
        if (taskRule == null) {
            log.info("未找到任务规则配置,跳过执行");
            return;
        }
 
        // 2. 判断充电策略功能是否启用
        if (taskRule.getChargingStrategy() == null || taskRule.getChargingStrategy() != 1) {
            log.info("充电策略未启用,跳过执行");
            return;
        }
 
        // 3. 获取电量阈值
        BigDecimal thresholdDecimal = taskRule.getChargingStrategyBatteryl();
        if (thresholdDecimal == null) {
            log.warn("充电策略电量阈值未配置,跳过执行");
            return;
        }
        int threshold = thresholdDecimal.intValue();
        if (threshold <= 0) {
            log.warn("充电策略电量阈值不合法:{},跳过执行", thresholdDecimal);
            return;
        }
 
        // 4. 获取任务接收角色的运维人员
        List<Long> operationUserIds = getOperationUserIdsByRoleType(TaskScheduleConstants.RULE_ROLE_TYPE_CHARGING);
        if (CollectionUtils.isEmpty(operationUserIds)) {
            log.warn("未找到充电策略任务接收角色的运维人员");
            return;
        }
        String belongUserIds = operationUserIds.stream().map(String::valueOf).collect(Collectors.joining(","));
 
        // 5. 获取所有运营中的车辆,并构建 VIN -> Vehicle 映射
        List<XpVehicle> operatingVehicles = getOperatingVehicles();
        if (CollectionUtils.isEmpty(operatingVehicles)) {
            log.info("没有运营中的车辆,跳过执行");
            return;
        }
        Map<String, XpVehicle> operatingVehicleByVin = operatingVehicles.stream()
                .filter(v -> StringUtils.hasLength(v.getVehicleVin()))
                .collect(Collectors.toMap(XpVehicle::getVehicleVin, v -> v, (a, b) -> a));
        if (operatingVehicleByVin.isEmpty()) {
            log.info("运营车辆VIN为空,跳过执行");
            return;
        }
 
        // 6. 从MongoDB查询电量低于阈值的车辆位置数据(只查运营车辆VIN)
        List<String> vins = new ArrayList<>(operatingVehicleByVin.keySet());
        Query query = new Query(Criteria.where("vin").in(vins).and("currentElectricity").lt(threshold));
        List<VehiclePosition> lowBatteryPositions = mongoTemplate.find(query, VehiclePosition.class);
        if (CollectionUtils.isEmpty(lowBatteryPositions)) {
            log.info("未找到低电量车辆(阈值={}),跳过执行", threshold);
            return;
        }
 
        int createdCount = 0;
        int skippedCount = 0;
        for (VehiclePosition position : lowBatteryPositions) {
            if (position == null || !StringUtils.hasLength(position.getVin())) {
                continue;
            }
            XpVehicle vehicle = operatingVehicleByVin.get(position.getVin());
            if (vehicle == null || vehicle.getId() == null) {
                continue;
            }
 
            // 避免重复创建:若存在未完成的充电任务则跳过
            if (hasUnfinishedTask(vehicle.getId(), TaskScheduleConstants.TASK_TYPE_CHARGING)) {
                skippedCount++;
                continue;
            }
 
            XpTask task = buildChargingTask(vehicle, position, belongUserIds, taskRule, threshold);
            taskMapper.insert(task);
            createdCount++;
        }
 
        log.info("========== {}执行完成,阈值={},命中={},创建任务数={},跳过(已存在未完成任务)={} ==========",
                TASK_NAME, threshold, lowBatteryPositions.size(), createdCount, skippedCount);
    }
 
    private XpTaskRule getTaskRule() {
        return taskRuleMapper.selectOne(new LambdaQueryWrapper<XpTaskRule>().last("limit 1"));
    }
 
    /**
     * 获取所有运营中的车辆
     */
    private List<XpVehicle> getOperatingVehicles() {
        try {
            R<List<XpVehicle>> result = xpVehicleClient.listVehicle();
            if (result != null && result.getData() != null) {
                return result.getData().stream()
                        .filter(v -> v.getVehicleType() != null && v.getVehicleType() == 2)
                        .filter(v -> v.getOperatingStatus() != null && v.getOperatingStatus() == 1)
                        .collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error("获取车辆列表失败", e);
        }
        return Collections.emptyList();
    }
 
    /**
     * 根据角色类型获取运维人员ID列表
     */
    private List<Long> getOperationUserIdsByRoleType(Integer roleType) {
        List<XpTaskRuleRole> ruleRoles = taskRuleRoleMapper.selectList(
                new LambdaQueryWrapper<XpTaskRuleRole>()
                        .eq(XpTaskRuleRole::getRuleType, roleType)
        );
        if (CollectionUtils.isEmpty(ruleRoles)) {
            return Collections.emptyList();
        }
 
        Set<Long> userIds = new HashSet<>();
        for (XpTaskRuleRole ruleRole : ruleRoles) {
            try {
                R<List<XpOperationsRole>> result = xpOperationUserClient.getXpOperationsRoleByRoleId(ruleRole.getRoleId());
                if (result != null && result.getData() != null) {
                    userIds.addAll(
                            result.getData().stream()
                                    .map(XpOperationsRole::getOperationsUserId)
                                    .filter(Objects::nonNull)
                                    .collect(Collectors.toList())
                    );
                }
            } catch (Exception e) {
                log.error("获取角色[{}]对应的运维人员失败", ruleRole.getRoleId(), e);
            }
        }
        return new ArrayList<>(userIds);
    }
 
    /**
     * 检查是否已存在未完成的同类型任务
     */
    private boolean hasUnfinishedTask(Long vehicleId, String taskTypeId) {
        XpTask existingTask = taskMapper.selectOne(
                new LambdaQueryWrapper<XpTask>()
                        .eq(XpTask::getVehicleId, vehicleId)
                        .eq(XpTask::getTaskTypeId, taskTypeId)
                        .in(XpTask::getStatus,
                                TaskScheduleConstants.TASK_STATUS_PENDING_ARRIVE,
                                TaskScheduleConstants.TASK_STATUS_PENDING)
                        .last("limit 1")
        );
        return existingTask != null;
    }
 
    private XpTask buildChargingTask(XpVehicle vehicle,
                                    VehiclePosition position,
                                    String belongUserIds,
                                    XpTaskRule taskRule,
                                    int threshold) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String taskCode = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
 
        Integer currentElectricity = position.getCurrentElectricity();
        String desc = String.format("系统自动下发的车辆充电任务,当前电量%s%%,阈值%d%%",
                currentElectricity == null ? "-" : String.valueOf(currentElectricity),
                threshold);
 
        XpTask task = new XpTask();
        task.setTaskCode(taskCode);
        task.setTaskCategory(TaskScheduleConstants.TASK_CATEGORY_ROUTINE);
        task.setTaskTypeId(TaskScheduleConstants.TASK_TYPE_CHARGING);
        task.setTaskUrgencyLevel(taskRule.getChargingStrategyLevel() != null
                ? taskRule.getChargingStrategyLevel()
                : TaskScheduleConstants.URGENCY_LEVEL_P2);
        task.setTaskDescription(desc);
 
        task.setVehicleId(vehicle.getId());
        if (position.getPoint() != null) {
            task.setVehicleLon(BigDecimal.valueOf(position.getPoint().getX()));
            task.setVehicleLat(BigDecimal.valueOf(position.getPoint().getY()));
        }
 
        // 常规任务默认限时3天
        task.setEndTime(LocalDateTime.now().plusDays(3));
        task.setStatus(TaskScheduleConstants.TASK_STATUS_PENDING);
        task.setHandleUserId(belongUserIds);
        task.setReportUserId(0L);
        task.setReportTime(LocalDateTime.now());
        task.setCreateBy(TaskScheduleConstants.SCHEDULE_CREATOR);
        return task;
    }
}