StoreServiceImpl.java 28.9 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
package vion.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.date.DateUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileUtil;
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.cron.CronUtil;
import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.http.html.HtmlUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import vion.constant.RedisKeyEnum;
import vion.dto.StatusDTO;
import vion.dto.StoreDTO;
import vion.mapper.StoreMapper;
import vion.mapper.TaskMapper;
import vion.model.*;
import vion.service.*;
import vion.third.DingMod;
import vion.vo.ContractVO;
import vion.vo.StoreVO;
import vion.vo.TagVO;
import vion.vo.UserVO;

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

@Service
@RequiredArgsConstructor
@Slf4j
public class StoreServiceImpl extends MPJBaseServiceImpl<StoreMapper, Store> implements IStoreService {

    private final IAccountService accountService;
    private final IRContractStoreService contractStoreService;
    private final IContractPaymentService contractPaymentService;
    private final IContractService contractService;
    private final IFileService fileService;
    private final IFaultLogService faultLogService;
    private final IFormService formService;
    private final IInspectService inspectService;
    private final ITagService tagService;
    private final IRStoreTagService storeTagService;
    private final IRStoreUserService storeUserService;
    private final IStoreLogService storeLogService;
    private final ITaskTempService taskTempService;
    private final Converter converter;
    private final DingMod dingMod;
    // 引入 taskService 会循环依赖
    private final TaskMapper taskMapper;
    private final RedissonClient redissonClient;

    @Value("${fileUrl:}")
    private String fileUrl;

    @Override
    public Page<StoreVO> getStoreList(StoreDTO data, List<OrderItem> orderItemList) {
        var storeIdListByTagId = Optional.ofNullable(data.getTagId())
                .map(tagId -> storeTagService.lambdaQuery().eq(RStoreTag::getTagId, tagId).list())
                .map(storeTagList -> storeTagList.stream().map(RStoreTag::getStoreId).collect(Collectors.toList()))
                .filter(CollUtil::isNotEmpty)
                .orElse(List.of(-1L));

        var storeIdListByMainUser = Optional.ofNullable(data.getMainUser())
                .map(mainUser -> storeUserService.lambdaQuery().eq(RStoreUser::getUserId, mainUser).eq(RStoreUser::getIsMain, 1).list())
                .map(storeUserList -> storeUserList.stream().map(RStoreUser::getStoreId).collect(Collectors.toList()))
                .filter(CollUtil::isNotEmpty)
                .orElse(List.of(-1L));

        var store = converter.convert(data, Store.class);
        var page = Page.<Store>of(data.getPageNum(), data.getPageSize());
        Opt.ofEmptyAble(orderItemList).ifPresent(page::addOrder);

        // 单独处理 estDate 字段
        var estDate = store.getEstDate();
        store.setEstDate(null);

        var storeList = this.lambdaQuery(store)
                .in(ObjUtil.isNotNull(data.getTagId()), Store::getId, storeIdListByTagId)
                .in(ObjUtil.isNotNull(data.getMainUser()), Store::getId, storeIdListByMainUser)
                .gt(ObjUtil.isNotNull(estDate), Store::getEstDate, estDate)
                .page(page);
        // todo 缓存
        List<Account> accountList = accountService.list();

        var storeIdList = Opt.ofEmptyAble(storeList.getRecords())
                .map(recs -> recs.stream().map(Store::getId).collect(Collectors.toList()))
                .orElse(ListUtil.empty());

        // storeId -> 文件数量
        var store2CntMap = Opt.ofEmptyAble(storeIdList)
                .map(l -> fileService.lambdaQuery()
                        .in(FileInfo::getSourceId, l)
                        .in(FileInfo::getStoreId, l)
                        .in(FileInfo::getSourceType, 1, 24, 25, 26, 27, 28)
                        .list())
                .map(fileList -> fileList.stream().collect(Collectors.groupingBy(FileInfo::getStoreId, Collectors.counting())))
                .orElse(MapUtil.empty());
        // storeId -> 项目绑定的合同的 list
        var storeIdMap = Opt.ofEmptyAble(storeIdList)
                .map(l -> contractStoreService.lambdaQuery().in(RContractStore::getStoreId, l).list())
                .map(contractStoreList -> contractStoreList.stream().collect(Collectors.groupingBy(RContractStore::getStoreId)))
                .orElse(MapUtil.empty());
        // 项目绑定的合同的id
        var contractIdList = Opt.ofEmptyAble(storeIdMap.values())
                .map(values -> values.stream()
                        .flatMap(List::stream)
                        .map(RContractStore::getContractId)
                        .collect(Collectors.toList()))
                .orElse(Collections.emptyList());
        // contractId -> contract
        var id2ContractMap = Opt.ofEmptyAble(contractIdList)
                .map(l -> contractService.lambdaQuery()
                        .select(Contract::getId, Contract::getName, Contract::getContractNo, Contract::getType, Contract::getSignDate, Contract::getWarrantyPeriod, Contract::getFinalDate, Contract::getStatus, Contract::getSaleName, Contract::getCustomerName, Contract::getMaintainSdate, Contract::getMaintainEdate)
                        .in(Contract::getId, l).list())
                .map(contractList -> contractList.stream().collect(Collectors.toMap(Contract::getId, Function.identity())))
                .orElse(MapUtil.empty());

        // contractId -> 合同付款约定
        var contractId2CpMap = Opt.ofEmptyAble(contractIdList)
                .map(l -> contractPaymentService.lambdaQuery().in(ContractPayment::getContractId, l).in(ContractPayment::getPaymentType, 3, 4).isNotNull(ContractPayment::getNodeDate).list())
                .map(contractPaymentList -> contractPaymentList.stream().collect(Collectors.groupingBy(ContractPayment::getContractId, Collectors.collectingAndThen(Collectors.toList(), v -> {
                    v.sort(Comparator.comparing(ContractPayment::getPaymentType).reversed());
                    return v;
                }))))
                .orElse(MapUtil.empty());

        // storeId -> taskIdList
        var store2TaskIdMap = Opt.ofEmptyAble(storeIdList)
                .map(l -> taskMapper.selectList(Wrappers.lambdaQuery(Task.class).in(Task::getStoreId, l)))
                .map(taskList -> taskList.stream().collect(Collectors.groupingBy(Task::getStoreId, Collectors.mapping(Task::getId, Collectors.toList()))))
                .orElse(MapUtil.empty());
        var taskIds = store2TaskIdMap.values().stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
        var taskServiceOrderMap = Opt.ofEmptyAble(taskIds)
                .map(t -> Db.list(Wrappers.lambdaQuery(ServiceOrder.class).in(ServiceOrder::getTaskId, taskIds)))
                .map(serviceOrderList -> serviceOrderList.stream().collect(Collectors.groupingBy(ServiceOrder::getTaskId)))
                .orElse(MapUtil.empty());

        // storeId -> storeLog
        var store2LogMap = Opt.ofEmptyAble(storeIdList)
                .map(l -> storeLogService.lambdaQuery().in(StoreLog::getStoreId, l).list())
                .map(storeLogList -> storeLogList.stream().collect(Collectors.groupingBy(StoreLog::getStoreId)))
                .orElse(MapUtil.empty());

        // storeId -> tagList
        var storeId2TagMap = Opt.ofEmptyAble(storeIdList)
                .map(l -> {
                    MPJLambdaWrapper<Tag> wrapper = new MPJLambdaWrapper<Tag>()
                            .select(Tag::getId, Tag::getName, Tag::getRemark)
                            .selectAs(RStoreTag::getStoreId, TagVO::getStoreId)
                            .leftJoin(RStoreTag.class, RStoreTag::getTagId, Tag::getId)
                            .in(RStoreTag::getStoreId, l);
                    return tagService.selectJoinList(TagVO.class, wrapper);
                })
                .filter(CollUtil::isNotEmpty)
                .map(tagVOS -> tagVOS.stream().collect(Collectors.groupingBy(TagVO::getStoreId)))
                .orElse(MapUtil.empty());


        // storeId -> userId(项目主要负责人 or 项目经理)
        var storeId2UserIdMap = Opt.ofEmptyAble(storeIdList)
                .map(l -> storeUserService.lambdaQuery().in(RStoreUser::getStoreId, l).eq(RStoreUser::getIsMain, 1).list())
                .map(suList -> suList.stream().collect(Collectors.toMap(RStoreUser::getStoreId, RStoreUser::getUserId)))
                .orElse(MapUtil.empty());

        List<StoreVO> storeVOList = new ArrayList<>();
        storeList.getRecords().forEach(item -> {
            var storeVO = converter.convert(item, StoreVO.class);
            storeVO.setAccountName(accountList.stream().filter(v -> v.getId().equals(item.getAccountId())).map(Account::getName).findFirst().orElse("--"));
            storeVO.setFileNum(store2CntMap.getOrDefault(item.getId(), 0L));

            Long storeId = item.getId();
            // 关联合同
            var contractStores = storeIdMap.get(storeId);
            storeVO.setContractCount(Opt.ofEmptyAble(contractStores).map(List::size).orElse(0));
            storeVO.setContractVOList(id2ContractMap.values().stream()
                    .filter(v -> CollUtil.isNotEmpty(contractStores) && contractStores.stream().map(RContractStore::getContractId).toList().contains(v.getId()))
                    .map(v -> converter.convert(v, ContractVO.class))
                    .collect(Collectors.toList()));

            var masterContract = id2ContractMap.getOrDefault(item.getMasterContract(), null);
            // 关联合同验收时间
            Opt.ofNullable(masterContract)
                    .map(c -> contractId2CpMap.getOrDefault(c.getId(), ListUtil.empty()))
                    .filter(CollUtil::isNotEmpty)
                    .map(l -> l.get(0).getNodeDate())
                    .ifPresent(nodeDate -> masterContract.setFinalDate(nodeDate));
            storeVO.setMainContract(Opt.ofNullable(masterContract).map(c -> converter.convert(c, ContractVO.class)).orElse(null));

            storeVO.setTaskCount(store2TaskIdMap.getOrDefault(storeId, ListUtil.empty()).size());
            storeVO.setLogCount(store2LogMap.getOrDefault(storeId, ListUtil.empty()).size());

            // 补充服务单
            if (store2TaskIdMap.containsKey(item.getId())) {
                var cnt = store2TaskIdMap.get(item.getId())
                        .stream().mapToLong(taskId -> taskServiceOrderMap.getOrDefault(taskId, ListUtil.empty()).size()).sum();
                storeVO.setServiceOrderCount((int) cnt);
            }
            // 关联标签
            storeVO.setTagList(storeId2TagMap.getOrDefault(storeId, ListUtil.empty()));
            // 关联项目负责人 or 项目经理
            storeVO.setMainUser(storeId2UserIdMap.getOrDefault(storeId, null));
            storeVOList.add(storeVO);
        });
        return Page.<StoreVO>of(data.getPageNum(), data.getPageSize(), storeList.getTotal()).setRecords(storeVOList);
    }

    @Override
    public String updateStoreStage(StatusDTO statusDTO, String token) {
        this.update(Wrappers.<Store>lambdaUpdate()
                .set(Store::getProjectStage, statusDTO.getProjectStage())
                .eq(Store::getId, statusDTO.getStoreId()));
        UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser");

        Opt.ofNullable(statusDTO.getFiles()).ifPresent(tmpFiles -> {
            for (MultipartFile infile : tmpFiles) {
                //上传url地址
                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 + statusDTO.getStoreId() + FileUtil.FILE_SEPARATOR + statusDTO.getSourceId() + FileUtil.FILE_SEPARATOR + filename;
                File file = FileUtil.touch(path);
                try {
                    infile.transferTo(file);
                } catch (IOException e) {
                    log.error("保存文件出错", e);
                }
                // storeId = sourceId
                FileInfo tempFileInfo = new FileInfo();
                tempFileInfo.setStoreId(statusDTO.getStoreId());
                tempFileInfo.setSourceId(statusDTO.getSourceId());
                tempFileInfo.setSourceType(statusDTO.getSourceType());
                tempFileInfo.setName(filename);
                tempFileInfo.setUrl(path);
                tempFileInfo.setType(FileNameUtil.extName(file));
                tempFileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
                tempFileInfo.setUploader(userVO.getUsername());

                fileService.save(tempFileInfo);
            }
        });
        return "更新成功";
    }

    @Override
    public String calMaintainStatus(List<Long> storeIdList) {
        List<Store> storeList = this.lambdaQuery().in(CollUtil.isNotEmpty(storeIdList), Store::getId, storeIdList).list();
        Map<Long, List<Long>> storeId2ContractIdMap = Opt.ofEmptyAble(contractStoreService.list())
                .map(l -> l.stream().collect(Collectors.groupingBy(RContractStore::getStoreId, Collectors.mapping(RContractStore::getContractId, Collectors.toList()))))
                .orElse(MapUtil.empty());
        List<Contract> contractList = contractService.listByIds(storeId2ContractIdMap.values().stream().flatMap(List::stream).collect(Collectors.toList()));
        // storeId 为 key,List<Contract> 为 value 的 map
        Map<Long, List<Contract>> storeId2ContractListMap = storeList.stream()
                .collect(Collectors.toMap(Store::getId, store ->
                        storeId2ContractIdMap.getOrDefault(store.getId(), ListUtil.empty())
                                .stream()
                                .map(contractId -> contractList.stream().filter(contract -> contract.getId().equals(contractId)).findFirst().orElse(null))
                                .filter(Objects::nonNull)
                                .collect(Collectors.toList())));

        var contractId2CpMap = Opt.ofEmptyAble(contractPaymentService.lambdaQuery().in(ContractPayment::getPaymentType, 3, 4).isNotNull(ContractPayment::getNodeDate).list())
                .map(contractPaymentList -> contractPaymentList.stream().collect(Collectors.groupingBy(ContractPayment::getContractId, Collectors.collectingAndThen(Collectors.toList(), v -> {
                    v.sort(Comparator.comparing(ContractPayment::getPaymentType).reversed());
                    return v;
                }))))
                .orElse(MapUtil.empty());

        List<Store> updStoreList = new ArrayList<>();
        for (Store s : storeList) {
            s.setMaintainStatus("--");
            List<Contract> contracts = storeId2ContractListMap.getOrDefault(s.getId(), ListUtil.empty());
            if (CollUtil.isNotEmpty(contracts)) {
                // 1.项目关联的主合同在维保期内,那么这个项目就是在保
                Contract masterContract = contracts.stream().filter(contract -> ObjUtil.equals(contract.getId(), s.getMasterContract())).findFirst().orElse(null);
                if (ObjUtil.isNotNull(masterContract)) {
                    Integer warrantyPeriod = masterContract.getWarrantyPeriod();

                    Opt.ofNullable(contractId2CpMap.getOrDefault(masterContract.getId(), ListUtil.empty()))
                            .filter(CollUtil::isNotEmpty)
                            .map(l -> l.get(0).getNodeDate())
                            .ifPresent(masterContract::setFinalDate);
                    Date finalDate = masterContract.getFinalDate();

                    if (ArrayUtil.isAllNotNull(finalDate, warrantyPeriod)) {
                        Date finalDateEnd = DateUtil.offsetMonth(finalDate, warrantyPeriod);
                        boolean isIn = DateUtil.isIn(new Date(), finalDate, finalDateEnd);
                        if (isIn) {
                            s.setMaintainStatus("在保");
                            Store updStore = new Store();
                            updStore.setId(s.getId());
                            updStore.setMaintainStatus(s.getMaintainStatus());
                            updStoreList.add(updStore);
                            continue;
                        } else {
                            s.setMaintainStatus("脱保");
                        }
                    }
                }

                // 2.主合同脱保,那就判断维保合同
                Set<Boolean> maintainStatusSet = new HashSet<>();
                contracts.stream()
                        .filter(contract -> ObjUtil.equals(contract.getType(), 1))
                        .map(Contract::getMaintainEdate)
                        .filter(Objects::nonNull)
                        .forEach(maintainEdate -> maintainStatusSet.add(DateUtil.compare(maintainEdate, new Date()) >= 0));
                s.setMaintainStatus(CollUtil.isEmpty(maintainStatusSet) ? s.getMaintainStatus() : maintainStatusSet.contains(true) ? "在保" : "脱保");
            }
            Store updStore = new Store();
            updStore.setId(s.getId());
            updStore.setMaintainStatus(s.getMaintainStatus());
            updStoreList.add(updStore);
        }
        this.updateBatchById(updStoreList);
        return "计算成功";
    }

    @Override
    public List<StoreVO> storeScreen() {
        MPJLambdaWrapper<Store> wrapper = new MPJLambdaWrapper<Store>()
                .select(Store::getId, Store::getName, Store::getTaskDetail, Store::getPlanFinishDate, Store::getPercentage, Store::getStuckPoint, Store::getIsImportant)
                .selectCollection(User.class, StoreVO::getUserNameList, map -> map.result(User::getUsername))
                .leftJoin(RStoreUser.class, on -> on.eq(RStoreUser::getStoreId, Store::getId).eq(RStoreUser::getIsMain, 1))
                .leftJoin(User.class, User::getId, RStoreUser::getUserId)
                .eq(Store::getIsImportant, 1)
                .orderByAsc(Store::getFinishDate);
        return this.selectJoinList(StoreVO.class, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String mergeStore(StoreDTO dto) {
        // targetId 合并到 sourceId
        Long sourceId = dto.getSourceId();
        Store store = this.getById(sourceId);
        Long targetId = dto.getTargetId();
        // 项目关联合同合并
        Opt.ofEmptyAble(contractStoreService.lambdaQuery().select(RContractStore::getContractId).eq(RContractStore::getStoreId, targetId).list())
                .ifPresent(l -> {
                    List<RContractStore> existList = contractStoreService.lambdaQuery().select(RContractStore::getContractId).eq(RContractStore::getStoreId, sourceId).list();

                    List<RContractStore> insList = l.stream().filter(v -> !existList.contains(v)).map(v -> {
                        RContractStore contractStore = new RContractStore();
                        contractStore.setContractId(v.getContractId());
                        contractStore.setStoreId(sourceId);
                        return contractStore;
                    }).collect(Collectors.toList());
                    contractStoreService.saveBatch(insList);
                    contractStoreService.lambdaUpdate().eq(RContractStore::getStoreId, targetId).remove();
                });

        // 工单相关合并
        taskMapper.update(new Task(), Wrappers.lambdaUpdate(Task.class).set(Task::getStoreId, sourceId).set(Task::getAccountId, store.getAccountId()).eq(Task::getStoreId, targetId));
        taskTempService.lambdaUpdate().set(TaskTemp::getStoreId, sourceId).eq(TaskTemp::getStoreId, targetId).update();
        // 所有 targetId 的文件 转移到 sourceId
        fileService.lambdaUpdate().set(FileInfo::getStoreId, sourceId).eq(FileInfo::getStoreId, targetId).update();
        faultLogService.lambdaUpdate().set(FaultLog::getStoreId, sourceId).eq(FaultLog::getStoreId, targetId).update();
        formService.lambdaUpdate().set(Form::getStoreId, sourceId).set(Form::getAccountId, store.getAccountId()).eq(Form::getStoreId, targetId).update(new Form());
        inspectService.lambdaUpdate().set(Inspect::getStoreId, sourceId).set(Inspect::getAccountId, store.getAccountId()).eq(Inspect::getStoreId, targetId).update(new Inspect());
        // 删除 targetId 对应的项目
        this.removeById(targetId);
        return "合并成功";
    }

    @Override
    public String addTag(Long id, List<Long> tagIdList) {
        storeTagService.lambdaUpdate().eq(RStoreTag::getStoreId, id).remove();
        Opt.ofEmptyAble(tagIdList).ifPresent(l -> {
            List<RStoreTag> list = l.stream().map(tagId -> {
                RStoreTag storeTag = new RStoreTag();
                storeTag.setStoreId(id);
                storeTag.setTagId(tagId);
                return storeTag;
            }).collect(Collectors.toList());
            storeTagService.saveBatch(list);
        });
        return "成功";
    }

    @Override
    public List<Map<String, Number>> fileDetail(List<Long> storeIdList) {
        var fileList = fileService.lambdaQuery()
                .in(FileInfo::getSourceId, storeIdList)
                .in(FileInfo::getStoreId, storeIdList)
                .in(FileInfo::getSourceType, 1, 24, 25, 26, 27, 28)
                .list();
        var storeId2FileMap = fileList.stream().collect(Collectors.groupingBy(FileInfo::getStoreId, Collectors.groupingBy(FileInfo::getSourceType)));
        return storeIdList.stream().map(storeId -> {
            var fileMap = storeId2FileMap.getOrDefault(storeId, MapUtil.empty());
            Map<String, Number> map = new HashMap<>();
            map.put("storeId", storeId);
            map.put("1", fileMap.getOrDefault(1, List.of()).size());
            map.put("24", fileMap.getOrDefault(24, List.of()).size());
            map.put("25", fileMap.getOrDefault(25, List.of()).size());
            map.put("26", fileMap.getOrDefault(26, List.of()).size());
            map.put("27", fileMap.getOrDefault(27, List.of()).size());
            map.put("28", fileMap.getOrDefault(28, List.of()).size());
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    public Boolean logNotify(Long id, String[] userIdStr) {
        MPJLambdaWrapper<Store> wrapper = new MPJLambdaWrapper<Store>()
                .select(Store::getName, Store::getBotToken)
                .selectCollection(StoreLog.class, StoreVO::getStoreLog)
                .leftJoin(StoreLog.class, StoreLog::getStoreId, Store::getId)
                .eq(StoreLog::getId, id);
        var storeVO = this.selectJoinOne(StoreVO.class, wrapper);
        var storeLog = storeVO.getStoreLog().get(0);
        var user = (User) redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_ID.getVal() + storeLog.getCreateUser()).get();

        var content = storeLog.getContent();
        var content1 = StrUtil.replace(content, "<br>", "\n");
        var logText = HtmlUtil.cleanHtmlTag(content1);
        var text = StrUtil.format("""
                ### 项目日志
                ### 项目:{}
                ### 提交人:{}
                ### 提交日期:{}
                ### 内容:
                > {}
                """, storeVO.getName(), user.getUsername(), DateUtil.formatDate(storeLog.getLogDate()), logText);
        var markdown = JSONUtil.ofObj()
                .set("title", "项目日志提醒")
                .set("text", text);

        JSONObject atObj = null;
        if (ArrayUtil.isNotEmpty(userIdStr)) {
            var arr = JSONUtil.ofArray();
            Arrays.stream(userIdStr).forEach(arr::put);
            var atUser = Arrays.stream(userIdStr).collect(Collectors.joining("@", "@", ""));
            System.out.println(atUser);
            atObj = JSONUtil.ofObj().set("atUserIds", arr);
            text = StrUtil.format("""
                    ### 项目日志
                    ### 查收人:{}
                    ### 项目:{}
                    ### 提交人:{}
                    ### 提交日期:{}
                    ### 内容:
                    > {}
                    """, atUser, storeVO.getName(), user.getUsername(), DateUtil.formatDate(storeLog.getLogDate()), logText);
            markdown.set("text", text);
        }

        var body = JSONUtil.ofObj()
                .set("msgtype", "markdown")
                .set("markdown", markdown)
                .setOpt("at", atObj);
        var pushRes = dingMod.robotPush(storeVO.getBotToken(), body.toString());
        return StrUtil.containsIgnoreCase(pushRes, "ok");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addCron(Long storeId, String storeName, String cronStr, String userId) {
        String scheduleId = null;
        try {
            var update = this.lambdaUpdate().eq(Store::getId, storeId).set(Store::getCronStr, cronStr).update();

            if (update) {
                scheduleId = CronUtil.schedule(cronStr, (org.dromara.hutool.cron.task.Task) () -> {
                    if (StrUtil.isBlank(userId)) {
                        log.info("storeId:{},该项目未设置项目经理,不发送日志提醒", storeId);
                        return;
                    }
                    var user = (User) redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_ID.getVal() + userId).get();
                    dingMod.workMsg(buildMsg(storeName, user.getUserid()));
                    log.info("storeId:{},项目发送日志提醒,提醒人:{}({})", storeId, user.getUsername(), user.getUserid());
                });
                if (!CronUtil.getScheduler().isStarted()) {
                    CronUtil.setMatchSecond(true);
                    CronUtil.start();
                }
                this.lambdaUpdate().eq(Store::getId, storeId).set(Store::getScheduleId, scheduleId).update();
                return "定时提醒任务添加成功";
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "定时提醒任务添加失败";
        } finally {
            if (StrUtil.isNotBlank(scheduleId)) {
                CronUtil.remove(scheduleId);
            }
        }
        return "定时提醒任务添加失败";
    }

    @Override
    public String stopCron(Long storeId) {
        var store = this.getById(storeId);
        var update = this.lambdaUpdate()
                .eq(Store::getId, storeId)
                .set(Store::getCronStr, null)
                .set(Store::getScheduleId, null)
                .update();
        if (update) {
            CronUtil.remove(store.getScheduleId());
            return "定时提醒任务移除成功";
        }
        return "定时提醒任务移除失败";
    }

    @Override
    public Map<Integer, Long> statState() {
        var storeList = this.lambdaQuery().eq(Store::getProjectState, 2).list();
        return storeList.stream().collect(Collectors.groupingBy(Store::getProjectStage, Collectors.counting()));
    }

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

        var msg = JSONUtil.ofObj();
        var content = JSONUtil.ofObj()
                .set("title", "项目日志提醒")
                .set("text", StrUtil.format("""
                        #### 项目:[{}]请及时提交日志
                        #### 发送时间:{}""", storeName, DateUtil.now()));

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