TaskServiceImpl.java 31.6 KB
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 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
package vion.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.collection.set.SetUtil;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vion.constant.RedisKeyEnum;
import vion.dto.TaskDTO;
import vion.mapper.TaskMapper;
import vion.model.*;
import vion.service.*;
import vion.third.DingMod;
import vion.third.WechatMod;
import vion.vo.RoleVO;
import vion.vo.TaskTempVO;
import vion.vo.TaskVO;
import vion.vo.UserVO;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implements ITaskService {

    private final ITaskTempService taskTempService;
    private final IFileService fileService;
    private final IFaultLogService faultLogService;
    private final IStoreService storeService;
    private final IUserService userService;
    private final DingMod dingMod;
    private final WechatMod wechatMod;
    private final Converter converter;
    private final RedissonClient redissonClient;
    @Value("${fileUrl:}")
    private String fileUrl;

    @Override
    public Page<TaskVO> getTaskList(TaskDTO data) {
        UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser");
        var taskIdSet = getTaskIdSet(userVO);

        var wrapper = new MPJLambdaWrapper<>(converter.convert(data, Task.class))
                .selectAll(Task.class)
                .selectAs(Store::getName, TaskVO::getStoreName)
                .selectAs(Account::getName, TaskVO::getAccountName)
                .selectAssociation(ServiceOrder.class, TaskVO::getServiceOrder)
                .leftJoin(Store.class, Store::getId, Task::getStoreId)
                .leftJoin(Account.class, Account::getId, Task::getAccountId)
                .leftJoin(ServiceOrder.class, ServiceOrder::getTaskId, Task::getId)
                .between(ArrayUtil.isAllNotNull(data.getStartdate(), data.getEnddate()), Task::getRepairTime, data.getStartdate(), data.getEnddate())
                .isNotNull(ObjUtil.equals(data.getSource(), 1), Task::getTaskTempId)
                .isNull(ObjUtil.equals(data.getSource(), 2), Task::getTaskTempId)
                .lt(data.getCurDate() != null, Task::getExpDate, data.getCurDate());

        if (taskIdSet.size() == 1) {
            var taskId = CollUtil.get(taskIdSet, 0);
            // 不是管理员,并且第一次处理工单,但当前处理人是他 || 管理员逻辑
            if (taskId.equals(-99L) || taskId.equals(0L)) {
                return this.selectJoinListPage(Page.of(data.getPageNum(), data.getPageSize()), TaskVO.class, wrapper);
            }
        }

        wrapper.in(Task::getId, taskIdSet);
        return this.selectJoinListPage(Page.of(data.getPageNum(), data.getPageSize()), TaskVO.class, wrapper);
    }

    /**
     * 根据当前登录用户,判断其权限和其参与过的工单,获取工单id集合
     *
     * @param userVO 当前登录用户
     * @return java.util.Set<java.lang.Long>
     */
    private Set<Long> getTaskIdSet(UserVO userVO) {
        Set<Long> taskIdSet = SetUtil.zero();
        Opt.ofEmptyAble(userVO.getRoleVOList())
                .map(l -> l.stream().map(RoleVO::getCode).collect(Collectors.toList()))
                .map(roleCodeList -> {
                    if (CollUtil.contains(roleCodeList, "task_admin") || CollUtil.contains(roleCodeList, "admin")) {
                        FaultLog log = new FaultLog();
                        log.setTaskId(0L);
                        return ListUtil.of(log);
                    } else {
                        List<FaultLog> logList = faultLogService.lambdaQuery()
                                .select(FaultLog::getTaskId)
                                .in(FaultLog::getOperator, userVO.getId())
                                .list();
                        if (CollUtil.isEmpty(logList)) {
                            FaultLog log = new FaultLog();
                            log.setTaskId(-99L);
                            logList.add(log);
                        }
                        // 当前处理人的工单也要加入筛选条件
                        Long id = userVO.getId();
                        Opt.ofEmptyAble(this.lambdaQuery().eq(Task::getActiveUser, id).list())
                                .map(l -> l.stream().map(Task::getId).collect(Collectors.toList()))
                                .ifPresent(taskIdSet::addAll);
                        return logList;
                    }
                })
                .ifPresent(logs -> taskIdSet.addAll(logs.stream().map(FaultLog::getTaskId).collect(Collectors.toSet())));
        return taskIdSet;
    }

    @Override
    public TaskVO getTaskById(Long taskId) {
        var wrapper = new MPJLambdaWrapper<Task>()
                .selectAll(Task.class)
                .selectAs(Store::getName, TaskVO::getStoreName)
                .selectAs(Store::getSalesperson, TaskVO::getSalesperson)
                .selectAs(Store::getMaintainStatus, TaskVO::getMaintainStatus)
                .selectCollection(FileInfo.class, TaskTempVO::getFileList)
                .leftJoin(Store.class, Store::getId, Task::getStoreId)
                .leftJoin(FileInfo.class, on -> on
                        .eq(FileInfo::getSourceId, Task::getId)
                        .eq(FileInfo::getStoreId, Task::getStoreId))
                .eq(Task::getId, taskId);
        return this.selectJoinOne(TaskVO.class, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long circTask(TaskDTO data) {
        UserVO user = (UserVO) StpUtil.getTokenSession().get("curLoginUser");
        Store store = storeService.getById(data.getStoreId());

        handleTaskTemp(data);
        Task task = prepareTask(data, user, store);
        sendNotifications(task, user, store);
        handleFiles(data, task, user);
        return task.getId();
        /**
         * fixme
         * 1.修改工单的所属项目,工单的日志和文件查询不到
         * 2.任然会推送一次钉钉提醒
         */
    }

    /**
     * <p>创建工单前,先判断预工单是否已经确认。</p>
     * <p>如果未确认,将预工单状态改为已确认。后面的流程进行创建工单。</p>
     *
     * @param data 前端传参
     */
    private void handleTaskTemp(TaskDTO data) {
        if (ObjUtil.isNotNull(data.getTaskTempId())) {
            Task existTask = this.lambdaQuery().eq(Task::getTaskTempId, data.getTaskTempId()).one();
            Assert.isNull(existTask, "工单已创建,无需再次确认");
            taskTempService.lambdaUpdate()
                    .set(TaskTemp::getStatus, 3)
                    .set(TaskTemp::getOperator, data.getActiveUser())
                    .set(TaskTemp::getStoreId, data.getStoreId())
                    .eq(TaskTemp::getId, data.getTaskTempId())
                    .update(new TaskTemp());
        }
    }

    /**
     * 根据前端是否传参工单id,来判断是更新工单还是新增工单,并创建对应的工单日志
     *
     * @param data  前端传参
     * @param user  当前登录用户
     * @param store 项目
     * @return vion.model.Task
     */
    private Task prepareTask(TaskDTO data, UserVO user, Store store) {
        Task task = converter.convert(data, Task.class);
        if (task.getId() == null) {
            task.setCreateUser(user.getId());
            task.setUuid(IdUtil.nanoId());
            this.save(task);

            Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_ID.getVal() + store.getSalesperson()).get())
                    .map(u -> (User) u)
                    .map(User::getUserid)
                    .ifPresent(userid -> dingMod.workMsg(buildMsg2(userid, store.getName(), task)));

            // 预工单文件在工单创建时,复制一份到工单文件夹下
            Opt.ofNullable(data.getTaskTempId())
                    .map(taskTempId -> fileService.lambdaQuery()
                            .eq(FileInfo::getSourceId, taskTempId)
                            .eq(FileInfo::getSourceType, 2)
                            .eq(FileInfo::getStoreId, 0L)
                            .list()
                    )
                    .filter(CollUtil::isNotEmpty)
                    .ifPresent(fileInfoList -> fileInfoList.forEach(fileInfo -> {
                        String path = fileUrl + FileUtil.FILE_SEPARATOR + task.getStoreId() + FileUtil.FILE_SEPARATOR + task.getId() + FileUtil.FILE_SEPARATOR + fileInfo.getName();
                        FileUtil.copy(fileInfo.getUrl(), path, true);

                        FileInfo newFileInfo = new FileInfo();
                        newFileInfo.setStoreId(task.getStoreId());
                        newFileInfo.setSourceId(task.getId());
                        newFileInfo.setSourceType(3);
                        newFileInfo.setName(fileInfo.getName());
                        newFileInfo.setUrl(path);
                        newFileInfo.setType(fileInfo.getType());
                        newFileInfo.setSha256(fileInfo.getSha256());
                        newFileInfo.setUploader(fileInfo.getUploader());
                        fileService.save(newFileInfo);
                    }));

            List<FaultLog> saveList = new ArrayList<>();
            // 预工单提交,客户名称不在系统用户表内。单独处理客户提交的预工单日志
            FaultLog faultLog = new FaultLog();
            faultLog.setTaskId(task.getId());
            faultLog.setStoreId(task.getStoreId());
            faultLog.setOperator(-1L);
            faultLog.setContent(data.getRepairPeople() + "|提交工单");
            faultLog.setCreateTime(task.getRepairTime());
            saveList.add(faultLog);

            // 添加工单处理日志
            // 预工单确认,变为工单,添加日志
            FaultLog faultLog1 = new FaultLog();
            faultLog1.setTaskId(task.getId());
            faultLog1.setStoreId(task.getStoreId());
            faultLog1.setOperator(user.getId());
            faultLog1.setContent("确认工单");
            faultLog1.setRemark(task.getRemark());
            saveList.add(faultLog1);
            faultLogService.saveBatch(saveList);
        } else {
            this.updateById(task);
            handleFaultLog(data, user, task);
        }
        return task;
    }

    /**
     * 工单日志处理
     *
     * @param data 前端传参
     * @param user 当前登录用户
     * @param task 工单
     */
    private void handleFaultLog(TaskDTO data, UserVO user, Task task) {
        FaultLog faultLog = new FaultLog();
        faultLog.setTaskId(task.getId());
        faultLog.setStoreId(task.getStoreId());
        faultLog.setOperator(user.getId());
        faultLog.setRemark(task.getRemark());
        faultLog.setManHour(data.getManHour());
        faultLog.setContent(getFaultLogContent(task.getStatus()));
        faultLogService.save(faultLog);
    }

    private String getFaultLogContent(int status) {
        return switch (status) {
            case 2 -> "工单正在处理中";
            case 3 -> "工单处理完成";
            case 4 -> "工单挂起";
            case 5 -> "工单已关闭";
            default -> "";
        };
    }

    /**
     * 钉钉提醒和微信提醒
     *
     * @param task  工单
     * @param user  当前登录用户
     * @param store 项目
     */
    private void sendNotifications(Task task, UserVO user, Store store) {
        Task existTask = this.getById(task.getId());
        Long activeUserId = task.getActiveUser();
        Set<String> useridList = new HashSet<>();
        Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_ID.getVal() + activeUserId).get())
                .map(u -> (User) u)
                .map(User::getUserid)
                .ifPresent(useridList::add);
        if (task.getStatus() == 3) {
            // 工单完成时,推送钉钉消息到预工单的确认人
            Opt.ofNullable(existTask.getTaskTempId())
                    .map(taskTempId -> taskTempService.getById(taskTempId).getOperator())
                    .map(userService::getById)
                    .map(User::getUserid)
                    .ifPresent(useridList::add);
        }
        JSONObject msg = buildMsg(String.join(",", useridList), store.getName(), existTask);
        String pushRes = dingMod.workMsg(msg);

        // todo 异步微信公众号消息推送
        if (task.getStatus() == 3) {
            Opt.ofNullable(existTask.getTaskTempId())
                    .map(taskTempId -> taskTempService.getById(taskTempId).getOpenid())
                    .ifPresent(openid -> {
                        Map<Integer, String> statusMap = MapUtil.<Integer, String>builder()
                                .put(1, "待确认")
                                .put(2, "进行中")
                                .put(3, "已完成")
                                .put(4, "挂起")
                                .build();
                        List<WxMpTemplateData> wxMpTemplateDataList = ListUtil.of(
                                new WxMpTemplateData("character_string21", existTask.getUuid()),
                                new WxMpTemplateData("thing12", DesensitizedUtil.chineseName(user.getUsername())),
                                new WxMpTemplateData("time11", DateUtil.formatDateTime(new Date())),
                                new WxMpTemplateData("thing20", existTask.getFaultDescription().length() > 20 ? StrUtil.sub(existTask.getFaultDescription(), 0, 17) + "..." : existTask.getFaultDescription()),
                                new WxMpTemplateData("phrase25", statusMap.get(existTask.getStatus())));
                        String sentMsg = wechatMod.sendMsg("H3zWJysLWrcxrUlrgqPnjDV7LyWLaml_Ap9WsLuQDCs", openid, wxMpTemplateDataList, null);
                    });
        }
    }

    /**
     * 文件处理
     *
     * @param data 前端传参
     * @param task 工单
     * @param user 当前登录用户
     */
    private void handleFiles(TaskDTO data, Task task, UserVO user) {
        Opt.ofNullable(data.getFiles())
                .ifPresent(fileList ->
                        Arrays.stream(fileList).forEach(infile -> {
                            String orgName = infile.getOriginalFilename();
                            String mainName = FileNameUtil.mainName(orgName);
                            String fileExt = FileNameUtil.extName(orgName);
                            String filename = StrUtil.format("{}_{}.{}", mainName, DateUtil.format(new Date(), "yyyyMMdd_HHmmssSSS"), fileExt);
                            String path = fileUrl + FileUtil.FILE_SEPARATOR + data.getStoreId() + FileUtil.FILE_SEPARATOR + task.getId() + FileUtil.FILE_SEPARATOR + filename;
                            File file = FileUtil.touch(path);
                            try {
                                infile.transferTo(file);
                            } catch (IOException e) {
                                log.error("保存文件出错", e);
                            }

                            FileInfo fileInfo = new FileInfo();
                            fileInfo.setStoreId(task.getStoreId());
                            fileInfo.setSourceId(task.getId());
                            fileInfo.setSourceType(3);
                            fileInfo.setName(filename);
                            fileInfo.setUrl(path);
                            fileInfo.setType(FileNameUtil.extName(file));
                            fileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
                            fileInfo.setUploader(user.getUsername());
                            fileService.save(fileInfo);
                        }));
    }

    @Override
    public String batchIns(List<TaskDTO> data) {
        return this.saveBatch(converter.convert(data, Task.class)) ? "成功" : "失败";
    }

    @Override
    public TaskVO getTaskByUuid(String uuid) {
        MPJLambdaWrapper<Task> wrapper = new MPJLambdaWrapper<Task>()
                .selectAll(Task.class)
                .selectAs(Store::getName, TaskVO::getStoreName)
                .selectAs(Store::getSalesperson, TaskVO::getSalesperson)
                .selectAs(Store::getMaintainStatus, TaskVO::getMaintainStatus)
                .selectCollection(FaultLog.class, TaskVO::getFaultLogList)
                .leftJoin(Store.class, Store::getId, Task::getStoreId)
                .leftJoin(FaultLog.class, FaultLog::getTaskId, Task::getId)
                .eq(Task::getUuid, uuid);
        TaskVO vo = this.selectJoinOne(TaskVO.class, wrapper);
        // 进行中的任务,在最后追加一条当前处理人正在处理的记录,仅做显示用
        if (vo.getStatus() == 2) {
            FaultLog faultLog = new FaultLog();
            faultLog.setOperator(vo.getActiveUser());
            faultLog.setContent("工单正在处理中");
            faultLog.setCreateTime(new Date());
            vo.getFaultLogList().add(faultLog);
        }
        return vo;
    }

    @Override
    public String forwardTask(Long taskId, String forwardUser) {
        Task task = this.getById(taskId);
        Store store = storeService.getById(task.getStoreId());

        JSONObject msg = buildMsg3(forwardUser, store.getName(), task);
        String pushRes = dingMod.workMsg(msg);
        if (StrUtil.contains(pushRes, "ok")) {
            return "成功";
        } else {
            return "失败";
        }
    }

    @Override
    public String urgeTask(Long taskId, String remark) {
        Task task = this.getById(taskId);
        Long activeUserId = task.getActiveUser();
        String userid = Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_ID.getVal() + activeUserId).get())
                .map(u -> (User) u)
                .map(User::getUserid)
                .orElse(null);
        Store store = storeService.getById(task.getStoreId());

        JSONObject msg = buildMsg4(userid, store.getName(), task, remark);
        String pushRes = dingMod.workMsg(msg);
        if (StrUtil.contains(pushRes, "ok")) {
            return "成功";
        } else {
            return "失败";
        }
    }

    @Override
    public List<Map<String, Object>> peopleAnalysis(Date startDate, Date endDate, Integer source) {
        List<Task> taskList = this.lambdaQuery()
                .between(ArrayUtil.isAllNotNull(startDate, endDate), Task::getRepairTime, startDate, endDate)
                .isNotNull(ObjUtil.equals(source, 1), Task::getTaskTempId)
                .isNull(ObjUtil.equals(source, 2), Task::getTaskTempId)
                .list();
        List<Store> storeList = storeService.list();
        Map<Long, String> id2UsernameMap = userService.list().stream().collect(Collectors.toMap(User::getId, User::getUsername));
        List<FaultLog> logList = faultLogService.lambdaQuery().isNotNull(FaultLog::getManHour).list();
        Map<Long, Double> taskId2HourMap = logList.stream().collect(Collectors.groupingBy(FaultLog::getTaskId, Collectors.summingDouble(FaultLog::getManHour)));

        // 人 => 工单
        Map<Long, List<Task>> p2TaskMap = taskList.stream().collect(Collectors.groupingBy(Task::getActiveUser));
        var resList = new ArrayList<Map<String, Object>>();
        p2TaskMap.forEach((p, list) -> {
            var hourSum = list.stream().mapToDouble(v -> taskId2HourMap.getOrDefault(v.getId(), 0D)).sum();

            var inList = list.stream().filter(v -> v.getStatus().equals(2)).toList();
            var expList = inList.stream().filter(v -> v.getExpDate().after(new Date())).toList();
            var finishList = list.stream().filter(v -> v.getStatus().equals(3)).toList();
            var storeIdSet = list.stream().map(Task::getStoreId).collect(Collectors.toSet());
            var storeNameList = storeList.stream().filter(v -> storeIdSet.contains(v.getId())).distinct().map(Store::getName).collect(Collectors.joining(","));
            Map<String, Object> cntMap = Map.of("person", id2UsernameMap.get(p),
                    "total", list,
                    "finish", finishList,
                    "in", inList,
                    "exp", expList,
                    "hourSum", hourSum,
                    "storeNameList", storeNameList);
            resList.add(cntMap);
        });
        // resList 按照 total对应的list的size降序排列
        resList.sort((o1, o2) -> ((List<Task>) o2.get("total")).size() - ((List<Task>) o1.get("total")).size());
        return resList;
    }

    @Override
    public List<Map<String, Object>> proAnalysis(Date startDate, Date endDate, Integer source) {
        List<Task> taskList = this.lambdaQuery()
                .between(ArrayUtil.isAllNotNull(startDate, endDate), Task::getRepairTime, startDate, endDate)
                .isNotNull(ObjUtil.equals(source, 1), Task::getTaskTempId)
                .isNull(ObjUtil.equals(source, 2), Task::getTaskTempId)
                .list();
        List<Store> storeList = storeService.list();
        Map<Long, String> id2UsernameMap = userService.list().stream().collect(Collectors.toMap(User::getId, User::getUsername));
        List<FaultLog> logList = faultLogService.lambdaQuery().isNotNull(FaultLog::getManHour).list();
        Map<Long, Double> taskId2HourMap = logList.stream().collect(Collectors.groupingBy(FaultLog::getTaskId, Collectors.summingDouble(FaultLog::getManHour)));

        Map<Long, String> storeId2NameMap = storeList.stream().collect(Collectors.toMap(Store::getId, Store::getName));
        // 项目 => 工单
        Map<Long, List<Task>> store2TaskMap = taskList.stream().collect(Collectors.groupingBy(Task::getStoreId));
        var resList = new ArrayList<Map<String, Object>>();
        store2TaskMap.forEach((p, list) -> {
            var hourSum = list.stream().mapToDouble(v -> taskId2HourMap.getOrDefault(v.getId(), 0D)).sum();

            var inList = list.stream().filter(v -> v.getStatus().equals(2)).toList();
            var expList = inList.stream().filter(v -> v.getExpDate().after(new Date())).toList();
            var finishList = list.stream().filter(v -> v.getStatus().equals(3)).toList();
            var userSet = list.stream().map(Task::getActiveUser).distinct().map(id2UsernameMap::get).collect(Collectors.joining(","));
            Map<String, Object> cntMap = Map.of("name", storeId2NameMap.get(p),
                    "total", list,
                    "finish", finishList,
                    "in", inList,
                    "exp", expList,
                    "hourSum", hourSum,
                    "userList", userSet);
            resList.add(cntMap);
        });
        resList.sort((o1, o2) -> ((List<Task>) o2.get("total")).size() - ((List<Task>) o1.get("total")).size());
        return resList;
    }

    @Override
    public Map<String, Map<String, List<Task>>> summaryAnalysis(Date startDate, Date endDate, Integer source) {
        Map<Long, String> id2UsernameMap = userService.list().stream().collect(Collectors.toMap(User::getId, User::getUsername));
        Map<Long, String> id2StoreNameMap = storeService.list().stream().collect(Collectors.toMap(Store::getId, Store::getName));

        var taskList = this.lambdaQuery()
                .between(ArrayUtil.isAllNotNull(startDate, endDate), Task::getRepairTime, startDate, endDate)
                .isNotNull(ObjUtil.equals(source, 1), Task::getTaskTempId)
                .isNull(ObjUtil.equals(source, 2), Task::getTaskTempId)
                .eq(Task::getStatus, 2).list();
        var map = taskList.stream().collect(Collectors.groupingBy(Task::getActiveUser, Collectors.groupingBy(Task::getStoreId)));
        var resMap = new HashMap<String, Map<String, List<Task>>>();
        map.forEach((k, m) -> {
            var username = id2UsernameMap.get(k);
            var storeMap = new HashMap<String, List<Task>>();
            m.forEach((k1, l) -> storeMap.put(id2StoreNameMap.get(k1), l));
            resMap.put(username, storeMap);
        });
        return resMap;
    }

    JSONObject buildMsg(String userid, String storeName, Task task) {
        RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal());

        var jsonObj = JSONUtil.ofObj()
                .set("agent_id", 2358374016L)
                .set("userid_list", userid);

        var msg = JSONUtil.ofObj();
        var content = JSONUtil.ofObj().set("title", "您有一条新工单请及时处理哦~_~");
        String template = """
                #### 门店信息: **{}** [FullOfVitality]" +
                #### 任务编号:{}
                #### 报修人:{}
                #### 联系方式:{}
                #### 当前工单状态:{}
                #### 故障描述:{}
                #### 发送时间:{}
                """;
        String markdown = StrUtil.format(template,
                storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), task.getFaultDescription(), DateUtil.now());
        content.set("markdown", markdown).set("btn_orientation", "1");

        var jsonArray = JSONUtil.ofArray()
                .put(JSONUtil.ofObj()
                        .set("title", "查看详情")
                        .set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FstoreId%3D" + task.getStoreId() + "%26taskId%3D" + task.getId()));
        content.set("btn_json_list", jsonArray);

        msg.set("msgtype", "action_card").set("action_card", content);
        jsonObj.set("msg", msg);
        return jsonObj;
    }

    JSONObject buildMsg2(String userid, String storeName, Task task) {
        var jsonObj = JSONUtil.ofObj()
                .set("agent_id", 2358374016L)
                .set("userid_list", userid);

        var msg = JSONUtil.ofObj();
        var content = JSONUtil.ofObj().set("title", "工单消息提醒");
        String template = """
                #### 门店信息: **{}**
                #### 报修人:{}
                #### 联系方式:{}
                #### 故障描述:{}
                #### 发送时间:{}
                """;
        String markdown = StrUtil.format(template,
                storeName, task.getRepairPeople(), task.getRepairPhone(), task.getFaultDescription(), DateUtil.now());
        content.set("markdown", markdown).set("btn_orientation", "1");

        var jsonArray = JSONUtil.ofArray()
                .put(JSONUtil.ofObj()
                        .set("title", "查看详情")
                        .set("action_url", """
                                https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FtaskUuid%3D""" + task.getUuid()));
        content.set("btn_json_list", jsonArray);

        msg.set("msgtype", "action_card").set("action_card", content);
        jsonObj.set("msg", msg);
        return jsonObj;
    }

    JSONObject buildMsg3(String userid, String storeName, Task task) {
        RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal());

        var jsonObj = JSONUtil.ofObj().set("agent_id", 2358374016L).set("userid_list", userid);

        var msg = JSONUtil.ofObj();
        var content = JSONUtil.ofObj().set("title", "工单转发提醒");
        String template = """
                #### 门店信息: **{}** [FullOfVitality]`
                #### 任务编号:{}
                #### 报修人:{}
                #### 联系方式:{}
                #### 当前工单状态:{}
                #### 故障描述:{}
                #### 发送时间:{}
                """;
        String markdown = StrUtil.format(template,
                storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), task.getFaultDescription(), DateUtil.now());
        content.set("markdown", markdown).set("btn_orientation", "1");

        var jsonArray = JSONUtil.ofArray()
                .put(JSONUtil.ofObj()
                        .set("title", "查看详情")
                        .set("action_url", """
                                https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FtaskUuid%3D""" + task.getUuid()));
        content.set("btn_json_list", jsonArray);

        msg.set("msgtype", "action_card").set("action_card", content);
        jsonObj.set("msg", msg);
        return jsonObj;
    }

    JSONObject buildMsg4(String userid, String storeName, Task task, String remark) {
        RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal());

        var jsonObj = JSONUtil.ofObj()
                .set("agent_id", 2358374016L)
                .set("userid_list", userid);

        var msg = JSONUtil.ofObj();
        var content = JSONUtil.ofObj().set("title", "工单催办提醒");
        String template = """
                #### 门店信息: **{}** [FullOfVitality]
                #### 任务编号:{}
                #### 报修人:{}
                #### 联系方式:{}
                #### 当前工单状态:{}
                #### 催办提醒:**{}**
                #### 发送时间:{}
                """;
        String markdown = StrUtil.format(template,
                storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), remark, DateUtil.now());
        content.set("markdown", markdown).set("btn_orientation", "1");

        var jsonArray = JSONUtil.ofArray()
                .put(JSONUtil.ofObj()
                        .set("title", "查看详情")
                        .set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FstoreId%3D" + task.getStoreId() + "%26taskId%3D" + task.getId()));
        content.set("btn_json_list", jsonArray);

        msg.set("msgtype", "action_card").set("action_card", content);
        jsonObj.set("msg", msg);
        return jsonObj;
    }
}