FollowBizService.java 45.4 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 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
package cn.fw.shirasawa.service.bus.follow;

import cn.fw.common.web.annotation.DisLock;
import cn.fw.common.web.auth.LoginAuthBean;
import cn.fw.shirasawa.common.constant.RoleCode;
import cn.fw.shirasawa.common.utils.DateUtil;
import cn.fw.shirasawa.component.ApproveDefeatFollowProducer;
import cn.fw.shirasawa.domain.db.ApproveRecord;
import cn.fw.shirasawa.domain.db.OriginalData;
import cn.fw.shirasawa.domain.db.SecretReportHistory;
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.follow.SucessFollowRecord;
import cn.fw.shirasawa.domain.db.pool.CluePool;
import cn.fw.shirasawa.domain.dto.CallReportDTO;
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.ClueHistoryVO;
import cn.fw.shirasawa.domain.vo.follow.DateFollowRecordHistoryVO;
import cn.fw.shirasawa.domain.vo.follow.FollowDetailVO;
import cn.fw.shirasawa.domain.vo.follow.FollowRecordHistoryVO;
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.UserRoleDataRangeDTO;
import cn.fw.shirasawa.rpc.flow.FlowApproveRpc;
import cn.fw.shirasawa.rpc.flow.dto.FlowDto;
import cn.fw.shirasawa.rpc.member.MemberRpcService;
import cn.fw.shirasawa.rpc.member.dto.MemberUserDTO;
import cn.fw.shirasawa.rpc.sms.SmsRpcService;
import cn.fw.shirasawa.sdk.enums.BusinessTypeEnum;
import cn.fw.shirasawa.sdk.mq.FollowApproveDTO;
import cn.fw.shirasawa.sdk.param.NewRecordDTO;
import cn.fw.shirasawa.sdk.result.SucessFollowRecordVo;
import cn.fw.shirasawa.service.bus.follow.strategy.FollowStrategy;
import cn.fw.shirasawa.service.data.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

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

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

/**
 * @author : kurisu
 * @className : FollowBizService
 * @description : 跟进业务服务
 * @date: 2020-08-14 17:27
 */
@Slf4j
@Service
public class FollowBizService {
    /**
     * 跟进处理器map
     */
    private final Map<FollowTypeEnum, FollowStrategy> followMap;
    private final FollowRecordService followRecordService;
    private final CluePoolService cluePoolService;
    private final FollowTaskService followTaskService;
    private final StringRedisTemplate redisTemplate;
    private final UserService userService;
    private final SmsRpcService smsRpcService;
    private final EhrRpcService ehrRpcService;
    private final ApproveRecordService approveRecordService;
    private final FlowApproveRpc flowApproveRpc;
    private final FollowRecordLogService followRecordLogService;
    private final SecretReportHistoryService secretReportHistoryService;
    private final MemberRpcService memberRpcService;
    private final ApproveDefeatFollowProducer approveDefeatFollowProducer;

    @Value("${follow.pno}")
    @Getter
    private String preFlowNo;

    @Value("${follow.ano}")
    @Getter
    private String afterFlowNo;

    @Value("${spring.cache.custom.global-prefix}:follow-record")
    @Getter
    private String keyPrefix;

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

    @Autowired
    public FollowBizService(final List<FollowStrategy> followStrategyList,
                            final FollowRecordService followRecordService,
                            final CluePoolService cluePoolService,
                            final FollowTaskService followTaskService,
                            final StringRedisTemplate redisTemplate,
                            final UserService userService,
                            final SmsRpcService smsRpcService,
                            final EhrRpcService ehrRpcService,
                            final ApproveRecordService approveRecordService,
                            final FlowApproveRpc flowApproveRpc,
                            final FollowRecordLogService followRecordLogService,
                            final SecretReportHistoryService secretReportHistoryService,
                            final MemberRpcService memberRpcService,
                            final ApproveDefeatFollowProducer approveDefeatFollowProducer) {
        this.followMap = followStrategyList.stream().collect(Collectors.toMap(FollowStrategy::getFollowType, v -> v));
        this.followRecordService = followRecordService;
        this.cluePoolService = cluePoolService;
        this.followTaskService = followTaskService;
        this.redisTemplate = redisTemplate;
        this.userService = userService;
        this.smsRpcService = smsRpcService;
        this.ehrRpcService = ehrRpcService;
        this.approveRecordService = approveRecordService;
        this.flowApproveRpc = flowApproveRpc;
        this.followRecordLogService = followRecordLogService;
        this.secretReportHistoryService = secretReportHistoryService;
        this.memberRpcService = memberRpcService;
        this.approveDefeatFollowProducer = approveDefeatFollowProducer;
    }

    /**
     * 元数据生成线索
     *
     * @param originalData
     */
    public boolean origin2task(OriginalData originalData) {
        if (Objects.isNull(originalData)) {
            return true;
        }
        FollowTypeEnum type = originalData.getType();
        FollowStrategy strategy = followMap.get(type);
        Assert.notNull(strategy, "strategy cannot be null");
        try {
            if (null == originalData.getFirstDeadline()) {
                log.info("原始数据id:{},没有第一次跟进结束时间,默认跟进结束时间", originalData.getId());
                originalData.setFirstDeadline(originalData.getDeadline());
            }
            return strategy.origin2task(originalData);
        } catch (Exception exception) {
            log.error("处理元数据失败 data: [{}]", originalData, exception);
            return false;
        }
    }

    /**
     * 线索开始事件
     *
     * @param cluePool
     */
    public void startClue(CluePool cluePool) {
        try {
            FollowStrategy strategy = followMap.get(cluePool.getClueType());
            Assert.notNull(strategy, "strategy cannot be null");

            strategy.startClue(cluePool);
        } catch (Exception e) {
            log.error("开始线索失败:clueId[{}]", cluePool.getId(), e);
        }
    }

    /**
     * 结束对应线索的跟进任务
     *
     * @param cluePool
     */
    public void endTask(CluePool cluePool) {
        try {
            FollowStrategy strategy = followMap.get(cluePool.getClueType());
            Assert.notNull(strategy, "strategy cannot be null");

            strategy.endTask(cluePool);
        } catch (Exception e) {
            log.error("结束任务失败:clueId[{}]", cluePool.getId(), e);
            redisTemplate.opsForList().rightPush(getPlanKey(), String.valueOf(cluePool.getId()));
        }
    }

    /**
     * 结束跟进任务
     *
     * @param task
     */
    public void endTask(FollowTask task) {
        try {
            FollowStrategy strategy = followMap.get(task.getType());
            Assert.notNull(strategy, "strategy cannot be null");

            strategy.endTask(task, false);
        } catch (Exception e) {
            log.error("结束任务失败:taskId[{}]", task.getId(), e);
            redisTemplate.opsForList().rightPush(getPlanKey(), String.valueOf(task.getClueId()));
        }
    }


    /**
     * 跟进待办逾期
     *
     * @param record
     */
    public void overdueProcessing(FollowRecord record) {
        if (Objects.isNull(record)) {
            return;
        }
        FollowTypeEnum type = record.getType();
        FollowStrategy strategy = followMap.get(type);
        Assert.notNull(strategy, "strategy cannot be null");
        try {
            strategy.overdue(record);
        } catch (Exception exception) {
            log.error("处理逾期数据失败 data: [{}]", record, exception);
        }
    }

    /**
     * 完成跟进待办
     *
     * @param recordId
     * @param userId
     */
    @DisLock(prefix = "#this.getKeyPrefix()", key = "'complete:' + #recordId", message = "正在完成跟进,请勿重复操作")
    public void completeRecord(Long recordId, Long userId) {
        FollowRecord record = followRecordService.getById(recordId);
        if (Objects.isNull(record) || Boolean.FALSE.equals(record.getYn())) {
            return;
        }
        FollowStrategy strategy = followMap.get(record.getType());
        strategy.complete(record, userId);
    }

    /**
     * 生成新待办
     *
     * @param newRecordDTO
     */
    @DisLock(prefix = "#this.getKeyPrefix()", key = "'create:' + #newRecordDTO.userId + ':' + #newRecordDTO.customerId", message = "请勿重复操作")
    public Boolean createNewRecord(NewRecordDTO newRecordDTO) {
        LocalDate startDate = DateUtil.date2LocalDate(newRecordDTO.getNextDate());
        LocalDate endDate = DateUtil.date2LocalDate(newRecordDTO.getNextDeadline());
        boolean b = !startDate.isBefore(LocalDate.now()) && !endDate.isBefore(startDate);
        BV.isTrue(b, () -> "开始日期必须大于且截止日期不能小于当前日期");

        if (Objects.isNull(newRecordDTO.getPreRecordId())) {
            BV.notNull(newRecordDTO.getCustomerId(), () -> "档案id不能为空");
            BV.notNull(newRecordDTO.getDataType(), () -> "数据类型不能为空");
        }
        return createNextRecord(newRecordDTO);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean createNextRecord(NewRecordDTO newRecordDTO) {
        if (BusinessTypeEnum.AS.getValue().equals(newRecordDTO.getBusinessType())) {
            return afterSaleRecord(newRecordDTO);
        }
        return preSaleRecord(newRecordDTO);
    }

    /**
     * 上传跟进附件
     *
     * @param dto
     */
    @DisLock(prefix = "#this.getKeyPrefix()", key = "'upload:' + #dto.recordId", message = "附件上传中,请勿重复操作")
    public void uploadAtt(FollowAttachmentDTO dto, Long userId) {
        FollowRecord record = followRecordService.getById(dto.getRecordId());
        if (Objects.isNull(record) || !record.getYn()) {
            return;
        }
        FollowStrategy strategy = followMap.get(record.getType());
        strategy.uploadAtt(dto, record, userId);
    }

    /**
     * 完成跟进任务
     *
     * @param taskCompleteDTO
     */
    public void completeTask(FollowTaskCompleteDTO taskCompleteDTO) {
        FollowStrategy strategy = followMap.get(taskCompleteDTO.getFollowType());
        strategy.completeTask(taskCompleteDTO);
    }

    /**
     * 终止跟进
     *
     * @param followTask
     * @param fromFlow
     */
    public void terminationTask(FollowTask followTask, boolean fromFlow) {
        FollowStrategy strategy = followMap.get(followTask.getType());
        strategy.endTask(followTask, fromFlow);
    }


    /**
     * 终止跟进
     *
     * @param terminationDTO
     */
    public void terminationTask(FollowTerminationDTO terminationDTO) {
        FollowStrategy strategy = followMap.get(terminationDTO.getFollowType());
        strategy.terminationTaskPlan(terminationDTO);
    }

    /**
     * 批量终止任务
     *
     * @param list
     */
    public void terminationTaskBatch(List<FollowTerminationDTO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        FollowTypeEnum followType = list.get(0).getFollowType();
        FollowStrategy strategy = followMap.get(followType);
        for (FollowTerminationDTO followTerminationDTO : list) {
            strategy.terminationTaskPlan(followTerminationDTO);
        }
    }

    /**
     * 查询跟进详情
     *
     * @param recordId 跟进待办id
     * @return 跟进详情
     */
    public FollowDetailVO queryFollowDetail(Long recordId) {
        FollowRecord followRecord = followRecordService.getById(recordId);
        BV.notNull(followRecord, () -> "跟进待办不存在");
        BV.isTrue(followRecord.getYn(), () -> "跟进待办不存在");
        FollowTypeEnum type = followRecord.getType();
        FollowStrategy strategy = followMap.get(type);
        return strategy.queryDetail(followRecord);
    }

    /**
     * 查询跟进详情(审批用)
     *
     * @param recordId 跟进待办id
     * @return 跟进详情
     */
    public FollowDetailVO queryApplyFollowDetail(Long recordId) {
        FollowDetailVO vo = queryFollowDetail(recordId);
        ApproveRecord approveRecord = approveRecordService.getOne(Wrappers.<ApproveRecord>lambdaQuery()
                .eq(ApproveRecord::getDataId, vo.getTaskId())
                .eq(ApproveRecord::getUserId, vo.getUserId())
                .eq(ApproveRecord::getType, ApproveTypeEnum.FOLLOW_DEFEAT)
                .last(" limit 1"));
        if (Objects.nonNull(approveRecord)) {
            vo.setReason(approveRecord.getReason());
        }
        return vo;
    }

    /**
     * 查询跟进历史
     *
     * @param recordId 跟进待办id
     * @return 跟进详情
     */
    public List<FollowRecordHistoryVO> todoRecordHistory(Long recordId) {
        BV.notNull(recordId, () -> "跟进记录id不能为空");
        FollowRecord followRecord = followRecordService.getById(recordId);
        BV.notNull(followRecord, () -> "跟进待办不存在");
        BV.isTrue(followRecord.getYn(), () -> "跟进待办不存在");
        FollowTypeEnum type = followRecord.getType();
        FollowStrategy strategy = followMap.get(type);
        return strategy.queryHistoryByRecord(followRecord);
    }

    /**
     * 查询跟进详情
     *
     * @param taskId 跟进任务id
     * @return 跟进详情
     */
    public List<FollowRecordHistoryVO> todoHistoryTask(Long taskId) {
        BV.notNull(taskId, () -> "跟进任务id不能为空");
        FollowTask task = followTaskService.getById(taskId);
        BV.notNull(task, () -> "跟进任务不存在");
        FollowTypeEnum type = task.getType();
        FollowStrategy strategy = followMap.get(type);
        return strategy.queryHistoryByTask(task);
    }

    /**
     * 查询短信模板
     *
     * @param type
     * @return
     */
    public String smsTemplate(Long userId, Integer type) {
        FollowTypeEnum followType = FollowTypeEnum.ofValue(type);
        BV.notNull(followType, () -> "跟进类型不正确");
        StaffInfoDTO staffInfo = ehrRpcService.queryStaffInfo(userId);
        BV.notNull(staffInfo, () -> "员工信息获取失败");
        List<UserRoleDataRangeDTO> range = null;
        if (FollowTypeEnum.AC.equals(followType)) {
            range = userService.getUserRoleDataRange(userId, RoleCode.SGCGJ);
        }
        if (FollowTypeEnum.FM.equals(followType) || FollowTypeEnum.RM.equals(followType)) {
            range = userService.getUserRoleDataRange(userId, RoleCode.FWGW);
        }
        if (FollowTypeEnum.IR.equals(followType)) {
            range = userService.getUserRoleDataRange(userId, RoleCode.XBGJ);
        }
        BV.isNotEmpty(range, () -> "门店信息获取失败");
        Long shopId = range.get(0).getRangeValue();
        String shopName = range.get(0).getRangeName();
        return smsRpcService.getSmsTemplate(shopId, followType) + "\n" + "门店:" + shopName + "专属顾问:" + staffInfo.getName() + ";" + "手机号:" + staffInfo.getMobile() + "; 微信同号。";
    }

    /**
     * 主动战败
     *
     * @param currentUser
     * @param reason
     * @param recordId
     */
    @Transactional(rollbackFor = Exception.class)
    @DisLock(prefix = "#this.getKeyPrefix()", key = "'defeat:' + #recordId", message = "请勿重复提交")
    public void defeat(LoginAuthBean currentUser, Long recordId, String reason) {
        FollowRecord record = followRecordService.getById(recordId);
        BV.notNull(record, () -> "跟进信息不存在");
        BV.isTrue(record.getYn(), () -> "跟进信息不存在");
        String flowNo = getPreFlowNo();
        Long userId = currentUser.getUserId();
        Long shopId = record.getShopId();
        if (BusinessTypeEnum.AS.equals(record.getBizType())) {
            flowNo = getAfterFlowNo();
        }
        boolean repetition = isRepetition(record.getTaskId().toString());
        BV.isFalse(repetition, () -> "正在审批处理中,请勿重复申请");

        FlowDto flowDto = FlowDto.create(currentUser.getGroupId(), flowNo, userId, shopId);
        HashMap<String, Object> param = new HashMap<>(2);
        param.put("recordId", recordId.toString());
        param.put("type", record.getType().getValue().toString());
        flowDto.setExtData(param);
        List<String> list = new ArrayList<>();
        list.add("申请人: " + currentUser.getUserName());
        if (BusinessTypeEnum.AS.equals(record.getBizType())) {
            list.add("客户: " + (StringUtils.isBlank(record.getCustomerName()) ? "-" : record.getCustomerName()));
            list.add("车辆: " + record.getPlateNo());
        }
        list.add("跟进类型: " + record.getType().getName());
        list.add("战败原因: " + reason);
        flowDto.setBriefContent(list);
        String orderNo = flowApproveRpc.initiate(flowDto);
        ApproveRecord approveRecord = new ApproveRecord();
        approveRecord.setDataId(record.getTaskId());
        approveRecord.setUserId(userId);
        approveRecord.setOrderNo(orderNo);
        approveRecord.setReason(reason);
        approveRecord.setState(ApproveStateEnum.WAIT);
        approveRecord.setType(ApproveTypeEnum.FOLLOW_DEFEAT);
        approveRecord.setPassed(Boolean.FALSE);
        approveRecordService.save(approveRecord);
    }

    /**
     * 审批战败同意
     *
     * @param taskId
     */
    @Transactional(rollbackFor = Exception.class)
    public void onApproveAgree(Long taskId) {
        FollowTask task = followTaskService.getById(taskId);
        if (Objects.isNull(task) || !TaskStateEnum.ONGOING.equals(task.getState())) {
            return;
        }
        if (BusinessTypeEnum.AS.equals(task.getBizType())) {
            FollowApproveDTO approveDTO = new FollowApproveDTO();
            approveDTO.setVin(task.getBizId());
            approveDTO.setPlateNo(task.getPlateNo());
            approveDTO.setType(task.getType().getValue());
            approveDefeatFollowProducer.send(approveDTO);
        }
        task.setCloseTime(LocalDateTime.now());
        task.setReason(TaskDefeatTypeEnum.A);
        this.terminationTask(task, true);
    }


    public List<ClueHistoryVO> clueHistoryList(final Long groupId, final Long customerId, Integer bizType) {
        List<ClueHistoryVO> historyVOList = new ArrayList<>();
        BusinessTypeEnum businessTypeEnum = BusinessTypeEnum.ofValue(bizType);
        List<CluePool> list = cluePoolService.list(Wrappers.<CluePool>lambdaQuery()
                .eq(CluePool::getCustomerId, customerId)
                .eq(CluePool::getGroupId, groupId)
                .ne(CluePool::getClueType, FollowTypeEnum.AC)
                .ne(CluePool::getClueStatus, ClueStatusEnum.WAITING)
                .eq(Objects.nonNull(businessTypeEnum), CluePool::getBizType, businessTypeEnum));
        if (!CollectionUtils.isEmpty(list)) {
            historyVOList.addAll(list.stream().map(ClueHistoryVO::with).filter(Objects::nonNull).collect(Collectors.toList()));
        }

        Map<Long, Long> taskIdCount = null;
        Map<Long, Long> clueIdTaskIdMap = null;
        if (!historyVOList.isEmpty()) {
            List<Long> clueIds = historyVOList.stream().map(ClueHistoryVO::getId).collect(Collectors.toList());
            List<FollowTask> taskList = followTaskService.list(Wrappers.<FollowTask>lambdaQuery().in(FollowTask::getClueId, clueIds));
            if (null != taskList && !taskList.isEmpty()) {
                List<Long> tashkIds = taskList.stream().map(FollowTask::getId).collect(Collectors.toList());
                List<FollowRecord> followRecordList = followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                        .in(FollowRecord::getTaskId, tashkIds)
                        .eq(FollowRecord::getOutTime, OutTimeEnum.BE_COMPLETE));
                if (null != followRecordList && !followRecordList.isEmpty()) {
                    //获取任务下面的跟进记录次数
                    taskIdCount = followRecordList.stream().collect(Collectors.groupingBy(FollowRecord::getTaskId, Collectors.counting()));
                    //获取线索与任务的id关系
                    clueIdTaskIdMap = taskList.stream().collect(Collectors.toMap(FollowTask::getClueId, FollowTask::getId));
                }
            }
        }

        //遍历返回对象赋值
        for (ClueHistoryVO clueHistoryVO : historyVOList) {
            if (null != clueIdTaskIdMap && null != taskIdCount) {
                ////2022-06-08 获取跟进次数
                if (clueIdTaskIdMap.containsKey(clueHistoryVO.getId())) {
                    Long taskId = clueIdTaskIdMap.get(clueHistoryVO.getId());
                    if (taskIdCount.containsKey(taskId)) {
                        clueHistoryVO.setFollowRecordTimes(taskIdCount.get(taskId).intValue());
                    }
                }
            }
            //对活动名称赋值
            String activeName = null;
            if (null != clueHistoryVO.getActivityName()) {
                JSONObject noteJson = JSON.parseObject(clueHistoryVO.getActivityName());
                if (null != noteJson && noteJson.containsKey("activityName")) {
                    activeName = noteJson.getString("activityName");
                }
            }
            if ((null == activeName || "".equals(activeName)) && null != clueHistoryVO.getType()) {
                activeName = FollowTypeEnum.getNameByVale(clueHistoryVO.getType());
            }
            clueHistoryVO.setActivityName(activeName);
        }
        historyVOList.sort(Comparator.comparing(ClueHistoryVO::getDeadline));
        return historyVOList;
    }

    public List<ClueHistoryVO> asClueHistoryList(final Long groupId, final String vin) {
        List<ClueHistoryVO> historyVOList = new ArrayList<>();
        List<CluePool> list = cluePoolService.list(Wrappers.<CluePool>lambdaQuery()
                .eq(CluePool::getFrameNo, vin)
                .eq(CluePool::getGroupId, groupId)
                .ne(CluePool::getClueStatus, ClueStatusEnum.WAITING)
                .eq(CluePool::getBizType, BusinessTypeEnum.AS));
        if (!CollectionUtils.isEmpty(list)) {
            historyVOList.addAll(list.stream().map(ClueHistoryVO::with).filter(Objects::nonNull).collect(Collectors.toList()));
        }

        Map<Long, Long> taskIdCount = null;
        Map<Long, Long> clueIdTaskIdMap = null;
        if (!historyVOList.isEmpty()) {
            List<Long> clueIds = historyVOList.stream().map(ClueHistoryVO::getId).collect(Collectors.toList());
            List<FollowTask> taskList = followTaskService.list(Wrappers.<FollowTask>lambdaQuery().in(FollowTask::getClueId, clueIds));
            if (null != taskList && !taskList.isEmpty()) {
                List<Long> tashkIds = taskList.stream().map(FollowTask::getId).collect(Collectors.toList());
                List<FollowRecord> followRecordList = followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                        .in(FollowRecord::getTaskId, tashkIds)
                        .eq(FollowRecord::getOutTime, OutTimeEnum.BE_COMPLETE));
                if (null != followRecordList && !followRecordList.isEmpty()) {
                    //获取任务下面的跟进记录次数
                    taskIdCount = followRecordList.stream().collect(Collectors.groupingBy(FollowRecord::getTaskId, Collectors.counting()));
                    //获取线索与任务的id关系
                    clueIdTaskIdMap = taskList.stream().collect(Collectors.toMap(FollowTask::getClueId, FollowTask::getId));
                }
            }
        }

        //遍历返回对象赋值
        for (ClueHistoryVO clueHistoryVO : historyVOList) {
            if (null != clueIdTaskIdMap && null != taskIdCount) {
                ////2022-06-08 获取跟进次数
                if (clueIdTaskIdMap.containsKey(clueHistoryVO.getId())) {
                    Long taskId = clueIdTaskIdMap.get(clueHistoryVO.getId());
                    if (taskIdCount.containsKey(taskId)) {
                        clueHistoryVO.setFollowRecordTimes(taskIdCount.get(taskId).intValue());
                    }
                }
            }
            //对活动名称赋值
            String activeName = null;
            if (null != clueHistoryVO.getActivityName()) {
                JSONObject noteJson = JSON.parseObject(clueHistoryVO.getActivityName());
                if (null != noteJson && noteJson.containsKey("activityName")) {
                    activeName = noteJson.getString("activityName");
                }
            }
            if ((null == activeName || "".equals(activeName)) && null != clueHistoryVO.getType()) {
                activeName = FollowTypeEnum.getNameByVale(clueHistoryVO.getType());
            }
            clueHistoryVO.setActivityName(activeName);
        }
        historyVOList.sort(Comparator.comparing(ClueHistoryVO::getDeadline));
        return historyVOList;
    }

    /**
     * 根据线索id查询跟进记录
     *
     * @param clueId
     * @return
     */
    public List<FollowRecordHistoryVO> queryHistoryByClueId(Long clueId) {
        CluePool cluePool = cluePoolService.getById(clueId);
        BV.notNull(cluePool, () -> "跟进线索不存在");

        FollowStrategy strategy = followMap.get(cluePool.getClueType());
        BV.notNull(strategy, () -> "跟进类型不正确");

        return strategy.getRecordListByClue(cluePool);
    }

    /**
     * 查询跟进池详情
     *
     * @param taskId
     * @return
     */
    public FollowDetailVO followPoolDetail(Long taskId) {
        FollowTask task = followTaskService.getById(taskId);
        BV.notNull(task, () -> "跟进线索不存在,请刷新列表");
        FollowStrategy strategy = followMap.get(task.getType());
        Assert.notNull(strategy, "strategy cannot be null");
        return strategy.followPoolDetail(task);
    }

    /**
     * 根据referId查询跟进任务
     *
     * @param refererId
     * @param groupId
     * @param type
     * @return
     */
    public Long queryTaskByReferId(String refererId, Long groupId, Integer type) {
        FollowTypeEnum typeEnum = FollowTypeEnum.ofValue(type);
        CluePool cluePool = cluePoolService.queryByRefererId(refererId, groupId, typeEnum);
        BV.notNull(cluePool, () -> "数据异常,请刷新页面");
        FollowTask task = followTaskService.getOne(Wrappers.<FollowTask>lambdaQuery()
                .eq(FollowTask::getClueId, cluePool.getId())
                .orderByDesc(FollowTask::getId)
                .last(" limit 1 ")
        );
        BV.notNull(task, () -> "数据异常,请刷新页面");
        return task.getId();
    }

    /**
     * 通过智能电话拨号
     *
     * @param recordId
     * @return
     */
    @DisLock(prefix = "#this.getKeyPrefix()", key = "'call:' + #recordId", message = "请勿重复尝试")
    public String callSomeone(Long recordId) {
        final FollowRecord record = followRecordService.getById(recordId);
        BV.notNull(record, () -> "跟进信息不存在");
        BV.isTrue(record.getYn(), () -> "跟进信息不存在");
        FollowStrategy strategy = followMap.get(record.getType());
        Assert.notNull(strategy, "strategy cannot be null");
        String contacts = record.getContacts();
        if (StringUtils.isEmpty(contacts)) {
            MemberUserDTO memberUserDTO = memberRpcService.user(record.getMemberId());
            BV.notNull(memberUserDTO, () -> "档案信息异常,请稍后再试");
            contacts = memberUserDTO.getPhone();
            record.setContacts(memberUserDTO.getPhone());
            CompletableFuture.runAsync(() -> followRecordService.updateById(record));
        }
        return contacts;
    }

    /**
     * 售前下次跟进处理
     *
     * @param newRecordDTO
     * @return
     */
    private Boolean preSaleRecord(NewRecordDTO newRecordDTO) {
        FollowTask task;
        if (Objects.nonNull(newRecordDTO.getPreRecordId())) {
            FollowRecord preRecord = followRecordService.getById(newRecordDTO.getPreRecordId());
            BV.notNull(preRecord, () -> "跟进记录不存在");
            return createRecord(newRecordDTO, preRecord);
        } else {
            CluePool cluePool = cluePoolService.getOne(Wrappers.<CluePool>lambdaQuery()
                    .eq(CluePool::getRefererId, newRecordDTO.getCustomerId())
                    .eq(CluePool::getClueType, FollowTypeEnum.ofValue(newRecordDTO.getDataType().getValue()))
                    .eq(CluePool::getClueStatus, ClueStatusEnum.ONGOING)
                    .eq(CluePool::getBizType, BusinessTypeEnum.PS)
                    .eq(CluePool::getOriginalUserId, newRecordDTO.getUserId())
                    .orderByDesc(CluePool::getCreateTime)
                    .last(" limit 1"));
            if (Objects.isNull(cluePool)) {
                log.error("跟进线索不存在");
                return Boolean.FALSE;
            }
            task = followTaskService.queryOngoingTaskByClueId(cluePool.getId());
        }
        if (Objects.isNull(task)) {
            log.error("跟进任务不存在");
            return Boolean.FALSE;
        }
        FollowStrategy strategy = followMap.get(task.getType());
        String json = JSONObject.toJSONString(newRecordDTO.getNoteMap());
        strategy.createNewRecord(task, DateUtil.date2LocalDateTime(newRecordDTO.getNextDate()), DateUtil.date2LocalDateTime(newRecordDTO.getNextDeadline()), json);
        return Boolean.TRUE;
    }

    /**
     * 售后下次跟进处理
     *
     * @param newRecordDTO
     * @return
     */
    private Boolean afterSaleRecord(NewRecordDTO newRecordDTO) {
        FollowRecord preRecord = followRecordService.getById(newRecordDTO.getPreRecordId());
        BV.notNull(preRecord, () -> "跟进记录不存在");
        return createRecord(newRecordDTO, preRecord);
    }

    /**
     * 处理通话记录
     *
     * @param dto
     */
    public void readCallReport(CallReportDTO dto) {
        final Long talkTime = dto.getTalkTime();
        if (Objects.isNull(talkTime) || talkTime <= 0) {
            return;
        }

        uploadAttBySmartPhone(dto);

        if (Objects.isNull(dto.getMemberId()) || dto.getMemberId() < 0) {
            MemberUserDTO memberInfo = memberRpcService.queryByMobile(dto.getPeerNo());
            if (Objects.nonNull(memberInfo)) {
                List<FollowTask> taskList = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                        .eq(FollowTask::getFollowUser, dto.getStaffId())
                        .eq(FollowTask::getMemberId, memberInfo.getUserId())
                        .eq(FollowTask::getGroupId, dto.getGroupId())
                        .eq(FollowTask::getState, TaskStateEnum.ONGOING));

                if (CollectionUtils.isEmpty(taskList)) {
                    return;
                }
                for (FollowTask task : taskList) {
                    uploadAttBySmartPhone(dto, task);
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void uploadAttBySmartPhone(CallReportDTO reportDTO, FollowTask task) {
        FollowTypeEnum followType = task.getType();
        List<FollowRecord> list = followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                .eq(FollowRecord::getTaskId, task.getId())
                .eq(FollowRecord::getUserId, task.getFollowUser())
                .eq(FollowRecord::getType, followType)
                .eq(FollowRecord::getAddTodo, Boolean.TRUE)
                .eq(FollowRecord::getSecondary, Boolean.FALSE)
                .eq(FollowRecord::getOutTime, OutTimeEnum.ONGOING)
                .eq(FollowRecord::getYn, Boolean.TRUE)
                .isNull(FollowRecord::getFollowTime));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        FollowStrategy strategy = followMap.get(followType);

        List<SecretReportHistory> reportHistoryList = new ArrayList<>();
        for (FollowRecord record : list) {
            FollowAttachmentDTO dto = new FollowAttachmentDTO();
            dto.setTaskId(record.getTaskId());
            dto.setRecordId(record.getId());
            dto.setAttType(AttTypeEnum.SMART_PHONE.getValue());
            dto.setAttachments(reportDTO.getCallId());

            reportHistoryList.add(createReportHistory(reportDTO, record));
            strategy.uploadAtt(dto, record, record.getUserId());
        }
        secretReportHistoryService.saveBatch(reportHistoryList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void uploadAttBySmartPhone(CallReportDTO reportDTO) {
        List<FollowRecord> list = followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                .eq(FollowRecord::getUserId, reportDTO.getStaffId())
                .eq(FollowRecord::getAddTodo, Boolean.TRUE)
                .eq(FollowRecord::getOutTime, OutTimeEnum.ONGOING)
                .eq(FollowRecord::getYn, Boolean.TRUE)
                .eq(FollowRecord::getContacts, reportDTO.getPeerNo())
                .isNull(FollowRecord::getFollowTime));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<SecretReportHistory> reportHistoryList = new ArrayList<>();
        for (FollowRecord record : list) {
            FollowAttachmentDTO dto = new FollowAttachmentDTO();
            FollowStrategy strategy = followMap.get(record.getType());
            dto.setTaskId(record.getTaskId());
            dto.setRecordId(record.getId());
            dto.setFeedbackType(FollowTypeEnum.AC.equals(record.getType()) ? FeedbackTypeEnum.OTHER.getValue() : null);
            dto.setAttType(AttTypeEnum.SMART_PHONE.getValue());
            dto.setAttachments(reportDTO.getCallId());

            reportHistoryList.add(createReportHistory(reportDTO, record));
            strategy.uploadAtt(dto, record, record.getUserId());
        }
        secretReportHistoryService.saveBatch(reportHistoryList);
    }


    /**
     * 审批防重
     *
     * @param taskId
     * @return
     */
    private boolean isRepetition(String taskId) {
        return approveRecordService.count(Wrappers.<ApproveRecord>lambdaQuery()
                .eq(ApproveRecord::getDataId, taskId)
                .eq(ApproveRecord::getType, ApproveTypeEnum.FOLLOW_DEFEAT)
                .eq(ApproveRecord::getState, ApproveStateEnum.WAIT)) > 0;
    }

    private SecretReportHistory createReportHistory(CallReportDTO reportDTO, FollowRecord record) {
        SecretReportHistory history = new SecretReportHistory();
        history.setTaskId(record.getTaskId());
        history.setTaskType(record.getType());
        history.setFollowRecordId(record.getId());
        history.setCallId(reportDTO.getCallId());
        history.setStaffId(reportDTO.getStaffId());
        history.setStaffName(reportDTO.getStaffName());
        history.setStaffMobile(reportDTO.getStaffMobile());
        history.setCustomerId(record.getCustomerId());
        history.setCustomerName(reportDTO.getMemberName());
        history.setCustomerMobile(reportDTO.getPeerNo());
        history.setCallType(reportDTO.getDialType());
        history.setCallTime(reportDTO.getCallTime());
        history.setCallDuration(reportDTO.getTalkTime());
        history.setShopId(record.getShopId());
        history.setGroupId(record.getGroupId());

        long count = followRecordLogService.count(Wrappers.<FollowRecordLog>lambdaQuery()
                .eq(FollowRecordLog::getTaskId, record.getTaskId())
                .eq(FollowRecordLog::getAttType, AttTypeEnum.SMART_PHONE));
        history.setFirstCall(count <= 0);
        return history;
    }

    /**
     * 根据业务类型 档案id获取已完成的记录
     *
     * @param bizType
     * @param customerIdList
     * @return
     */
    public List<SucessFollowRecordVo> getCompletedFollowRecord(Integer bizType, List<Long> customerIdList) {
        List<SucessFollowRecord> list = followRecordService.getCompletedFollowRecord(bizType, customerIdList);
        if (null != list && !list.isEmpty()) {
            List<SucessFollowRecordVo> returnList = new ArrayList<>();

            for (SucessFollowRecord sucessFollowRecord : list) {
                SucessFollowRecordVo sucessFollowRecordVo = new SucessFollowRecordVo();
                BeanUtils.copyProperties(sucessFollowRecord, sucessFollowRecordVo);
                String activeName = null;
                if (StringUtils.isNotBlank(sucessFollowRecord.getNote())) {
                    JSONObject noteJson = JSON.parseObject(sucessFollowRecord.getNote());
                    if (null != noteJson && noteJson.containsKey("activityName")) {
                        activeName = noteJson.getString("activityName");
                    }
                }
                String followTypeName = FollowTypeEnum.getNameByVale(Integer.parseInt(sucessFollowRecord.getFollowType()));
                if (StringUtils.isBlank(activeName)) {
                    followTypeName += "跟进";
                } else {
                    followTypeName += "-" + activeName;
                }
                sucessFollowRecordVo.setFollowTypeName(followTypeName);
                returnList.add(sucessFollowRecordVo);
            }
            return returnList;
        }
        return null;
    }

    /**
     * 查询跟进记录池详情
     *
     * @param id
     * @return
     */
    public List<FollowRecordHistoryVO> recordPoolDetail(Long id) {
        FollowRecord record = followRecordService.getById(id);
        BV.notNull(record, () -> "跟进待办不存在");
        List<FollowRecordLog> attachments = followRecordLogService.getListByRecordIds(Collections.singletonList(id));
        if (CollectionUtils.isEmpty(attachments)) {
            return new ArrayList<>();
        }
        MemberUserDTO user = memberRpcService.user(record.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(record.getType());
            vo.setUploadTime(attachment.getUploadTime());
            vo.setDescribes(attachment.getDescribes());
            vo.setUserName(record.getUserName());
            list.add(vo);
        }

        return list;
    }

    /**
     * 根据跟进记录id获取详情及附件信息
     *
     * @param recordId
     * @return
     */
    public List<DateFollowRecordHistoryVO> followRecordDetail(Long recordId) {
        FollowRecord record = followRecordService.getById(recordId);
        if (Objects.isNull(record) || Boolean.FALSE.equals(record.getYn())) {
            return null;
        }
        //查询附件
        List<Long> recordIdList = new ArrayList<>();
        recordIdList.add(recordId);
        List<FollowRecordLog> followRecordLogs = followRecordLogService.getListByRecordIds(recordIdList);
        if (null != followRecordLogs && !followRecordLogs.isEmpty()) {
            //按日期分组
            List<DateFollowRecordHistoryVO> dateGroupList = new ArrayList<>();
            Map<String, DateFollowRecordHistoryVO> tmpMap = new HashMap<>();

            for (FollowRecordLog attachment : followRecordLogs) {
                FollowRecordHistoryVO vo = new FollowRecordHistoryVO();
                vo.setAttachments(attachment.getAttachments());
                vo.setId(attachment.getId());
                vo.setRecordId(attachment.getRecordId());
                vo.setTaskId(record.getTaskId());
                vo.setAttType(attachment.getAttType());
                vo.setFeedbackType(attachment.getFeedbackType());
                vo.setFollowType(record.getType());
                vo.setUploadTime(attachment.getUploadTime());
                vo.setDescribes(attachment.getDescribes());
                vo.setUserName(record.getUserName());
                //获取年月日
                String ymd = DateUtil.getFormatString(DateUtil.toDate(attachment.getUploadTime()), "yyyy-MM-dd");
                DateFollowRecordHistoryVO curFollowRecord = null;
                if (tmpMap.containsKey(ymd)) {
                    curFollowRecord = tmpMap.get(ymd);
                } else {
                    curFollowRecord = new DateFollowRecordHistoryVO();
                    curFollowRecord.setYmd(attachment.getUploadTime().toLocalDate());
                    curFollowRecord.setFollowRecordLogList(new ArrayList<>());
                    dateGroupList.add(curFollowRecord);
                    tmpMap.put(ymd, curFollowRecord);
                }
                curFollowRecord.getFollowRecordLogList().add(vo);
            }
            return dateGroupList;
        }
        return new ArrayList<>();
    }

    /**
     * 查询未完成的待办数量
     *
     * @param userId
     * @param bizType
     * @return
     */
    public long queryOngoingRecord(Long userId, BusinessTypeEnum bizType) {
        return followRecordService.recordRemaining(userId, bizType, null);
    }

    /**
     * 创建新跟进
     *
     * @param newRecordDTO
     * @param preRecord
     * @return
     */
    public boolean createRecord(NewRecordDTO newRecordDTO, FollowRecord preRecord) {
        FollowRecord record = new FollowRecord();
        record.setTaskId(preRecord.getTaskId());
        record.setCustomerId(preRecord.getCustomerId());
        record.setCustomerName(preRecord.getCustomerName());
        if (Objects.nonNull(newRecordDTO.getCustomerId()) && !preRecord.getCustomerId().equals(newRecordDTO.getCustomerId())) {
            record.setCustomerId(newRecordDTO.getCustomerId());
            record.setCustomerName(newRecordDTO.getCustomerName());
        }
        Integer businessType = Optional.ofNullable(newRecordDTO.getBusinessType()).orElse(1);
        record.setBizType(BusinessTypeEnum.ofValue(businessType));
        record.setType(preRecord.getType());

        record.setPlateNo(preRecord.getPlateNo());
        record.setContacts(preRecord.getContacts());
        if (StringUtils.isNotBlank(newRecordDTO.getContacts())) {
            record.setContacts(newRecordDTO.getContacts());
        }
        if (StringUtils.isNotBlank(newRecordDTO.getPlateNo())) {
            record.setPlateNo(newRecordDTO.getPlateNo());
        }
        record.setUserId(newRecordDTO.getUserId());
        if (newRecordDTO.getUserId().equals(preRecord.getUserId())) {
            record.setUserName(preRecord.getUserName());
        } else {
            StaffInfoDTO staffInfo = ehrRpcService.queryStaffInfo(newRecordDTO.getUserId());
            BV.notNull(staffInfo, () -> "用户信息不存在");
            record.setUserName(staffInfo.getName());
        }
        record.setSecondary(Boolean.TRUE.equals(newRecordDTO.getSecondary()));
        record.setPlanTime(DateUtil.date2LocalDateTime(newRecordDTO.getNextDate()));
        record.setDeadline(DateUtil.date2LocalDateTime(newRecordDTO.getNextDeadline()));
        record.setShopId(preRecord.getShopId());
        record.setMemberId(preRecord.getMemberId());
        record.setGroupId(preRecord.getGroupId());
        record.setAddTodo(Boolean.FALSE);
        record.setOutTime(OutTimeEnum.ONGOING);
        record.setTodoCode(preRecord.getTodoCode());
        record.setBizId(preRecord.getBizId());
        record.setNote(CollectionUtils.isEmpty(newRecordDTO.getNoteMap()) ? preRecord.getNote() : JSONObject.toJSONString(newRecordDTO.getNoteMap()));

        if (BusinessTypeEnum.AS.getValue().equals(newRecordDTO.getBusinessType())) {
            record.setCompelTel(Boolean.TRUE);
            boolean compelTel = Boolean.TRUE.equals(preRecord.getCompelTel());
            if (compelTel) {
                boolean hadcall = followRecordLogService.count(Wrappers.<FollowRecordLog>lambdaQuery()
                        .eq(FollowRecordLog::getRecordId, preRecord.getId())
                        .eq(FollowRecordLog::getAttType, AttTypeEnum.SMART_PHONE)
                ) > 0;
                record.setCompelTel(!hadcall);
            }
        }

        if (FollowTypeEnum.CF == preRecord.getType() || FollowTypeEnum.PF == preRecord.getType()) {
            if (followRecordService.checkCompelCall(preRecord.getTaskId(), record.getUserId(), 2)) {
                record.setCompelTel(Boolean.TRUE);
            }
        }

        return followRecordService.save(record);
    }
}