AbstractFollowStrategy.java 35.1 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 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
package cn.fw.shirasawa.service.bus.follow.strategy;

import cn.fw.shirasawa.common.utils.DateUtil;
import cn.fw.shirasawa.common.utils.MobileUtil;
import cn.fw.shirasawa.common.utils.StringUtils;
import cn.fw.shirasawa.domain.db.OriginalData;
import cn.fw.shirasawa.domain.db.follow.FollowRecord;
import cn.fw.shirasawa.domain.db.follow.FollowRecordLog;
import cn.fw.shirasawa.domain.db.follow.FollowTask;
import cn.fw.shirasawa.domain.db.pool.CluePool;
import cn.fw.shirasawa.domain.dto.FollowAttachmentDTO;
import cn.fw.shirasawa.domain.dto.FollowTaskCompleteDTO;
import cn.fw.shirasawa.domain.dto.FollowTerminationDTO;
import cn.fw.shirasawa.domain.enums.*;
import cn.fw.shirasawa.domain.vo.follow.FollowDetailVO;
import cn.fw.shirasawa.domain.vo.follow.FollowRecordHistoryVO;
import cn.fw.shirasawa.rpc.backlog.TodoRpcService;
import cn.fw.shirasawa.rpc.backlog.dto.BackLogItemDTO;
import cn.fw.shirasawa.rpc.ehr.EhrRpcService;
import cn.fw.shirasawa.rpc.ehr.dto.StaffInfoDTO;
import cn.fw.shirasawa.rpc.erp.UserService;
import cn.fw.shirasawa.rpc.erp.dto.UserInfoDTO;
import cn.fw.shirasawa.rpc.member.MemberRpcService;
import cn.fw.shirasawa.rpc.member.dto.MemberUserDTO;
import cn.fw.shirasawa.rpc.oop.OopService;
import cn.fw.shirasawa.rpc.oop.dto.ShopDTO;
import cn.fw.shirasawa.rpc.pstn.PstnRpcService;
import cn.fw.shirasawa.service.data.*;
import cn.fw.shirasawa.service.event.CancelApproveEvent;
import cn.fw.shirasawa.service.event.RecordCompleteEvent;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.fw.common.businessvalidator.Validator.BV;

/**
 * @author : kurisu
 * @className : AbstractFollowStrategy
 * @description : 策略抽象类
 * @date: 2020-08-17 10:42
 */
@Slf4j
@SuppressWarnings("Duplicates")
public abstract class AbstractFollowStrategy implements FollowStrategy {
    @Autowired
    protected FollowTaskService followTaskService;
    @Autowired
    protected FollowRecordService followRecordService;
    @Autowired
    protected UserService userService;
    @Autowired
    protected FollowRecordLogService followRecordLogService;
    @Autowired
    protected OopService oopService;
    @Autowired
    protected ApplicationEventPublisher eventPublisher;
    @Autowired
    protected TodoRpcService todoRpcService;
    @Autowired
    protected CluePoolService cluePoolService;
    @Autowired
    protected StringRedisTemplate redisTemplate;
    @Autowired
    protected EhrRpcService ehrRpcService;
    @Autowired
    protected PstnRpcService pstnRpcService;
    @Autowired
    protected SecretReportHistoryService secretReportHistoryService;
    @Autowired
    protected MemberRpcService memberRpcService;


    @Value("${spring.cache.locker.key-prefix}:termination")
    @Getter
    private String planKey;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void overdue(FollowRecord record) {
        record.setOutTime(OutTimeEnum.BE_OVERDUE);
        if (!Boolean.TRUE.equals(record.getAddTodo())) {
            record.setYn(Boolean.FALSE);
            followRecordService.updateById(record);
        } else {
            followRecordService.overdue(record.getId());
        }
        FollowTask task = followTaskService.getById(record.getTaskId());
        eventPublisher.publishEvent(new RecordCompleteEvent(record, task.getClueId()));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void complete(FollowRecord record, Long userId) {
        FollowTask task = followTaskService.getById(record.getTaskId());
        BV.isTrue(record.getUserId().equals(userId), () -> "无法完成非本人待办任务");
        BV.isTrue(OutTimeEnum.ONGOING.equals(record.getOutTime()), () -> "无法完成已逾期的待办任务");
        List<FollowRecordLog> list = followRecordLogService.list(Wrappers.<FollowRecordLog>lambdaQuery()
                .eq(FollowRecordLog::getRecordId, record.getId())
        );
        BV.isNotEmpty(list, () -> "请上传跟进记录");

        boolean match = list.stream().allMatch(log -> Objects.nonNull(log.getFeedbackType()));
        BV.isTrue(match, () -> "请检查跟进记录是否已完成客户反馈的录入");

        if (Boolean.TRUE.equals(record.getCompelTel())) {
            boolean matchAttType = list.stream().anyMatch(log -> AttTypeEnum.SMART_PHONE == log.getAttType());
            BV.isTrue(matchAttType, () -> "您本次没有拨打电话,无法完成跟进记录!");
        }

        record.setFollowTime(LocalDateTime.now());
        record.setOutTime(OutTimeEnum.BE_COMPLETE);
        followRecordService.updateById(record);
        if (Objects.nonNull(task)) {
            int times = task.getTimes() == null ? 0 : task.getTimes();
            task.setTimes(times + 1);
            followTaskService.updateById(task);
        }
        BackLogItemDTO dto = new BackLogItemDTO(record.getUserId(), record.getTodoCode(), String.valueOf(record.getId()),
                DateUtil.toDate(record.getFollowTime()), record.getShopId());
        todoRpcService.complete(dto);

        eventPublisher.publishEvent(new RecordCompleteEvent(record, task.getClueId()));
    }

    /**
     * 与上面代码重复 考虑到出错可能性 暂不对上面代码改造
     *
     * @param record      跟进待办
     * @param userId      完成人
     * @param ignoreCheck 是否忽略检查  true-忽略  false-不忽略
     */
    @Override
    public void complete(FollowRecord record, Long userId, Boolean ignoreCheck) {
        FollowTask task = followTaskService.getById(record.getTaskId());

        if (!ignoreCheck) {
            BV.isTrue(record.getUserId().equals(userId), () -> "无法完成非本人待办任务");
            BV.isTrue(OutTimeEnum.ONGOING.equals(record.getOutTime()), () -> "无法完成已逾期的待办任务");
            List<FollowRecordLog> list = followRecordLogService.list(Wrappers.<FollowRecordLog>lambdaQuery()
                    .eq(FollowRecordLog::getRecordId, record.getId())
            );
            BV.isNotEmpty(list, () -> "请上传跟进记录");
            boolean match = list.stream().allMatch(log -> Objects.nonNull(log.getFeedbackType()));
            BV.isTrue(match, () -> "请检查跟进记录是否已完成客户反馈的录入");
        } else {
            record.setOutTime(OutTimeEnum.BE_SYSTEM);
        }
        record.setFollowTime(LocalDateTime.now());

        followRecordService.updateById(record);
        if (Objects.nonNull(task)) {
            int times = task.getTimes() == null ? 0 : task.getTimes();
            task.setTimes(times + 1);
        }
        followTaskService.updateById(task);
        BackLogItemDTO dto = new BackLogItemDTO(record.getUserId(), record.getTodoCode(), String.valueOf(record.getId()),
                DateUtil.toDate(record.getFollowTime()), record.getShopId());
        todoRpcService.complete(dto);
        eventPublisher.publishEvent(new RecordCompleteEvent(record, task.getClueId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createNewRecord(FollowTask task, LocalDateTime nextTime, LocalDateTime nextEndTime, String note) {
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeTask(FollowTaskCompleteDTO taskCompleteDTO) {
        List<CluePool> cluePoolList = cluePoolService.list(Wrappers.<CluePool>lambdaQuery()
                .eq(CluePool::getRefererId, taskCompleteDTO.getDetailId())
                .eq(CluePool::getClueType, taskCompleteDTO.getFollowType())
                .in(CluePool::getClueStatus, ClueStatusEnum.WAITING, ClueStatusEnum.ONGOING)
                .eq(CluePool::getBizType, taskCompleteDTO.getBizType())
        );
        if (CollectionUtils.isEmpty(cluePoolList)) {
            return;
        }
        for (CluePool cluePool : cluePoolList) {
            cluePool.setFinishShopId(taskCompleteDTO.getShopId());
            cluePool.setFinishUserId(taskCompleteDTO.getUserId());
            UserInfoDTO user = userService.user(taskCompleteDTO.getUserId());
            if (Objects.nonNull(user)) {
                cluePool.setFinishUserName(user.getUserName());
            }
            ShopDTO shop = oopService.shop(taskCompleteDTO.getShopId());
            if (Objects.nonNull(shop)) {
                cluePool.setFinishShopName(shop.getShortName());
            }
            cluePool.setCloseTime(DateUtil.date2LocalDateTime(taskCompleteDTO.getCompleteTime()));
            if (ClueStatusEnum.ONGOING.equals(cluePool.getClueStatus())) {
                FollowTask task = followTaskService.queryOngoingTaskByClueId(cluePool.getId());
                if (Objects.isNull(task)) {
                    return;
                }
                task.setFinishUser(cluePool.getFinishUserId());
                task.setFinishUserName(cluePool.getFinishUserName());
                task.setFinishShop(cluePool.getFinishShopId());
                task.setCloseTime(cluePool.getCloseTime());
                boolean equals = task.getFollowShop().equals(cluePool.getFinishShopId());
                task.setState(equals ? TaskStateEnum.COMPLETE : TaskStateEnum.DEFEAT);
                if (!equals) {
                    task.setReason(TaskDefeatTypeEnum.F);
                }
                boolean succeed = followTaskService.updateById(task);
                if (succeed) {
                    completeTodo(task.getId());
                    CancelApproveEvent event = new CancelApproveEvent(task.getId(), ApproveTypeEnum.FOLLOW_DEFEAT);
                    eventPublisher.publishEvent(event);
                }
            }
            cluePool.setClueStatus(ClueStatusEnum.COMPLETE);
            cluePoolService.updateById(cluePool);
        }
    }

    @Override
    public void terminationTaskPlan(FollowTerminationDTO terminationDTO) {
        List<CluePool> cluePoolList = cluePoolService.list(Wrappers.<CluePool>lambdaQuery()
                .eq(CluePool::getRefererId, terminationDTO.getDetailId())
                .eq(CluePool::getClueType, terminationDTO.getFollowType())
                .in(CluePool::getClueStatus, ClueStatusEnum.WAITING, ClueStatusEnum.ONGOING)
                .eq(CluePool::getBizType, terminationDTO.getBizType())
        );
        if (CollectionUtils.isEmpty(cluePoolList)) {
            return;
        }
        for (CluePool cluePool : cluePoolList) {
            endTask(cluePool);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void endTask(CluePool cluePool) {
        if (ClueStatusEnum.WAITING.equals(cluePool.getClueStatus())) {
            cluePool.setCloseTime(LocalDateTime.now());
            cluePool.setClueStatus(ClueStatusEnum.FAILURE);
            cluePoolService.updateById(cluePool);
        }

        FollowTask task = followTaskService.queryOngoingTaskByClueId(cluePool.getId());
        if (Objects.nonNull(task)) {
            task.setCloseTime(LocalDateTime.now());
            task.setReason(TaskDefeatTypeEnum.E);
            endTask(task, false);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void endTask(FollowTask task, boolean fromFlow) {
        Long clueId = task.getClueId();
        if (TaskStateEnum.ONGOING == task.getState()) {
            task.setState(TaskStateEnum.DEFEAT);
            task.setCloseTime(Objects.isNull(task.getCloseTime()) ? task.getDeadline() : task.getCloseTime());
            if (Objects.isNull(task.getReason())) {
                task.setReason(TaskDefeatTypeEnum.C);
            }
            followTaskService.updateById(task);
            completeTodo(task.getId());
        }
        CluePool cluePool = cluePoolService.getById(clueId);
        cluePool.setCloseTime(task.getCloseTime());
        cluePool.setClueStatus(ClueStatusEnum.FAILURE);
        cluePoolService.updateById(cluePool);

        if (!fromFlow) {
            CancelApproveEvent event = new CancelApproveEvent(task.getId(), ApproveTypeEnum.FOLLOW_DEFEAT);
            eventPublisher.publishEvent(event);
        }
    }

    @Override
    public FollowDetailVO queryDetail(FollowRecord record) {
        FollowTask followTask = followTaskService.getById(record.getTaskId());
        BV.notNull(followTask, "跟进任务不存在");
        CluePool cluePool = cluePoolService.getById(followTask.getClueId());
        BV.notNull(cluePool, "跟进线索不存在");

        FollowDetailVO vo = new FollowDetailVO();
        assembleRecordDetail(vo, record, cluePool);
        vo.setTaskDeadline(followTask.getDeadline());
        return vo;
    }

    @Override
    public List<FollowRecordHistoryVO> queryHistoryByRecord(FollowRecord record) {
        FollowTask task = followTaskService.getById(record.getTaskId());
        List<FollowRecordHistoryVO> list = new ArrayList<>(queryHistoryByTask(task));
        return list.stream().sorted((a, b) -> b.getId().compareTo(a.getId())).collect(Collectors.toList());
    }

    @Override
    public List<FollowRecordHistoryVO> queryHistoryByTask(FollowTask task) {
        List<FollowRecord> followRecordList = new ArrayList<>();
        if (Objects.nonNull(task)) {
            Long clueId = task.getClueId();
            List<FollowTask> taskList = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                    .eq(FollowTask::getClueId, clueId)
                    .ne(FollowTask::getId, task.getId())
            );
            if (!CollectionUtils.isEmpty(taskList)) {
                for (FollowTask followTask : taskList) {
                    List<FollowRecord> recordList = followRecordService.getRecordList(followTask.getId());
                    if (!CollectionUtils.isEmpty(recordList)) {
                        followRecordList.addAll(recordList);
                    }
                }
            }
        }
        List<FollowRecord> recordList = followRecordService.getRecordList(task.getId());
        if (!CollectionUtils.isEmpty(recordList)) {
            followRecordList.addAll(recordList);
        }
        if (CollectionUtils.isEmpty(followRecordList)) {
            return new ArrayList<>();
        }
        List<Long> recordIds = followRecordList.stream().map(FollowRecord::getId).collect(Collectors.toList());
        Map<Long, String> map = followRecordList.stream().collect(Collectors.toMap(FollowRecord::getId, FollowRecord::getUserName));
        List<FollowRecordLog> attachments = followRecordLogService.getListByRecordIds(recordIds);
        if (CollectionUtils.isEmpty(attachments)) {
            return new ArrayList<>();
        }
        MemberUserDTO user = memberRpcService.user(task.getMemberId());
        List<FollowRecordHistoryVO> list = new ArrayList<>();
        for (FollowRecordLog attachment : attachments) {
            FollowRecordHistoryVO vo = new FollowRecordHistoryVO();
            vo.setAttachments(attachment.getAttachments());
            vo.setId(attachment.getId());
            vo.setCustomerName(Optional.ofNullable(user).map(MemberUserDTO::getRealName).orElse(null));
            vo.setRecordId(attachment.getRecordId());
            vo.setTaskId(attachment.getTaskId());
            vo.setAttType(attachment.getAttType());
            vo.setFeedbackType(attachment.getFeedbackType());
            vo.setFollowType(task.getType());
            vo.setUploadTime(attachment.getUploadTime());
            vo.setDescribes(attachment.getDescribes());
            vo.setUserName(map.get(attachment.getRecordId()));
            list.add(vo);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uploadAtt(FollowAttachmentDTO dto, FollowRecord record, Long userId) {
        BV.isTrue(record.getUserId().equals(userId), () -> "无法跟进非本人待办任务");
        BV.isTrue(OutTimeEnum.ONGOING.equals(record.getOutTime()), () -> "无法跟进已逾期的待办任务");
        FollowRecordLog recordLog = new FollowRecordLog();
        recordLog.setId(dto.getId());
        recordLog.setTaskId(record.getTaskId());
        recordLog.setAttachments(dto.getAttachments());
        recordLog.setFeedbackType(dto.getFeedbackTypeEnum());
        recordLog.setAttType(dto.getAttTypeEnum());
        recordLog.setDescribes(dto.getDescribes());
        recordLog.setRecordId(dto.getRecordId());
        if (Objects.isNull(dto.getId())) {
            recordLog.setUploadTime(LocalDateTime.now());
        }
        followRecordLogService.saveOrUpdate(recordLog);
        feedbackTask(record.getTaskId(), dto.getFeedbackTypeEnum());
    }

    @Override
    public List<FollowRecordHistoryVO> getRecordListByClue(CluePool cluePool) {
        Long clueId = cluePool.getId();
        List<FollowRecord> followRecordList = new ArrayList<>();
        List<FollowTask> taskList = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                .eq(FollowTask::getClueId, clueId)
        );
        if (!CollectionUtils.isEmpty(taskList)) {
            for (FollowTask followTask : taskList) {
                List<FollowRecord> recordList = followRecordService.getRecordList(followTask.getId());
                if (!CollectionUtils.isEmpty(recordList)) {
                    followRecordList.addAll(recordList);
                }
            }
        }

        if (CollectionUtils.isEmpty(followRecordList)) {
            return new ArrayList<>();
        }
        List<Long> recordIds = followRecordList.stream().map(FollowRecord::getId).collect(Collectors.toList());
        Map<Long, FollowRecord> map = followRecordList.stream().collect(Collectors.toMap(FollowRecord::getId, record -> record));
        List<FollowRecordLog> attachments = followRecordLogService.getListByRecordIds(recordIds);
        if (CollectionUtils.isEmpty(attachments)) {
            return new ArrayList<>();
        }
        List<FollowRecordHistoryVO> list = new ArrayList<>();
        for (FollowRecordLog attachment : attachments) {
            FollowRecordHistoryVO vo = new FollowRecordHistoryVO();
            vo.setAttachments(attachment.getAttachments());
            vo.setId(attachment.getId());
            vo.setRecordId(attachment.getRecordId());
            vo.setTaskId(map.get(attachment.getRecordId()).getTaskId());
            vo.setAttType(attachment.getAttType());
            vo.setFeedbackType(attachment.getFeedbackType());
            vo.setFollowType(cluePool.getClueType());
            vo.setUploadTime(attachment.getUploadTime());
            vo.setDescribes(attachment.getDescribes());
            vo.setUserName(map.get(attachment.getRecordId()).getUserName());
            list.add(vo);
        }
        return list;
    }

    @Override
    public FollowDetailVO followPoolDetail(FollowTask task) {
        CluePool cluePool = cluePoolService.getById(task.getClueId());
        BV.notNull(cluePool, "跟进线索不存在");
        FollowDetailVO vo = new FollowDetailVO();
        vo.setCustomerId(task.getCustomerId());
        vo.setType(task.getType().getValue());
        vo.setBizType(cluePool.getBizType().getValue());
        vo.setTaskId(task.getId());
        vo.setDeadline(task.getDeadline());
        queryTimes(cluePool.getId(), vo);
        return vo;
    }

    /**
     * 原始数据转线索
     *
     * @param originalData
     * @return
     */
    protected CluePool transformClue(OriginalData originalData) {
        CluePool cluePool = new CluePool();
        cluePool.setRefererId(originalData.getDetailId());
        cluePool.setCustomerId(originalData.getCustomerId());
        cluePool.setCustomerName(originalData.getCustomerName());
        cluePool.setNote(originalData.getNote());
        cluePool.setContacts(originalData.getContacts());
        cluePool.setFrameNo(originalData.getFrameNo());
        cluePool.setPlateNo(originalData.getPlateNo());
        cluePool.setClueType(originalData.getType());
        cluePool.setBizType(originalData.getBizType());
        cluePool.setAddTime(originalData.getGenerateTime());
        cluePool.setClueStatus(ClueStatusEnum.WAITING);
        cluePool.setRedistribution(originalData.getSecondary());
        cluePool.setOriginalUserId(originalData.getUserId());
        cluePool.setOriginalUserName(originalData.getUserName());
        if (StringUtils.isEmpty(originalData.getUserName())) {
            StaffInfoDTO info = ehrRpcService.queryStaffInfo(originalData.getUserId());
            cluePool.setOriginalUserName(Optional.ofNullable(info).map(StaffInfoDTO::getName).orElse(null));
        }
        cluePool.setOriginalShopId(originalData.getShopId());
        cluePool.setOriginalShopName(originalData.getShopName());
        if (StringUtils.isEmpty(originalData.getShopName())) {
            ShopDTO shop = oopService.shop(originalData.getShopId());
            cluePool.setOriginalShopName(Optional.ofNullable(shop).map(ShopDTO::getShortName).orElse(null));
        }
        cluePool.setGroupId(originalData.getGroupId());
        cluePool.setMemberId(originalData.getMemberId());
        cluePool.setFirstDeadline(originalData.getFirstDeadline());
        cluePool.setBizId(originalData.getBizId());
        cluePool.setCoverFlag(originalData.getCoverFlag());
        return cluePool;
    }

    /**
     * 创建跟进任务
     *
     * @param cluePool
     * @return
     */
    protected FollowTask createTask(CluePool cluePool) {
        FollowTask task = new FollowTask();
        String customerName = cluePool.getCustomerName();
        MemberUserDTO user = memberRpcService.user(cluePool.getMemberId());
        if (Objects.nonNull(user)) {
            customerName = StringUtils.isValid(user.getRealName()) ? user.getRealName() : user.getNickName();
            if (StringUtils.isEmpty(cluePool.getContacts())) {
                cluePool.setContacts(user.getPhone());
            }
        }
        task.setClueId(cluePool.getId());
        task.setCustomerId(cluePool.getCustomerId());
        task.setMemberId(cluePool.getMemberId());
        task.setCustomerName(customerName);
        task.setPlateNo(cluePool.getPlateNo());
        task.setType(cluePool.getClueType());
        task.setBizType(cluePool.getBizType());
        task.setBeginTime(cluePool.getStartTime());
        task.setRedistribution(cluePool.getRedistribution());
        task.setDeadline(cluePool.getDeadline());
        task.setState(TaskStateEnum.ONGOING);
        task.setFollowUser(cluePool.getOriginalUserId());
        task.setFollowUserName(cluePool.getOriginalUserName());
        task.setFollowShop(cluePool.getOriginalShopId());
        task.setGroupId(cluePool.getGroupId());
        task.setBizId(cluePool.getBizId());
        return task;
    }

    /**
     * 创建跟进待办基本信息
     *
     * @param task
     * @return
     */
    protected FollowRecord createRecord(FollowTask task) {
        return createRecord(task, task.getBeginTime(), task.getDeadline());
    }

    protected FollowRecord createRecord(FollowTask task, LocalDateTime beginTime, LocalDateTime deadline) {
        FollowRecord record = new FollowRecord();
        record.setTaskId(task.getId());
        record.setBizType(task.getBizType());
        record.setType(task.getType());
        record.setCustomerId(task.getCustomerId());
        record.setCustomerName(task.getCustomerName());
        record.setMemberId(task.getMemberId());
        record.setUserId(task.getFollowUser());
        record.setUserName(task.getFollowUserName());
        record.setPlanTime(beginTime);
        record.setDeadline(deadline);
        record.setOutTime(OutTimeEnum.ONGOING);
        record.setShopId(task.getFollowShop());
        record.setGroupId(task.getGroupId());
        record.setSecondary(Boolean.TRUE.equals(task.getRedistribution()));
        record.setAddTodo(Boolean.FALSE);
        record.setTodoCode(getTodoCode());
        record.setBizId(task.getBizId());
        record.setPlateNo(task.getPlateNo());
        boolean compelTel = false;
        //2022-05-20 需求 集客潜客  跟进记录每隔两次根据记录必须打电话
        if (FollowTypeEnum.CF == task.getType() || FollowTypeEnum.PF == task.getType()) {
            if (followRecordService.checkCompelCall(task.getId(), task.getFollowUser(), 2)) {
                compelTel = Boolean.TRUE;
            }
            record.setCompelTel(compelTel);
        } else {
            // 其他跟进首次必须打电话
            long count = followRecordLogService.count(Wrappers.<FollowRecordLog>lambdaQuery()
                    .eq(FollowRecordLog::getTaskId, record.getTaskId())
                    .eq(FollowRecordLog::getAttType, AttTypeEnum.SMART_PHONE)
            );
            record.setCompelTel(count <= 0);
        }
        //同一天多个市场活动跟进客户后,视为多个活动已跟进
        //同一天同一潜客:跟进任一次视为后续跟进为已跟进
        if (FollowTypeEnum.PF.equals(task.getType()) || FollowTypeEnum.AF.equals(task.getType())) {
            List<FollowRecord> existList = followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                    .eq(FollowRecord::getCustomerId, record.getCustomerId())
                    .eq(FollowRecord::getType, record.getType())
                    .eq(FollowRecord::getUserId, record.getUserId())
                    .eq(FollowRecord::getOutTime, OutTimeEnum.BE_COMPLETE)
                    .eq(FollowRecord::getYn, Boolean.TRUE)
                    .ge(FollowRecord::getFollowTime, LocalDate.now().atStartOfDay())
                    .le(FollowRecord::getFollowTime, LocalDateTime.now())
            );
            if (!CollectionUtils.isEmpty(existList)) {
                record.setOutTime(OutTimeEnum.BE_SYSTEM);
                record.setFollowTime(LocalDateTime.now());
            }
        }
        return record;
    }

    /**
     * 处理对应跟进任务的待办
     *
     * @param taskId
     */
    @Transactional(rollbackFor = Exception.class)
    public void completeTodo(Long taskId) {
        final LocalDateTime now = LocalDateTime.now();
        followRecordService.removeByTaskId(taskId);
        List<FollowRecord> list = Optional.ofNullable(followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                .eq(FollowRecord::getTaskId, taskId)
                .eq(FollowRecord::getOutTime, OutTimeEnum.ONGOING)
                .eq(FollowRecord::getAddTodo, Boolean.TRUE)
                .isNull(FollowRecord::getFollowTime)
                .ge(FollowRecord::getDeadline, now)
        )).orElse(new ArrayList<>());
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (FollowRecord record : list) {
            BackLogItemDTO dto = new BackLogItemDTO(record.getUserId(), record.getTodoCode(), String.valueOf(record.getId()), DateUtil.toDate(record.getPlanTime()), record.getShopId());
            record.setFollowTime(now);
            record.setOutTime(OutTimeEnum.BE_COMPLETE);
            boolean hasFollow = followRecordLogService.count(Wrappers.<FollowRecordLog>lambdaQuery()
                    .eq(FollowRecordLog::getRecordId, record.getId())
            ) > 0;

            if (hasFollow) {
                todoRpcService.complete(dto);
            } else {
                record.setOutTime(OutTimeEnum.BE_SYSTEM);
                todoRpcService.cancel(dto);
            }
        }
        followRecordService.updateBatchById(list);

        for (FollowRecord record : list) {
            eventPublisher.publishEvent(new RecordCompleteEvent(record, null));
        }
    }

    protected void updateContacts(FollowRecord record) {
        Long memberId = record.getMemberId();
        MemberUserDTO user = memberRpcService.user(memberId);
        if (Objects.nonNull(user)) {
            record.setContacts(user.getPhone());
        }
    }

    protected <T extends FollowDetailVO> void assembleRecordDetail(T vo, FollowRecord record, CluePool cluePool) {
        vo.setId(record.getId());
        vo.setCustomerId(record.getCustomerId());
        vo.setCustomerName(record.getCustomerName());
        vo.setType(record.getType().getValue());
        vo.setBizType(record.getBizType().getValue());
        queryTimes(cluePool.getId(), vo);
        vo.setTaskId(record.getTaskId());
        vo.setDeadline(record.getDeadline());
        vo.setUserId(record.getUserId());
        vo.setDetailId(cluePool.getRefererId());
        vo.setMobile(record.getContacts());
        vo.setVin(cluePool.getFrameNo());
        vo.setRealMobile(record.getContacts());
        vo.setRegion(MobileUtil.attribution(record.getContacts()));

        //默认已经打过电话
        Boolean hadCall = Boolean.TRUE;
        if (Boolean.TRUE.equals(record.getCompelTel())) {
            long count = followRecordLogService.count(Wrappers.<FollowRecordLog>lambdaQuery()
                    .eq(FollowRecordLog::getTaskId, record.getTaskId())
                    .eq(FollowRecordLog::getAttType, AttTypeEnum.SMART_PHONE)
            );
            if (count <= 0) {
                hadCall = Boolean.FALSE;
            }
        }
        //是否已经打过电话
        vo.setHadCall(hadCall);
    }

    protected <T extends FollowDetailVO> void queryTimes(Long clueId, T vo) {
        List<FollowTask> list = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                .eq(FollowTask::getClueId, clueId)
        );
        if (CollectionUtils.isEmpty(list)) {
            vo.setTimes(0);
            return;
        }
        int sum = list.stream().filter(r -> Objects.nonNull(r.getTimes())).mapToInt(FollowTask::getTimes).sum();
        vo.setTimes(sum);
    }

    /**
     * 更新反馈
     *
     * @param taskId
     * @param feedbackTypeEnum
     */
    protected void feedbackTask(Long taskId, FeedbackTypeEnum feedbackTypeEnum) {
        FollowTask task = followTaskService.getById(taskId);
        if (Objects.isNull(task) || Objects.isNull(feedbackTypeEnum)) {
            return;
        }
        String feedback = task.getFeedback();
        Set<String> feedbackSet = StringUtils.isEmpty(feedback) ? new HashSet<>() : new HashSet<>(Arrays.asList(feedback.split(",")));
        feedbackSet.add(String.valueOf(feedbackTypeEnum.getValue()));
        task.setFeedback(String.join(",", feedbackSet));
        task.setLastFeedback(feedbackTypeEnum);
        followTaskService.updateById(task);
    }


    /**
     * 处理重复的线索
     *
     * @param cluePool 当前线索
     * @param strategy
     * @return 是否包含重复的活动
     */
    protected boolean dealRepeatClue(CluePool cluePool, FollowStrategy strategy) {
        //判断是否可以去重
        if (null == cluePool.getCoverFlag() || Boolean.FALSE.equals(cluePool.getCoverFlag())) {
            return false;
        }
        boolean isContainAF = false;
        //查询到重复的正在进行中线索
        //2022-5-30 活动邀约优先级高 不可处理
        List<CluePool> cluePoolList = cluePoolService.list(Wrappers.<CluePool>lambdaQuery()
                .eq(CluePool::getBizType, cluePool.getBizType())
                .eq(CluePool::getOriginalUserId, cluePool.getOriginalUserId())
                .eq(CluePool::getCustomerId, cluePool.getCustomerId())
                .in(CluePool::getClueStatus, ClueStatusEnum.ONGOING)
                .ne(CluePool::getId, cluePool.getId())
        );
        //查询重复的正在进行中任务
        if (!CollectionUtils.isEmpty(cluePoolList)) {
            //获取有时间交集的线索id
            List<Long> clueIds = new ArrayList<>();
            for (CluePool pool : cluePoolList) {
                //判断时间交集
                if (DateUtil.isInterSection(cluePool.getStartTime(), cluePool.getDeadline(), pool.getStartTime(), pool.getDeadline())) {
                    //判断重复的线索 是否是活动
                    if (FollowTypeEnum.AF == pool.getClueType() && FollowTypeEnum.AF != cluePool.getClueType()) {
                        isContainAF = true;
                    } else {
                        clueIds.add(pool.getId());
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(clueIds)) {
                List<FollowTask> taskList = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                        .in(FollowTask::getClueId, clueIds)
                        .in(FollowTask::getState, TaskStateEnum.ONGOING)
                );
                if (null != taskList && !taskList.isEmpty()) {
                    //获取正在进行中的跟进记录
                    List<Long> taskIds = taskList.stream().map(FollowTask::getId).collect(Collectors.toList());
                    List<FollowRecord> followRecordList = followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                            .in(FollowRecord::getTaskId, taskIds)
                            .eq(FollowRecord::getYn, Boolean.TRUE)
                            .eq(FollowRecord::getOutTime, OutTimeEnum.ONGOING)
                    );
                    //调用已有的方法 分别处理
                    if (null != followRecordList && !followRecordList.isEmpty()) {
                        //需求:已经推送的完成  未推送的就逻辑删除
                        List<FollowRecord> updateList = new ArrayList<>();
                        for (FollowRecord record : followRecordList) {
                            if (Boolean.TRUE.equals(record.getAddTodo())) {
                                //已经推送到代办
                                strategy.complete(record, cluePool.getOriginalUserId(), true);
                            } else {
                                //未推送到代办
                                FollowRecord updateObj = new FollowRecord();
                                updateObj.setId(record.getId());
                                updateObj.setYn(false);
                                updateList.add(updateObj);
                            }
                        }
                        if (!updateList.isEmpty()) {
                            //逻辑删除
                            followRecordService.updateBatchById(updateList);
                        }
                    }
                }
            }
        }
        return isContainAF;
    }

    /**
     * 处理重复的跟进记录
     *
     * @param task
     */
    protected void dealRepeatRecord(FollowTask task) {
        List<FollowRecord> followRecordList = followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                .eq(FollowRecord::getTaskId, task.getId())
                .eq(FollowRecord::getType, task.getType())
                .eq(FollowRecord::getUserId, task.getFollowUser())
                .eq(FollowRecord::getCustomerId, task.getCustomerId())
                .eq(FollowRecord::getOutTime, OutTimeEnum.ONGOING)
                .eq(FollowRecord::getAddTodo, Boolean.FALSE)
                .eq(FollowRecord::getYn, Boolean.TRUE)
        );
        if (!CollectionUtils.isEmpty(followRecordList)) {
            followRecordList.forEach(r -> r.setYn(Boolean.FALSE));
            //将重复的跟进记录逻辑删除
            followRecordService.updateBatchById(followRecordList);
        }
    }
}