liujie
2026-06-09 c96fbe6b0aeb413a17c429133ee6d81d138144b9
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
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.XpFleetOperationsClient;
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.api.vo.maintenance.TaskScheduleConstants;
import com.xiaopeng.common.core.utils.SensitiveDataCryptoUtil;
import com.xiaopeng.maintenance.mapper.XpTaskMapper;
import com.xiaopeng.maintenance.mapper.XpTaskRuleMapper;
import com.xiaopeng.maintenance.mapper.XpTaskRuleRoleMapper;
import com.xiaopeng.maintenance.service.VehicleLocationFillService;
import com.xiaopeng.maintenance.utils.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
 
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 车身清洁定时任务
 * <p>
 * 根据任务规则配置,在指定时间自动创建车身清洁任务,
 * 并下发给关联角色的运维人员
 * </p>
 *
 * @author mitao
 * @since 2026-02-27
 */
@Component
public class VehicleCleanScheduleTask {
 
    private static final Logger log = LoggerFactory.getLogger(VehicleCleanScheduleTask.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 XpFleetOperationsClient xpFleetOperationsClient;
 
    @Autowired
    private VehicleLocationFillService vehicleLocationFillService;
 
    /**
     * 每分钟检查一次是否需要执行任务下发
     * <p>
     * 检查逻辑:
     * 1. 获取任务规则配置
     * 2. 判断车身清洁功能是否启用(周期值 > 0)
     * 3. 判断当前时间是否为配置的任务下发时间
     * 4. 查询所有运营中的车辆
     * 5. 根据清洁周期判断是否需要创建任务
     * 6. 创建任务并分配给相关角色的运维人员
     * </p>
     */
    @Scheduled(cron = "0 * * * * ?")
    public void executeCleanTask() {
        log.info("========== 开始执行车身清洁定时任务检查 ==========");
 
        // 1. 获取任务规则配置
        XpTaskRule taskRule = getTaskRule();
        if (taskRule == null) {
            log.info("未找到任务规则配置,跳过执行");
            return;
        }
 
        // 2. 判断车身清洁功能是否启用(周期值 > 0 表示启用)
        if (!isEnabled(taskRule)) {
            log.info("车身清洁功能未启用(周期值未配置或为0),跳过执行");
            return;
        }
 
        // 3. 判断当前时间是否为配置的任务下发时间
        if (!isExecuteTime(taskRule.getVehicleCleanTime())) {
            log.debug("当前时间不是任务下发时间,跳过执行");
            return;
        }
 
        // 计算清洁周期(天数)
        int cycleDays = calculateCycleDays(taskRule.getVehicleCleanCycle(), taskRule.getVehicleCleanTimeType());
 
        log.info("开始执行车身清洁任务下发,清洁周期: {}天, 紧急程度: P{}",
                cycleDays,
                taskRule.getVehicleCleanLevel());
 
        try {
            // 执行任务创建
            int createdCount = createCleanTasks(taskRule, cycleDays);
 
            log.info("========== 车身清洁定时任务执行完成,创建任务数: {} ==========", createdCount);
 
        } catch (Exception e) {
            log.error("车身清洁定时任务执行失败", e);
        }
    }
 
    /**
     * 获取任务规则配置
     *
     * @return 任务规则
     */
    private XpTaskRule getTaskRule() {
        return taskRuleMapper.selectOne(new LambdaQueryWrapper<XpTaskRule>().last("limit 1"));
    }
 
    /**
     * 判断车身清洁功能是否启用
     * <p>
     * 根据周期值判断:周期值 > 0 则认为启用
     * </p>
     *
     * @param taskRule 任务规则
     * @return 是否启用
     */
    private boolean isEnabled(XpTaskRule taskRule) {
        return taskRule.getVehicleCleanCycle() != null
                && taskRule.getVehicleCleanCycle() > 0;
    }
 
    /**
     * 判断当前时间是否为任务下发时间
     * <p>
     * 精确到分钟级别的时间匹配
     * </p>
     *
     * @param executeTime 配置的执行时间
     * @return 是否应该执行
     */
    private boolean isExecuteTime(LocalTime executeTime) {
        if (executeTime == null) {
            log.warn("任务下发时间未配置");
            return false;
        }
 
        LocalTime now = LocalTime.now();
 
        // 精确到分钟匹配
        return executeTime.getHour() == now.getHour() && executeTime.getMinute() == now.getMinute();
    }
 
    /**
     * 计算清洁周期天数
     * <p>
     * 根据周期类型转换为天数:
     * - 类型1:天,直接返回周期数值
     * - 类型2:月,按30天/月计算
     * </p>
     *
     * @param cycleTime     周期数值
     * @param cycleTimeType 周期类型:1=天, 2=月
     * @return 周期天数
     */
    private int calculateCycleDays(Integer cycleTime, Integer cycleTimeType) {
        // 默认周期为1
        if (cycleTime == null || cycleTime <= 0) {
            cycleTime = 1;
        }
 
        // 默认为天
        if (cycleTimeType == null || cycleTimeType == 1) {
            return cycleTime;
        } else {
            // 月(按30天计算)
            return cycleTime * 30;
        }
    }
 
    /**
     * 创建车身清洁任务
     *
     * @param taskRule  任务规则配置
     * @param cycleDays 清洁周期(天数)
     * @return 创建的任务数量
     */
    private int createCleanTasks(XpTaskRule taskRule, int cycleDays) {
        // 1. 获取任务接收角色的运维人员
        List<Long> roleOperationUserIds = getOperationUserIdsByRoleType(TaskScheduleConstants.RULE_ROLE_TYPE_CLEAN);
        if (CollectionUtils.isEmpty(roleOperationUserIds)) {
            log.warn("未找到车身清洁任务接收角色的运维人员");
            return 0;
        }
 
        Set<Long> roleOperationUserIdSet = new HashSet<>(roleOperationUserIds);
        log.info("找到 {} 个运维人员可接收车身清洁任务", roleOperationUserIdSet.size());
 
        // 2. 获取所有运营中的车辆
        List<XpVehicle> vehicles = getOperatingVehicles();
        if (CollectionUtils.isEmpty(vehicles)) {
            log.info("没有运营中的车辆,无需创建清洁任务");
            return 0;
        }
 
        log.info("找到 {} 辆运营中的车辆", vehicles.size());
 
        // 3. 过滤出今日需要清洁的车辆
        List<XpVehicle> needCleanVehicles = filterVehiclesNeedClean(vehicles, cycleDays);
        if (CollectionUtils.isEmpty(needCleanVehicles)) {
            log.info("今日没有需要清洁的车辆");
            return 0;
        }
 
        log.info("过滤后有 {} 辆车辆需要今日清洁", needCleanVehicles.size());
 
        // 4. 创建任务并分配给运维人员
        Map<Long, Long> vehicleIdToFleetIdCache = new HashMap<>();
        Map<Long, Set<Long>> fleetIdToOperationUserIdsCache = new HashMap<>();
        return createTasksAndAssign(needCleanVehicles, roleOperationUserIdSet, taskRule,
                vehicleIdToFleetIdCache, fleetIdToOperationUserIdsCache);
    }
 
    /**
     * 根据角色类型获取运维人员ID列表
     *
     * @param roleType 角色类型
     * @return 运维人员ID列表
     */
    private List<Long> getOperationUserIdsByRoleType(Integer roleType) {
        // 1. 获取该类型对应的角色ID
        List<XpTaskRuleRole> ruleRoles = taskRuleRoleMapper.selectList(
                new LambdaQueryWrapper<XpTaskRuleRole>()
                        .eq(XpTaskRuleRole::getRuleType, roleType)
        );
 
        if (CollectionUtils.isEmpty(ruleRoles)) {
            return Collections.emptyList();
        }
 
        // 2. 获取角色对应的运维人员
        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)
                                    .collect(Collectors.toList())
                    );
                }
            } catch (Exception e) {
                log.error("获取角色[{}]对应的运维人员失败", ruleRole.getRoleId(), e);
            }
        }
 
        return new ArrayList<>(userIds);
    }
 
    /**
     * 获取所有运营中的车辆
     *
     * @return 车辆列表
     */
    private List<XpVehicle> getOperatingVehicles() {
        try {
            R<List<XpVehicle>> result = xpVehicleClient.listVehicle();
            if (result != null && result.getData() != null) {
                // 过滤运营中的车辆 (vehicleType=2 表示运营, operatingStatus=1 表示运营中)
                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();
    }
 
    /**
     * 过滤出需要清洁的车辆
     * <p>
     * 根据清洁周期判断:查询车辆上次清洁任务时间,
     * 如果距今天数 >= 配置周期,则需要清洁
     * </p>
     *
     * @param vehicles  所有车辆
     * @param cycleDays 清洁周期(天数)
     * @return 需要清洁的车辆列表
     */
    private List<XpVehicle> filterVehiclesNeedClean(List<XpVehicle> vehicles, int cycleDays) {
        LocalDate today = LocalDate.now();
        List<XpVehicle> needCleanVehicles = new ArrayList<>();
 
        for (XpVehicle vehicle : vehicles) {
            // 查询该车辆最近一次清洁任务
            XpTask lastTask = taskMapper.selectOne(
                    new LambdaQueryWrapper<XpTask>()
                            .eq(XpTask::getVehicleId, vehicle.getId())
                            .eq(XpTask::getTaskCategory, TaskScheduleConstants.TASK_CATEGORY_ROUTINE)
                            .eq(XpTask::getTaskTypeId, TaskScheduleConstants.TASK_TYPE_CLEAN)
                            .orderByDesc(XpTask::getCreateTime)
                            .last("limit 1")
            );
 
            // 如果从未清洁过,需要清洁
            if (lastTask == null || lastTask.getCreateTime() == null) {
                needCleanVehicles.add(vehicle);
                continue;
            }
 
            // 计算距离上次清洁的天数
            LocalDate lastCleanDate = lastTask.getCreateTime().toLocalDate();
            long daysSinceLastClean = java.time.temporal.ChronoUnit.DAYS.between(lastCleanDate, today);
 
            // 如果距离上次清洁天数 >= 配置周期,则需要清洁
            if (daysSinceLastClean >= cycleDays) {
                needCleanVehicles.add(vehicle);
            }
        }
 
        return needCleanVehicles;
    }
 
    /**
     * 创建任务并分配给运维人员
     *
     * @param vehicles         需要清洁的车辆列表
     * @param roleOperationUserIds 配置角色下的运维人员ID集合
     * @param taskRule         任务规则
     * @param vehicleIdToFleetIdCache 车辆->车队缓存
     * @param fleetIdToOperationUserIdsCache 车队->人员缓存
     * @return 创建的任务数量
     */
    private int createTasksAndAssign(List<XpVehicle> vehicles, Set<Long> roleOperationUserIds, XpTaskRule taskRule,
                                     Map<Long, Long> vehicleIdToFleetIdCache,
                                     Map<Long, Set<Long>> fleetIdToOperationUserIdsCache) {
        List<XpTask> tasksToSave = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        int skippedCount = 0;
 
        Map<String, VehiclePosition> positionByVin = vehicleLocationFillService.loadPositionByVin(
                vehicles.stream()
                        .map(XpVehicle::getVehicleVin)
                        .filter(StringUtils::hasLength)
                        .distinct()
                        .collect(Collectors.toList())
        );
 
        for (XpVehicle vehicle : vehicles) {
            List<Long> handleUserIds = resolveHandleUserIds(vehicle.getId(), roleOperationUserIds,
                    vehicleIdToFleetIdCache, fleetIdToOperationUserIdsCache);
            if (CollectionUtils.isEmpty(handleUserIds)) {
                skippedCount++;
                continue;
            }
 
            String belongUserIds = handleUserIds.stream().map(String::valueOf).collect(Collectors.joining(","));
 
            XpTask task = new XpTask();
 
            // 生成任务编号
            String taskCode = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
            task.setTaskCode(taskCode);
 
            // 设置任务基本信息
            task.setTaskCategory(TaskScheduleConstants.TASK_CATEGORY_ROUTINE);
            task.setTaskTypeId(TaskScheduleConstants.TASK_TYPE_CLEAN);
            task.setTaskUrgencyLevel(taskRule.getVehicleCleanLevel() != null
                    ? taskRule.getVehicleCleanLevel()
                    : TaskScheduleConstants.URGENCY_LEVEL_P2);
            task.setTaskDescription("系统自动下发的车身清洁任务");
 
            // 设置车辆信息
            task.setVehicleId(vehicle.getId());
            String vin = SensitiveDataCryptoUtil.decryptIfPossible(vehicle.getVehicleVin());
            vehicleLocationFillService.fillFromVin(task, vin, positionByVin);
 
            // 设置任务时限 常规任务限时3天
            task.setEndTime(LocalDateTime.now().plusDays(3));
 
            // 设置任务状态为待到达
            task.setStatus(TaskScheduleConstants.TASK_STATUS_PENDING);
 
            // 设置任务接收人(车辆所属车队关联人员与配置角色人员取交集)
            task.setHandleUserId(belongUserIds);
            task.setReportTime(LocalDateTime.now());
            task.setReportUserId(0L);
            // 设置创建信息
            task.setReportTime(LocalDateTime.now());
            task.setCreateBy(TaskScheduleConstants.SCHEDULE_CREATOR);
 
            tasksToSave.add(task);
        }
 
        // 批量保存任务
        if (!CollectionUtils.isEmpty(tasksToSave)) {
            for (XpTask task : tasksToSave) {
                taskMapper.insert(task);
            }
            log.info("成功创建 {} 个车身清洁任务", tasksToSave.size());
        }
        if (skippedCount > 0) {
            log.warn("车身清洁任务:跳过 {} 辆车(无可分配处理人)", skippedCount);
        }
 
        return tasksToSave.size();
    }
 
    private List<Long> resolveHandleUserIds(Long vehicleId, Set<Long> roleOperationUserIds,
                                           Map<Long, Long> vehicleIdToFleetIdCache,
                                           Map<Long, Set<Long>> fleetIdToOperationUserIdsCache) {
        if (vehicleId == null) {
            log.warn("车身清洁定时任务分配处理人失败:vehicleId为空");
            return Collections.emptyList();
        }
 
        Long fleetId = vehicleIdToFleetIdCache.get(vehicleId);
        if (!vehicleIdToFleetIdCache.containsKey(vehicleId)) {
            try {
                R<Long> fleetIdResult = xpVehicleClient.findFleetIdByVehicleId(vehicleId);
                fleetId = fleetIdResult != null ? fleetIdResult.getData() : null;
            } catch (Exception e) {
                log.error("车身清洁定时任务:根据车辆查询车队失败,vehicleId={}", vehicleId, e);
                fleetId = null;
            }
            vehicleIdToFleetIdCache.put(vehicleId, fleetId);
        }
 
        if (fleetId == null) {
            log.warn("车身清洁定时任务跳过:车辆未关联车队,vehicleId={}", vehicleId);
            return Collections.emptyList();
        }
 
        Set<Long> fleetOperationUserIds = fleetIdToOperationUserIdsCache.get(fleetId);
        if (!fleetIdToOperationUserIdsCache.containsKey(fleetId)) {
            try {
                R<List<Long>> opsResult = xpFleetOperationsClient.getOperationsIdsByFleetId(fleetId);
                List<Long> opsIds = opsResult != null ? opsResult.getData() : null;
                fleetOperationUserIds = CollectionUtils.isEmpty(opsIds) ? Collections.emptySet() : new HashSet<>(opsIds);
            } catch (Exception e) {
                log.error("车身清洁定时任务:根据车队查询关联人员失败,fleetId={}, vehicleId={}", fleetId, vehicleId, e);
                fleetOperationUserIds = Collections.emptySet();
            }
            fleetIdToOperationUserIdsCache.put(fleetId, fleetOperationUserIds);
        }
 
        if (CollectionUtils.isEmpty(fleetOperationUserIds)) {
            log.warn("车身清洁定时任务跳过:车队未关联人员,fleetId={}, vehicleId={}", fleetId, vehicleId);
            return Collections.emptyList();
        }
 
        List<Long> finalUserIds = fleetOperationUserIds.stream()
                .filter(roleOperationUserIds::contains)
                .sorted()
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(finalUserIds)) {
            log.warn("车身清洁定时任务跳过:车队人员与角色人员无交集,fleetId={}, vehicleId={}", fleetId, vehicleId);
            return Collections.emptyList();
        }
 
        return finalUserIds;
    }
}