无关风月
18 小时以前 083c414ff683ab12e65069c6c0ba6871ed1ed09f
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
package com.ruoyi.web.controller.api;
 
 
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.basic.PageInfo;
import com.ruoyi.common.core.domain.BaseModel;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.applet.dto.*;
import com.ruoyi.system.applet.query.*;
import com.ruoyi.system.applet.vo.*;
import com.ruoyi.system.model.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.system.*;
import com.ruoyi.web.controller.tool.AmapApiClient;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
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 xiaochen
 * @since 2025-05-28
 */
@Api(tags = "首页")
@RestController
@RequestMapping("/t-index")
public class TIndexController {
    @Resource
    private TTaskCleanService taskCleanerService;
 
    @Resource
    private TTaskDetailService taskDetailService;
 
 
    @Resource
    private TLocationTypeService locationTypeService;
    @Resource
    private TLocationService locationService;
    @Resource
    private TProjectDeptService projectDeptService;
 
    @Resource
    private TTaskDetailService tTaskDetailService;
    @Resource
    private TDeptService deptService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysRoleService roleService;
    @Resource
    private TDictDataService dictDataService;
    @Resource
    private TLeaveService leaveService;
    @Resource
    private TLeaveAuditService leaveAuditService;
    @Resource
    private TokenService tokenService;
    @Resource
    private TAppealService appealService;
    @Resource
    private TInspectorService inspectorService;
    @Resource
    private TFeedbackService feedbackService;
    @Resource
    private TProblemEscalationService problemEscalationService;
    @Autowired
    private AmapApiClient amapApiClient;
    @Resource
    private TSystemBulletinService systemBulletinService;
 
 
    @ApiOperation(value = "首页-系统公告")
    @PostMapping(value = "/systemBulletin")
    public R<TSystemBulletin> systemBulletin() {
        TSystemBulletin systemBulletin = systemBulletinService.lambdaQuery().eq(TSystemBulletin::getStatus, 1).last("limit 1").one();
        return R.ok(systemBulletin);
    }
 
    @ApiOperation(value = "首页-数据概览-更多")
    @PostMapping(value = "/dataReport")
    public R<DataReportVO> dataReport(@RequestBody DataReportDTO dto) {
        DataReportQuery dataReportQuery = new DataReportQuery();
        dataReportQuery.setStartTime(dto.getStartTime()+" 00:00:00");
        dataReportQuery.setEndTime(dto.getEndTime()+" 23:59:59");
        dataReportQuery.setPageNum(dto.getPageNum());
        dataReportQuery.setPageSize(dto.getPageSize());
        DataReportVO res = new DataReportVO();
        List<TDictData> dataList = dictDataService.list();
        List<TProjectDept> projectDepts = projectDeptService.list();
        List<TTaskDetail> taskDetails = taskDetailService.lambdaQuery()
                .isNotNull(TTaskDetail::getClearStatus)
                .eq(TTaskDetail::getHandleType,1)
                .eq(TTaskDetail::getAuditStatus,1)
                .orderByDesc(BaseModel::getCreateTime)
                .list();
        taskDetails = new ArrayList<>(taskDetails.stream()
                .collect(Collectors.groupingBy(
                        TTaskDetail::getTaskId,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                listAll -> listAll.get(0)
                        )
                ))
                .values());
        List<String> userDeptIds = new ArrayList<>();
        LambdaQueryWrapper<TTask> tTaskLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(dto.getProjectId())) {
            TProjectDept projectDept = projectDeptService.getById(dto.getProjectId());
            if (!projectDept.getParentId().equals("0")) {
                tTaskLambdaQueryWrapper.eq(TTask::getProjectId, projectDept.getId());
                userDeptIds.add(projectDept.getId());
            } else {
                List<TProjectDept> list = projectDeptService.lambdaQuery().eq(TProjectDept::getParentId, projectDept.getId()).list();
                List<String> deptIds = list.stream().map(TProjectDept::getId).collect(Collectors.toList());
                if (!deptIds.isEmpty()) {
                    userDeptIds.addAll(deptIds);
                    tTaskLambdaQueryWrapper.in(TTask::getProjectId, deptIds);
                } else {
                    tTaskLambdaQueryWrapper.eq(TTask::getProjectId, "-1");
                    userDeptIds.add("-1");
 
                }
            }
        } else {
            // 根据当前登录人查询部门
            Long userId = tokenService.getLoginUserApplet().getUserId();
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (sysUser.getDeptType() == 1) {
                TProjectDept projectDept = projectDeptService.getById(sysUser.getDeptId());
                if (projectDept != null) {
                    if (!"0".equals(projectDept.getParentId())) {
                        tTaskLambdaQueryWrapper.eq(TTask::getProjectId, projectDept.getId());
                        userDeptIds.add(projectDept.getId());
                    } else {
                        userDeptIds.add(projectDept.getId());
                        List<TProjectDept> list = projectDeptService.lambdaQuery().eq(TProjectDept::getParentId, projectDept.getId()).list();
                        List<String> deptIds = list.stream().map(TProjectDept::getId).collect(Collectors.toList());
                        if (!deptIds.isEmpty()) {
                            tTaskLambdaQueryWrapper.in(TTask::getProjectId, deptIds);
                            userDeptIds.addAll(deptIds);
                        } else {
                            tTaskLambdaQueryWrapper.eq(TTask::getProjectId, "-1");
                            userDeptIds.add("-1");
                        }
                    }
                }
            }
        }
        dataReportQuery.setProjectIds(userDeptIds);
 
        if (StringUtils.hasLength(dto.getStartTime())) {
            tTaskLambdaQueryWrapper.ge(TTask::getImplementTime, dto.getStartTime()+" 00:00:00");
            tTaskLambdaQueryWrapper.le(TTask::getImplementTime, dto.getEndTime()+" 23:59:59");
        } else {
            // 获取今天凌晨00:00:00 和今天23:59:59 类型为LocalDateTime
            LocalDateTime startOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
            LocalDateTime endOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
            tTaskLambdaQueryWrapper.ge(TTask::getImplementTime, startOfToday);
            tTaskLambdaQueryWrapper.le(TTask::getImplementTime, endOfToday);
        }
//        tTaskLambdaQueryWrapper.ne(TTask::getStatus, 1);
        List<TTask> tasks = taskCleanerService.list(tTaskLambdaQueryWrapper);
        HashMap<String, Integer> taskMap = new HashMap<>();
        HashMap<String, Integer> statusMap = new HashMap<>();
        statusMap.put("未执行", 0);
        statusMap.put("超时", 0);
        statusMap.put("待确认", 0);
        statusMap.put("已驳回", 0);
        statusMap.put("已完成", 0);
        HashMap<String, Integer> clearMap = new HashMap<>();
        clearMap.put("合格", 0);
        clearMap.put("不合格", 0);
        HashMap<String, Integer> unqualifiedMap = new HashMap<>();
        List<TDictData> dictData = dataList.stream().filter(e -> e.getDataType() == 2).collect(Collectors.toList());
        for (TDictData dictDatum : dictData) {
            unqualifiedMap.put(dictDatum.getDataContent(), 0);
        }
        for (TTask task : tasks) {
            TProjectDept tProjectDept = projectDepts.stream().filter(e -> e.getId().equals(task.getProjectId())).findFirst().orElse(null);
            if (tProjectDept == null) continue;
            taskMap.put(tProjectDept.getProjectName(), taskMap.getOrDefault(tProjectDept.getProjectName(), 0) + 1);
            StringBuilder temp = new StringBuilder();
            switch (task.getStatus()) {
                case 1:
                    temp.append("未执行");
                    break;
                case 2:
                    temp.append("超时");
                    break;
                case 3:
                    temp.append("待确认");
                    break;
                case 4:
                    temp.append("已驳回");
                    break;
                case 5:
                    temp.append("已完成");
                    break;
                case 6:
                    temp.append("已完成");
                    break;
            }
            statusMap.put(temp.toString(), statusMap.getOrDefault(temp.toString(), 0) + 1);
            TTaskDetail tTaskDetail = taskDetails.stream().filter(e -> e.getTaskId().equals(task.getId())).findFirst().orElse(null);
            StringBuilder temp1 = new StringBuilder();
            if (tTaskDetail!=null){
                switch (tTaskDetail.getClearStatus()) {
                    case 1:
                        temp1.append("合格");
                        break;
                    case 2:
                        temp1.append("不合格");
                        TDictData tDictData = dataList.stream().filter(e -> e.getId().equals(tTaskDetail.getUnqualified())).findFirst().orElse(null);
                        if (tDictData != null){
                            unqualifiedMap.put(tDictData.getDataContent(), unqualifiedMap.getOrDefault(tDictData.getDataContent(), 0) + 1);
                        }
                        break;
                }
                clearMap.put(temp1.toString(), clearMap.getOrDefault(temp1.toString(), 0) + 1);
            }
        }
 
        PageInfo<TaskFinishListVO> taskFinishListVOPageInfo = sysUserService.pageListReport(dataReportQuery);
        for (TaskFinishListVO record : taskFinishListVOPageInfo.getRecords()) {
            int pass=0;
            int unPass=0;
            List<TTask> userTaskList = tasks.stream().filter(e -> e.getPatrolInspector().equals(record.getUserId() + "")).collect(Collectors.toList());
            List<TTask> userTaskListPass = tasks.stream().filter(e ->
                    (e.getStatus()==5||e.getStatus()==6)
                    &&
                    e.getPatrolInspector().equals(record.getUserId() + "")).collect(Collectors.toList());
            for (TTask tTask : userTaskList) {
                TTaskDetail tTaskDetail = taskDetails.stream().filter(e -> e.getTaskId().equals(tTask.getId())).findFirst().orElse(null);
                if (tTaskDetail!=null){
                    switch (tTaskDetail.getClearStatus()){
                        case 1:
                            pass++;
                            break;
                            case 2:
                            unPass++;
                            break;
                    }
                }
 
            }
            record.setTotal(userTaskList.size());
            record.setRate(pass+unPass!=0?new BigDecimal(pass).divide(new BigDecimal(pass+unPass),2,RoundingMode.HALF_DOWN).multiply(new BigDecimal(100)):BigDecimal.ZERO);
            record.setFinish(!userTaskList.isEmpty()?new BigDecimal(userTaskListPass.size()).divide(new BigDecimal(userTaskList.size()),2,RoundingMode.HALF_DOWN).multiply(new BigDecimal(100)):BigDecimal.ZERO);
 
        }
//        PageInfo<TaskFinishListVO> taskFinishListVOPageInfo = new PageInfo<>();
//        Page<TTask> page = new Page<>(dto.getPageNum(), dto.getPageSize());
//        Page<TTask> tasksPage = taskCleanerService.page(page, tTaskLambdaQueryWrapper);
        res.setTaskMap(taskMap);
        res.setStatusMap(statusMap);
        res.setClearMap(clearMap);
        res.setUnqualifiedMap(unqualifiedMap);
        res.setTaskFinishList(taskFinishListVOPageInfo);
        return R.ok(res);
    }
 
    @ApiOperation(value = "根据当前登陆人查询项目部/片区不分页列表")
    @PostMapping(value = "/list")
    public R<List<ProjectDeptListNoLimitVO>> list() {
        List<TProjectDept> list = projectDeptService.list(new LambdaQueryWrapper<TProjectDept>()
                .eq(TProjectDept::getParentId, "0")
                .eq(TProjectDept::getStatus, 1));
        List<ProjectDeptListNoLimitVO> projectDeptListNoLimitVOS = new ArrayList<>();
        for (TProjectDept tProjectDept : list) {
            ProjectDeptListNoLimitVO projectDeptListNoLimitVO = new ProjectDeptListNoLimitVO();
            BeanUtils.copyProperties(tProjectDept, projectDeptListNoLimitVO);
            List<TProjectDept> list1 = projectDeptService.list(new LambdaQueryWrapper<TProjectDept>()
                    .eq(TProjectDept::getParentId, tProjectDept.getId())
                    .eq(TProjectDept::getStatus, 1));
            List<ProjectDeptListNoLimitVO> projectDeptListNoLimitVOS1 = new ArrayList<>();
            for (TProjectDept projectDept : list1) {
                ProjectDeptListNoLimitVO projectDeptListNoLimitVO1 = new ProjectDeptListNoLimitVO();
                BeanUtils.copyProperties(projectDept, projectDeptListNoLimitVO1);
                projectDeptListNoLimitVOS1.add(projectDeptListNoLimitVO1);
            }
            projectDeptListNoLimitVO.setChildrenList(projectDeptListNoLimitVOS1);
            projectDeptListNoLimitVOS.add(projectDeptListNoLimitVO);
        }
        return R.ok(projectDeptListNoLimitVOS);
    }
@Resource
private TNoticeService noticeService;
    @ApiOperation(value = "首页")
    @PostMapping(value = "/index")
    public R<IndexVO> index(@RequestBody IndexDTO dto) throws IOException {
        IndexVO res = new IndexVO();
        res.setIsNotice(0);
        Long userId = tokenService.getLoginUserApplet().getUserId();
        Long count = noticeService.lambdaQuery().eq(TNotice::getUserId, userId).eq(TNotice::getStatus, 1).count();
        if (count>0){
            res.setIsNotice(1);
        }
        List<TProjectDept> projectListAll = projectDeptService.list();
 
        List<TLocation> locationList = locationService.list();
        List<TLocationType> locationTypeList = locationTypeService.list();
        dto.setUserId(userId);
        List<TTask> taskAll = taskCleanerService.indexTask(dto);
//        List<TTask> taskAll = taskCleanerService.lambdaQuery().eq(TTask::getPatrolInspector, userId).list();
        // 获取今天凌晨00:00:00 和今天23:59:59 类型为LocalDateTime
        LocalDateTime startOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        List<TTask> taskToday = taskCleanerService.lambdaQuery()
                .between(TTask::getImplementTime, startOfToday, endOfToday)
                .eq(TTask::getPatrolInspector, userId).list();
        List<SysUser> sysUsers = sysUserService.selectAllList();
        SysUser sysUser = sysUserService.selectUserById(userId);
 
        Long userRole = sysUserService.getUserRole(userId);
        SysRole sysRole = roleService.selectRoleById(userRole);
        List<SysUser> users = new ArrayList<>();
        if (!sysRole.getRoleName().equals("现场管理员")) {
            if (sysUser.getDeptType() == 1) {
 
                TProjectDept projectDept = projectDeptService.getById(sysUser.getDeptId());
                if (projectDept != null) {
                    if ("0".equals(projectDept.getParentId())) {
                        List<String> collect = projectListAll.stream().filter(e -> e.getParentId().equals(projectDept.getId())).map(TProjectDept::getId).collect(Collectors.toList());
                        collect.add(projectDept.getId());
                        // 查询片区下的所有人员
                        users = sysUsers.stream().filter(e ->collect.contains(e.getDeptId())
                                && e.getStatus().equals("0")
                                && e.getDeptType() == 1).collect(Collectors.toList());
                    } else {
                        TProjectDept parent = projectDeptService.getById(projectDept.getParentId());
                        users = sysUsers.stream().filter(e -> e.getDeptId()
                                .equals(parent.getId())
                                && e.getStatus().equals("0")
                                && e.getDeptType() == 1).collect(Collectors.toList());
                        List<TProjectDept> list = projectDeptService.lambdaQuery().eq(TProjectDept::getParentId, parent.getId()).list();
                        List<String> deptIds = list.stream().map(TProjectDept::getId).collect(Collectors.toList());
                        if (!deptIds.isEmpty()) {
                            List<SysUser> collect = sysUsers.stream().filter(e -> deptIds
                                    .contains(e.getDeptId())
                                    && e.getStatus().equals("0")
 
                                    && e.getDeptType() == 1).collect(Collectors.toList());
                            users.addAll(collect);
                        }
                    }
                }
            } else {
                TDept dept = deptService.getById(sysUser.getDeptId());
                if (dept != null) {
                    if (!dept.getDeptName().contains("公司")) {
                        users = sysUsers.stream().filter(e -> e.getDeptType() == 1).collect(Collectors.toList());
                    }
                }
 
            }
        }
        List<TaskPendingVO> pendingTask = new ArrayList<>();
 
        res.setTotalUserCount(users.size());
        if (!users.isEmpty()) {
            List<Long> userIds = users.stream().map(SysUser::getUserId).collect(Collectors.toList());
            List<TTask> tasks = taskCleanerService.lambdaQuery().in(TTask::getPatrolInspector, userIds).list();
            List<String> taskIds = tasks.stream().map(TTask::getId).collect(Collectors.toList());
            if (!tasks.isEmpty()) {
                List<TTask> status1 = tasks.stream().filter(e -> e.getStatus() == 5 || e.getStatus() == 6).collect(Collectors.toList());
                List<TTask> status2 = tasks.stream().filter(e -> e.getStatus() != 5 && e.getStatus() != 6).collect(Collectors.toList());
                res.setMiddle(!status1.isEmpty() ? new BigDecimal(status1.size())
                        .divide(new BigDecimal(status1.size() + status2.size()), 2, RoundingMode.HALF_DOWN)
                        .multiply(new BigDecimal(100))
                        : new BigDecimal(0));
                List<TTaskDetail> taskDetails = taskDetailService.lambdaQuery()
                        .eq(TTaskDetail::getAuditStatus, 1)
                        .in(TTaskDetail::getTaskId, taskIds)
                        .isNotNull(TTaskDetail::getClearStatus)
                        .eq(TTaskDetail::getHandleType,1)
                        .orderByDesc(TTaskDetail::getCreateTime).list();
 
                taskDetails = new ArrayList<>(taskDetails.stream()
                        .collect(Collectors.groupingBy(
                                TTaskDetail::getTaskId,
                                Collectors.collectingAndThen(
                                        Collectors.toList(),
                                        listAll -> listAll.get(0)
                                )
                        ))
                        .values());
                List<TTaskDetail> status3 = taskDetails.stream().filter(e -> e.getClearStatus() == 1).collect(Collectors.toList());
                List<TTaskDetail> status4 = taskDetails.stream().filter(e -> e.getClearStatus() == 2).collect(Collectors.toList());
                if (!status3.isEmpty()) {
                    BigDecimal divide = new BigDecimal(status3.size() )
                            .divide(new BigDecimal(status3.size()+ status4.size()), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                    res.setRate(divide);
                } else {
                    res.setRate(new BigDecimal(0));
                }
 
            } else {
                res.setMiddle(new BigDecimal(0));
                res.setRate(new BigDecimal(0));
            }
 
 
        } else {
            res.setRate(new BigDecimal(0));
            res.setMiddle(new BigDecimal(0));
            res.setPendingTask(new ArrayList<>());
        }
        List<LeaveUserListVO> leaveList = new ArrayList<>();
        List<TLeave> list = leaveService.lambdaQuery().eq(TLeave::getAuditId, userId).eq(TLeave::getAuditStatus, 1).list();
        for (TLeave tLeave : list) {
            LeaveUserListVO leaveUserListVO = new LeaveUserListVO();
            BeanUtils.copyProperties(tLeave, leaveUserListVO);
            SysUser user = sysUsers.stream()
                    .filter(e -> e.getUserId().equals(Long.valueOf(tLeave.getLeavePerson()))).findFirst()
                    .orElse(null);
            if (user == null)
                continue;
            leaveUserListVO.setLeavePersonName(user.getNickName());
            leaveUserListVO.setCreateTime1(tLeave.getCreateTime());
            leaveUserListVO.setStartTime1(tLeave.getStartTime());
            leaveUserListVO.setEndTime1(tLeave.getEndTime());
            leaveList.add(leaveUserListVO);
        }
        List<TTask> taskList = taskAll.stream().filter(e -> e.getPatrolInspector().equals(userId + "") && e.getStatus() == 4).collect(Collectors.toList());
        List<String> taskIds = taskList.stream().map(TTask::getId).collect(Collectors.toList());
        // 驳回原因
        List<TTaskDetail> tTaskDetails = taskDetailService.list(new LambdaQueryWrapper<TTaskDetail>()
                .eq(TTaskDetail::getHandleType,3).groupBy(TTaskDetail::getTaskId).orderByDesc(TTaskDetail::getCreateTime));
        for (TTask tTask : taskList) {
            List<TTaskDetail> taskDetailsStatus1 = taskDetailService.lambdaQuery()
                    .eq(TTaskDetail::getAuditStatus, 1).in(TTaskDetail::getTaskId, taskIds)
                    .eq(TTaskDetail::getClearStatus, 2)
                    .groupBy(TTaskDetail::getTaskId)
                    .orderByDesc(TTaskDetail::getCreateTime).list();
            TaskPendingVO taskTodayVO = new TaskPendingVO();
            BeanUtils.copyProperties(tTask, taskTodayVO);
            TLocation tLocation = locationList.stream().filter(e -> e.getId().equals(tTask.getLocationId())).findFirst().orElse(null);
            if (tLocation != null) {
                taskTodayVO.setLocationAddress(tLocation.getLocationAddress());
                taskTodayVO.setLocationLon(tLocation.getLocationLon());
                taskTodayVO.setLocationLat(tLocation.getLocationLat());
                taskTodayVO.setLocationName(tLocation.getLocationName());
                if(StringUtils.hasLength(dto.getLon())){
                    taskTodayVO.setDistance(tTask.getDistance().divide(new BigDecimal(1000),2, RoundingMode.HALF_DOWN));
//                    Map<String, String> distance = amapApiClient.getDistance(dto.getLon() + "," + dto.getLat(), tLocation.getLocationLon() + "," + tLocation.getLocationLat(), 1);
//                    if (distance != null) {
//                        taskTodayVO.setDistance(new BigDecimal(distance.get("distance")).divide(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_EVEN));
//                    } else {
//                        taskTodayVO.setDistance(new BigDecimal("0"));
//                    }
                }else {
                    taskTodayVO.setDistance(new BigDecimal("0"));
                }
                TLocationType tLocationType = locationTypeList.stream().filter(e -> e.getId().equals(tLocation.getLocationType())).findFirst().orElse(null);
                if (tLocationType != null) {
                    taskTodayVO.setLocationTypeName(tLocationType.getLocationName());
                    taskTodayVO.setLocationTypeIcon(tLocationType.getLocationIcon());
                }
            }
            TTaskDetail tTaskDetail = tTaskDetails.stream().filter(e -> e.getTaskId().equals(tTask.getId())).findFirst().orElse(null);
            if (tTaskDetail!=null){
                taskTodayVO.setRemark(tTaskDetail.getAuditRemark());
            }
            // 任务记录ids
            List<String> collect = taskAll.stream().map(TTask::getId).collect(Collectors.toList());
            if (!collect.isEmpty()){
                List<TInspector> list1 = inspectorService.lambdaQuery()
 
                        .in(TInspector::getTaskId, collect).eq(TInspector::getStatus, 2).list();
                for (TInspector tInspector : list1) {
                    TaskPendingVO taskTodayVOOne = new TaskPendingVO();
                    BeanUtils.copyProperties(tTask, taskTodayVOOne);
                    taskTodayVOOne.setId(tInspector.getId());
                    TLocation tLocationOne = locationList.stream().filter(e -> e.getId().equals(tTask.getLocationId())).findFirst().orElse(null);
                    if (tLocationOne != null) {
                        taskTodayVOOne.setLocationAddress(tLocationOne.getLocationAddress());
                        taskTodayVOOne.setLocationLon(tLocationOne.getLocationLon());
                        taskTodayVOOne.setLocationLat(tLocationOne.getLocationLat());
                        taskTodayVOOne.setLocationName(tLocationOne.getLocationName());
                        if(StringUtils.hasLength(dto.getLon())){
                            Map<String, String> distance = amapApiClient.getDistance(dto.getLon() + "," + dto.getLat(), tLocationOne.getLocationLon() + "," + tLocationOne.getLocationLat(), 1);
                            if (distance != null) {
                                taskTodayVOOne.setDistance(new BigDecimal(distance.get("distance")).divide(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_EVEN));
                            } else {
                                taskTodayVOOne.setDistance(new BigDecimal("0"));
                            }
                        }else {
                            taskTodayVOOne.setDistance(new BigDecimal("0"));
                        }
                        TLocationType tLocationType = locationTypeList.stream().filter(e -> e.getId().equals(tLocationOne.getLocationType())).findFirst().orElse(null);
                        if (tLocationType != null) {
                            taskTodayVOOne.setLocationTypeName(tLocationType.getLocationName());
                            taskTodayVOOne.setLocationTypeIcon(tLocationType.getLocationIcon());
                        }
                    }
                    taskTodayVOOne.setStatus(4);
                    taskTodayVOOne.setRemark(tInspector.getAuditRemark());
                    pendingTask.add(taskTodayVOOne);
                }
            }
            pendingTask.add(taskTodayVO);
        }
        // 将pendingTask按照距离 从小到大排序
        pendingTask.sort(Comparator.comparing(TaskPendingVO::getDistance));
        res.setPendingTask(pendingTask);
        res.setLeaveList(leaveList);
        List<TaskTodayVO> todayTask = new ArrayList<>();
        List<String> collect = taskAll.stream().map(TTask::getId).collect(Collectors.toList());
        for (TTask tTask : taskToday) {
            TaskTodayVO taskTodayVO = new TaskTodayVO();
            if(CollectionUtils.isEmpty(collect)){
                break;
            }
            List<TTaskDetail> taskDetailsStatus1 = taskDetailService.lambdaQuery()
                    .eq(TTaskDetail::getAuditStatus, 1).in(TTaskDetail::getTaskId, collect)
                    .eq(TTaskDetail::getClearStatus, 2)
                    .groupBy(TTaskDetail::getTaskId)
                    .orderByDesc(TTaskDetail::getCreateTime).list();
            BeanUtils.copyProperties(tTask, taskTodayVO);
            TLocation tLocation = locationList.stream().filter(e -> e.getId().equals(tTask.getLocationId())).findFirst().orElse(null);
            if (tLocation != null) {
                taskTodayVO.setLocationAddress(tLocation.getLocationAddress());
                taskTodayVO.setLocationLon(tLocation.getLocationLon());
                taskTodayVO.setLocationLat(tLocation.getLocationLat());
                taskTodayVO.setLocationName(tLocation.getLocationName());
                if(StringUtils.hasLength(dto.getLon())){
                    Map<String, String> distance = amapApiClient.getDistance(dto.getLon() + "," + dto.getLat(), tLocation.getLocationLon() + "," + tLocation.getLocationLat(), 1);
                    if (distance != null) {
                        taskTodayVO.setDistance(new BigDecimal(distance.get("distance")).divide(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_EVEN));
                    } else {
                        taskTodayVO.setDistance(new BigDecimal("0"));
                    }
                }else {
                    taskTodayVO.setDistance(new BigDecimal("0"));
                }
                TLocationType tLocationType = locationTypeList.stream().filter(e -> e.getId().equals(tLocation.getLocationType())).findFirst().orElse(null);
                if (tLocationType != null) {
                    taskTodayVO.setLocationTypeName(tLocationType.getLocationName());
                    taskTodayVO.setLocationTypeIcon(tLocationType.getLocationIcon());
                }
            }
            TTaskDetail tTaskDetail = tTaskDetails.stream().filter(e -> e.getTaskId().equals(tTask.getId())).findFirst().orElse(null);
            if (tTaskDetail!=null){
                taskTodayVO.setRemark(tTaskDetail.getAuditRemark());
            }
            todayTask.add(taskTodayVO);
 
        }
        // 将todayTask进行排序 优先根据status状态排序,优先展示未执行、超时、待整改、待确认、整改完成、已完成,然后状态一样再根据距离排序
        sortTodayTasks(todayTask);
        res.setTodayTask(todayTask);
        List<TaskTomorrowVO> tomorrowTask = new ArrayList<>();
 
        for (TaskTodayVO taskTodayVO : todayTask) {
            TaskTomorrowVO taskTomorrowVO = new TaskTomorrowVO();
            BeanUtils.copyProperties(taskTodayVO, taskTomorrowVO);
            tomorrowTask.add(taskTomorrowVO);
        }
        Collections.shuffle(tomorrowTask);
        res.setTomorrowTask(tomorrowTask);
        res.setIsLeave(0);
        // 查询请假状态
        List<TLeave> list2 = leaveService.lambdaQuery().eq(TLeave::getLeavePerson, userId)
                .eq(TLeave::getAuditStatus, 2)
                .list();
        for (TLeave tLeave : list2) {
            LocalDate now = LocalDate.now();
            LocalDate startDate = tLeave.getStartTime().toLocalDate();
            LocalDate endDate = tLeave.getStartTime().toLocalDate();
            if (now.isAfter(startDate) && now.isBefore(endDate)) {
                res.setIsLeave(1);
            } else if (now.isEqual(startDate) || now.isEqual(endDate)) {
                res.setIsLeave(1);
            }
        }
        return R.ok(res);
    }
    public static void sortTodayTasks(List<TaskTodayVO> taskList) {
        Map<Integer, Integer> statusOrder = new HashMap<>();
        statusOrder.put(1, 0);
        statusOrder.put(2, 1);
        statusOrder.put(4, 2);
        statusOrder.put(3, 3);
        statusOrder.put(5, 4);
        statusOrder.put(6, 5);
 
        taskList.sort(Comparator.comparingInt((TaskTodayVO o) -> statusOrder.getOrDefault(o.getStatus(), Integer.MAX_VALUE)).thenComparing(TaskTodayVO::getDistance));
    }
 
}