package com.storlead.sales.service.impl.customer;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.mail.pojo.vo.UserClickTitleVO;
import com.storlead.message.enums.MessageTypeEnum;
import com.storlead.sales.pojo.dto.customer.CustomerFollowUpAddDTO;
import com.storlead.sales.pojo.dto.customer.CustomerFollowUpSearchDTO;
import com.storlead.sales.pojo.dto.customer.CustomerSearchSearchDTO;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.vo.customer.*;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.pojo.dto.task.UpdateTaskDTO;
import com.storlead.sales.pojo.entity.task.TaskEntity;
import com.storlead.sales.mapper.customer.CustomerFollowUpMapper;
import com.storlead.sales.service.customer.*;
import com.storlead.mail.pojo.entity.EmailsEntity;
import com.storlead.mail.service.EmailsService;
import com.storlead.sales.pojo.entity.mail.CustomerMailBingMarkEntity;
import com.storlead.sales.service.CustomerMailBingMarkService;
import com.storlead.sales.service.systemrule.SystemRuleModuleConfigService;
import com.storlead.sales.service.task.TaskService;
import com.storlead.system.pojo.entity.SysDictDetailEntity;
import com.storlead.system.pojo.entity.SysDictEntity;
import com.storlead.system.service.SysDictDetailService;
import com.storlead.system.service.SysDictService;
import com.storlead.user.pojo.entity.JobEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IJobService;
import com.storlead.user.service.IUserService;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

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

/**
 * <p>
 * 客户跟进记录表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-04-19
 */
@Service
public class CustomerFollowUpServiceImpl extends MyBaseServiceImpl<CustomerFollowUpMapper, CustomerFollowUpEntity> implements CustomerFollowUpService {

    @Resource
    private IUserService userService;
    @Resource
    private CustomerService customerService;
    @Resource
    private TaskService taskService;
    @Resource
    private BusinessService businessService;
    @Resource
    private SysResourceService sysResourceService;
    @Resource
    private RecordCommentService recordCommentService;
    @Resource
    private LiaisonService liaisonService;
    @Resource
    private EmailsService emailsService;

    @Resource
    private OrderFormService orderFormService;

    @Resource
    private CustomerFollowUpService customerFollowUpService;

    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private SysDictService sysDictService;

    @Resource
    private SysDictDetailService sysDictDetailService;

    @Resource
    private MessageAssembleService assembleService;

    @Resource
    private CustomerMailBingMarkService customerMailBingMarkService;
    @Resource
    private SystemRuleModuleConfigService systemRuleModuleConfigService;
    @Resource
    private IJobService jobService;


    @Override
    public Result<?> addCustomerFollowUp(CustomerFollowUpAddDTO customerFollowUpAddDTO) {
        if (ObjectUtils.isEmpty(customerFollowUpAddDTO)){
            return Result.error("参数不能为空");
        }
        if(!ObjectUtils.isEmpty(customerFollowUpAddDTO.getMailId())){

            if (ObjectUtils.isEmpty(customerFollowUpAddDTO.getId()) && !ObjectUtils.isEmpty(customerFollowUpAddDTO.getCustomerId())){
                LambdaQueryWrapper<CustomerFollowUpEntity> mailWrapper = new LambdaQueryWrapper<>();
                mailWrapper.eq(CustomerFollowUpEntity::getMailId, customerFollowUpAddDTO.getMailId());
                mailWrapper.eq(CustomerFollowUpEntity::getCustomerId, customerFollowUpAddDTO.getCustomerId());
                mailWrapper.eq(CustomerFollowUpEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                Integer mailCount = count(mailWrapper);
                if (mailCount > 0){
                    return Result.error("该邮件已跟进");
                }
            }
        }

        CustomerFollowUpEntity customerFollowUp = new CustomerFollowUpEntity();
        BeanUtils.copyProperties(customerFollowUpAddDTO, customerFollowUp);
        customerFollowUp.setOwnerBy(customerFollowUp.getFollowUpMemberId());
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        if (ObjectUtils.isEmpty(customerFollowUpAddDTO.getFollowUpMemberId())) {
            customerFollowUp.setFollowUpMemberId(loginUser.getId());
        }
        if (!ObjectUtils.isEmpty(customerFollowUpAddDTO.getLiaisonIdList())){
            customerFollowUp.setLiaisonIds(customerFollowUpAddDTO.getLiaisonIdList().stream().map(String::valueOf).collect(Collectors.joining(",")));
        }

        boolean isOk = saveOrUpdate(customerFollowUp);
        if (isOk){
            LocalDateTime currentTime =  LocalDateTime.now();
//            if (Objects.nonNull(customerFollowUp.getMailId()) && Objects.nonNull(customerFollowUp.getCustomerId())) {
//                LambdaQueryWrapper<CustomerMailBingMarkEntity> mailBindWrapper = new LambdaQueryWrapper<>();
//                mailBindWrapper.eq(CustomerMailBingMarkEntity::getMailId, customerFollowUp.getMailId());
//                mailBindWrapper.eq(CustomerMailBingMarkEntity::getCustomerId, customerFollowUp.getCustomerId());
//                mailBindWrapper.last("limit 1");
//                CustomerMailBingMarkEntity customerMailBing = customerMailBingMarkService.getOne(mailBindWrapper);
//                if (Objects.nonNull(customerMailBing)) {
//                    LambdaUpdateWrapper<CustomerMailBingMarkEntity> updateCustomerMailBing = new LambdaUpdateWrapper();
//                    updateCustomerMailBing.in(CustomerMailBingMarkEntity::getId, customerFollowUpAddDTO.getLiaisonIdList());
//                    updateCustomerMailBing.set(CustomerMailBingMarkEntity::getFollowUpTime,currentTime);
//                    updateCustomerMailBing.set(CustomerMailBingMarkEntity::getFollowUpId,customerFollowUp.getId());
//                    customerMailBingMarkService.update(updateCustomerMailBing);
//                }
//            }
            //修改附件绑定的业务类型及业务id
//            sysResourceService.updateResource(ResourceTypeEnum.FOLLOW_UP.code,customerFollowUp.getId(),customerFollowUpAddDTO.getResourceList());
            //添加业务逻辑，根据跟进记录中的客户状态、线索状态、商机阶段修改对应的业务逻辑
            CustomerEntity customerEntity = new CustomerEntity();
            if (customerFollowUpAddDTO.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code)){
                customerEntity.setCustomerStatusDictValue(customerFollowUpAddDTO.getResourceStageDictValue());
            }else if (customerFollowUpAddDTO.getResourceType().equals(ResourceTypeEnum.CLUS.code)){
                customerEntity.setClueStatusDictValue(customerFollowUpAddDTO.getResourceStageDictValue());
                //添加线索首要联系人到跟进联系人
                LambdaQueryWrapper<LiaisonEntity> clusLiaisonWrapper = new LambdaQueryWrapper<>();
                clusLiaisonWrapper.eq(LiaisonEntity::getCustomerId,customerFollowUpAddDTO.getResourceTypeId());
                clusLiaisonWrapper.eq(LiaisonEntity::getHasPrimaryLialison,true);
                clusLiaisonWrapper.last("limit 1");
                LiaisonEntity clusLiaison = liaisonService.getOne(clusLiaisonWrapper);
                if (!ObjectUtils.isEmpty(clusLiaison)){
                    customerFollowUp.setLiaisonIds(clusLiaison.getId().toString());
                    updateById(customerFollowUp);
                }
            }else if (customerFollowUpAddDTO.getResourceType().equals(ResourceTypeEnum.BUSINESS.code)){
                //修改商机状态
                BusinessEntity business = new BusinessEntity();
                business.setId(customerFollowUpAddDTO.getResourceTypeId());
                business.setSalesPhaseDictValue(customerFollowUpAddDTO.getResourceStageDictValue());
                businessService.updateById(business);
            }else if (customerFollowUpAddDTO.getResourceType().equals(ResourceTypeEnum.LIAISON.code)){
                customerEntity.setCustomerStatusDictValue(customerFollowUpAddDTO.getResourceStageDictValue());
                //修改联系人最后跟进时间
                LiaisonEntity liaisonEntity = liaisonService.getById(customerFollowUpAddDTO.getResourceTypeId());
                if (!ObjectUtils.isEmpty(liaisonEntity)){
                    liaisonEntity.setLastFollowUpTime(currentTime);
                    liaisonService.updateById(liaisonEntity);
                }
            }
            /**
             * 如果有选择联系人，则修改最后跟进时间
             */
            if (!CollectionUtils.isEmpty(customerFollowUpAddDTO.getLiaisonIdList())) {
                LambdaUpdateWrapper<LiaisonEntity> updateLiaisonWrapper = new LambdaUpdateWrapper();
                updateLiaisonWrapper.in(LiaisonEntity::getId, customerFollowUpAddDTO.getLiaisonIdList());
                updateLiaisonWrapper.set(LiaisonEntity::getLastFollowUpTime,currentTime);
                liaisonService.update(updateLiaisonWrapper);
            }

            customerEntity.setId(customerFollowUp.getCustomerId());

            customerEntity.setLastFollowUpTime(LocalDateTime.now());

            CustomerEntity customerOld = customerService.getById(customerFollowUp.getCustomerId());
            customerEntity.setUpdateTime(customerOld.getUpdateTime());

            customerService.updateById(customerEntity);
            systemRuleModuleConfigService.updateCustomerDate(customerEntity.getId());
            if (!ObjectUtils.isEmpty(customerFollowUpAddDTO.getMailId())){
//                customer_mail_bing_mark
                LambdaUpdateWrapper<CustomerMailBingMarkEntity> mailWrapper = new LambdaUpdateWrapper<>();
                mailWrapper.eq(CustomerMailBingMarkEntity::getCustomerId,customerFollowUpAddDTO.getCustomerId());
                mailWrapper.eq(CustomerMailBingMarkEntity::getMailId,customerFollowUpAddDTO.getMailId());
                mailWrapper.set(CustomerMailBingMarkEntity::getFollowUpId,customerFollowUp.getId());
                mailWrapper.set(CustomerMailBingMarkEntity::getFollowUpTime,currentTime);
                customerMailBingMarkService.update(mailWrapper);
            }
            if (!ObjectUtils.isEmpty(customerFollowUpAddDTO.getTask())){
                customerFollowUpAddDTO.getTask().setResourceType(customerFollowUpAddDTO.getResourceType());
                customerFollowUpAddDTO.getTask().setResourceTypeId(customerFollowUpAddDTO.getResourceTypeId());
                customerFollowUpAddDTO.getTask().setCustomerId(getResourceTyepId(customerFollowUpAddDTO.getResourceType(),customerFollowUpAddDTO.getResourceTypeId()));
                taskService.addTask(customerFollowUpAddDTO.getTask());
            }

            if (!ObjectUtils.isEmpty(customerFollowUpAddDTO.getTaskId())){
                //从完成任务进来的
                UpdateTaskDTO updateTaskDTO = new UpdateTaskDTO();
                updateTaskDTO.setTaskId(customerFollowUpAddDTO.getTaskId());
                taskService.complete(updateTaskDTO);
            }
//            if (!CollectionUtils.isEmpty(customerFollowUpAddDTO.getResourceIdList())){
                //修改附件信息
                sysResourceService.updateResourceById(customerFollowUp.getCustomerId(),ResourceTypeEnum.FOLLOW_UP.code,customerFollowUp.getId(),customerFollowUpAddDTO.getResourceIdList());
//            }

            //修改邮件跟进时间
            if(!ObjectUtils.isEmpty(customerFollowUpAddDTO.getMailId())){
                LambdaUpdateWrapper<EmailsEntity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(EmailsEntity::getFollowUpTime,LocalDate.now());
                updateWrapper.eq(EmailsEntity::getId,customerFollowUpAddDTO.getMailId());
                emailsService.update(updateWrapper);
            }
            //发送消息

            if (!CollectionUtils.isEmpty(customerFollowUpAddDTO.getRemindUserIdsTemp())) {
                assembleService.sendFollowEventMessages(customerFollowUp.getId(),"FOLLOW_UP_REMINDER",new HashSet<>(customerFollowUpAddDTO.getRemindUserIdsTemp()));
            }

            return Result.result("操作成功");
        }
        return Result.error("处理失败!");
    }

    @Override
    public CustomerFollowUpDetailVO getVOById(Long id) {
        if (!ObjectUtils.isEmpty(id)){
            CustomerFollowUpEntity customerFollowUpEntity = getById(id);
            if (!ObjectUtils.isEmpty(customerFollowUpEntity)){
                CustomerFollowUpDetailVO customerFollowUpDetailVO = new CustomerFollowUpDetailVO();
                BeanUtils.copyProperties(customerFollowUpEntity,customerFollowUpDetailVO);
                //更改为对应字典的业务名称（根据resourceStageDictValue修改resourceStageName）
                if (!ObjectUtils.isEmpty(customerFollowUpEntity.getDictCode())){
                    LambdaQueryWrapper<SysDictEntity> queryWrapper = new LambdaQueryWrapper();
                    queryWrapper.eq(SysDictEntity::getIsDelete,Integer.valueOf(0));
                    queryWrapper.eq(SysDictEntity::getEnabled,1);
                    queryWrapper.eq(SysDictEntity::getCode,customerFollowUpEntity.getDictCode());
                    queryWrapper.last("limit 1");
                    SysDictEntity sysDictEntity = sysDictService.getOne(queryWrapper);
                    if (!ObjectUtils.isEmpty(sysDictEntity)) {
                        LambdaQueryWrapper<SysDictDetailEntity> sysDictDetailEntityLambdaQueryWrapper = new LambdaQueryWrapper();
                        sysDictDetailEntityLambdaQueryWrapper.eq(SysDictDetailEntity::getDictId, sysDictEntity.getDictId());
                        sysDictDetailEntityLambdaQueryWrapper.eq(SysDictDetailEntity::getValue, customerFollowUpEntity.getResourceStageDictValue());
                        sysDictDetailEntityLambdaQueryWrapper.eq(SysDictDetailEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                        sysDictDetailEntityLambdaQueryWrapper.last("limit 1");
                        SysDictDetailEntity sysDictDetailEntity = sysDictDetailService.getOne(sysDictDetailEntityLambdaQueryWrapper);
                        if (!ObjectUtils.isEmpty(sysDictDetailEntity)) {
                            customerFollowUpDetailVO.setResourceStageName(sysDictDetailEntity.getLabel());
                        }
                    }
                }


                if (!ObjectUtils.isEmpty(customerFollowUpEntity.getCustomerId())) {
                    //添加客户名称
                    CustomerEntity customerEntity = customerService.getById(customerFollowUpEntity.getCustomerId());
                    customerFollowUpDetailVO.setCustomerName(customerEntity.getCustomerName());
                    customerFollowUpDetailVO.setCustomerStatusDictValue(customerEntity.getCustomerStatusDictValue());
                }
                if (!ObjectUtils.isEmpty(customerFollowUpEntity.getTaskId())) {
                    //添加任务
                    TaskEntity taskEntity = taskService.getById(customerFollowUpEntity.getTaskId());
                    if (!ObjectUtils.isEmpty(taskEntity)){
                        customerFollowUpDetailVO.setTaskContent(taskEntity.getTaskContent());
                    }
                }
                if (!ObjectUtils.isEmpty(customerFollowUpDetailVO.getRemindUserIds())){
                    List remindUserIdList = Arrays.asList(customerFollowUpDetailVO.getRemindUserIds().split(","));
                    //返回提醒人员名称
                    Map<Long, UserEntity> userMap = userService.IdListToUserMap(remindUserIdList);
                    String remindUserNames = userMap.values().stream().map(UserEntity::getRealName).collect(Collectors.joining(","));
                    customerFollowUpDetailVO.setRemindUserNames(remindUserNames);
                }

                if (!ObjectUtils.isEmpty(customerFollowUpDetailVO.getResourceType()) && !ObjectUtils.isEmpty(customerFollowUpDetailVO.getResourceTypeId())) {
                    //返回资源类型名称
                    customerFollowUpDetailVO.setResourceTypeName(ResourceTypeEnum.getDescByCode(customerFollowUpDetailVO.getResourceType()));
                    String resourceName = customerFollowUpService.getResourceTyepName(customerFollowUpDetailVO.getResourceType(), customerFollowUpDetailVO.getResourceTypeId().toString());

                    customerFollowUpDetailVO.setResourceName(resourceName);
                }

                //添加跟进人员信息
                UserEntity followUser = userService.getById(customerFollowUpEntity.getFollowUpMemberId());
                customerFollowUpDetailVO.setFollowUpMemberName(followUser.getRealName());
                customerFollowUpDetailVO.setFollowUpMemberAvatar(followUser.getAvatar());
                //添加联系人信息
                if (!ObjectUtils.isEmpty(customerFollowUpEntity.getLiaisonIds())){
                    customerFollowUpDetailVO.setLiaisonIdList(Arrays.stream(customerFollowUpDetailVO.getLiaisonIds().split(","))
                        .map(String::trim) // 如果需要去除空格
                        .mapToLong(Long::parseLong)
                        .boxed()
                        .collect(Collectors.toList()));
                    List<LiaisonEntity> liaisonUserList = liaisonService.listByIds(customerFollowUpDetailVO.getLiaisonIdList());
                    customerFollowUpDetailVO.setLiaisonName(liaisonUserList.stream().map(LiaisonEntity::getName).collect(Collectors.joining(",")));
                }
                //获取相关附件
                LambdaQueryWrapper<SysResourceEntity> resourceWrapper = new LambdaQueryWrapper<>();
                resourceWrapper.eq(SysResourceEntity::getResourceType, ResourceTypeEnum.FOLLOW_UP.code);
                resourceWrapper.eq(SysResourceEntity::getResourceTypeId,customerFollowUpEntity.getId());
                resourceWrapper.eq(SysResourceEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
                List<SysResourceEntity> sysResourceList = sysResourceService.list(resourceWrapper);
                customerFollowUpDetailVO.setResourceList(sysResourceList);
                //添加评论数量
                customerFollowUpDetailVO.setCommentCount(recordCommentService.count(new LambdaQueryWrapper<RecordCommentEntity>().eq(RecordCommentEntity::getRecordId, customerFollowUpEntity.getId().toString()).eq(RecordCommentEntity::getIsDelete, CommonConstant.DEL_FLAG_0).eq(RecordCommentEntity::getType, ResourceTypeEnum.FOLLOW_UP.code)));

                customerFollowUpDetailVO.dictFiled();
                customerFollowUpDetailVO.orgFiled();

                //添加下一个id
                CustomerFollowUpEntity next = getNextById(id, new LambdaQueryWrapper<CustomerFollowUpEntity>().eq(CustomerFollowUpEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
                if (!ObjectUtils.isEmpty(next)){
                    customerFollowUpDetailVO.setNextId(next.getId());

                }
                //添加上一个id
                CustomerFollowUpEntity previous = getPreviousById(id, new LambdaQueryWrapper<CustomerFollowUpEntity>().eq(CustomerFollowUpEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
                if (!ObjectUtils.isEmpty(previous)){
                    customerFollowUpDetailVO.setPreviousId(previous.getId());
                }
                return customerFollowUpDetailVO;
            }
        }
        return null;
    }

    @Override
    public Map<Long, CustomerFollowUpLastVO> getFollowUpLastVOMap(List<Long> resourceTypeIdList, String type) {
        resourceTypeIdList = resourceTypeIdList.stream().distinct().collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(resourceTypeIdList) && !ObjectUtils.isEmpty(type)){
            List<CustomerFollowUpLastVO> customerFollowUpLastVOList = baseMapper.getFollowUpLastVOList(resourceTypeIdList,type);
            return customerFollowUpLastVOList.stream().collect(Collectors.toMap(CustomerFollowUpLastVO::getResourceTypeId, customerFollowUpLastVO -> customerFollowUpLastVO));
        }
        return null;
    }

    @Override
    public Map<Long, CustomerFollowUpLastVO> getBussFollowUpLastVOMap(List<Long> resourceTypeIdList, String type) {
        resourceTypeIdList = resourceTypeIdList.stream().distinct().collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(resourceTypeIdList) && !ObjectUtils.isEmpty(type)){
            List<CustomerFollowUpLastVO> customerFollowUpLastVOList = baseMapper.getBusinessFollowUpLastVOList(resourceTypeIdList,type);
            return customerFollowUpLastVOList.stream().collect(Collectors.toMap(CustomerFollowUpLastVO::getResourceTypeId, customerFollowUpLastVO -> customerFollowUpLastVO));
        }
        return null;
    }

    @Override
    public LocalDateTime getLastFollowUpTime(Long id, String type) {
        Map<Long, CustomerFollowUpLastVO> customerFollowUpLastVOMap = getFollowUpLastVOMap(Arrays.asList(id),type);
        if (!ObjectUtils.isEmpty(customerFollowUpLastVOMap)){
            CustomerFollowUpLastVO customerFollowUpLastVO = customerFollowUpLastVOMap.get(id);
            if (!ObjectUtils.isEmpty(customerFollowUpLastVO)){
                return customerFollowUpLastVO.getFollowUpTime();
            }
        }
        return null;
    }

    @Override
    public List<UserClickTitleVO> selectUserClickTitle(Long ownerBy, String title) {
        return this.baseMapper.selectUserClickTitle(ownerBy,title);
    }
    @Override
    public Result<?> selectListVO(CustomerFollowUpSearchDTO customerFollowUpSearchDTO) {
        IPage<CustomerFollowUpEntity> page = new Page<>(customerFollowUpSearchDTO.getPageIndex(), customerFollowUpSearchDTO.getPageSize());
        LambdaQueryWrapper<CustomerFollowUpEntity> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(CustomerFollowUpEntity::getCustomerId, customerFollowUpSearchDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getCustomerId()),CustomerFollowUpEntity::getCustomerId,customerFollowUpSearchDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getMailId()),CustomerFollowUpEntity::getMailId,customerFollowUpSearchDTO.getMailId());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getResourceType()),CustomerFollowUpEntity::getResourceType,customerFollowUpSearchDTO.getResourceType());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getResourceTypeId()),CustomerFollowUpEntity::getResourceTypeId,customerFollowUpSearchDTO.getResourceTypeId());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getFollowUpTypeValue()), CustomerFollowUpEntity::getFollowUpTypeValue, customerFollowUpSearchDTO.getFollowUpTypeValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getFollowUpMemberId()), CustomerFollowUpEntity::getFollowUpMemberId, customerFollowUpSearchDTO.getFollowUpMemberId());
        wrapper.ge(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getFollowUpStartDate()), CustomerFollowUpEntity::getFollowUpTime, customerFollowUpSearchDTO.getFollowUpStartDate());
        wrapper.le(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getFollowUpEndDate()), CustomerFollowUpEntity::getFollowUpTime, customerFollowUpSearchDTO.getFollowUpEndDate());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpSearchDTO.getOwnerBy()), CustomerFollowUpEntity::getOwnerBy, customerFollowUpSearchDTO.getOwnerBy());
        wrapper.in(!CollectionUtils.isEmpty(customerFollowUpSearchDTO.getOwnerByIds()),CustomerFollowUpEntity::getOwnerBy, customerFollowUpSearchDTO.getOwnerByIds());
        if (StrUtil.isNotBlank(customerFollowUpSearchDTO.getBlurry())) {
            wrapper.and(w ->w.like(CustomerFollowUpEntity::getContent,customerFollowUpSearchDTO.getBlurry()).or().like(CustomerFollowUpEntity::getResourceName,customerFollowUpSearchDTO.getBlurry()));
        }
        wrapper.eq(CustomerFollowUpEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.orderByDesc(CustomerFollowUpEntity::getFollowUpTime);

        Long loginUserId = LoginUserUtil.getCurrentUserId();
        List<Long> customerIds = customerService.getCustomerIdList(loginUserId);
        String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));

        StringBuilder mergeSql = new StringBuilder();
        String v1 = StrUtil.isBlank(customerIdString) ? "" : " customer_id in ( "+customerIdString +") or ";
        mergeSql.append(v1);
        String v2 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+loginUserId+",managers))";

        mergeSql.append(v2);

        page = pageWithScope(page, wrapper,customerFollowUpSearchDTO,mergeSql.toString());
        if (CollectionUtils.isEmpty(page.getRecords())){
            return Result.result(page);
        }
        DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<CustomerFollowUpListVO> customerFollowUpListVOList = mapperFactory.getMapperFacade().mapAsList(page.getRecords(),CustomerFollowUpListVO.class);
        SysBaseField.dictFileds(customerFollowUpListVOList);
        //获取用户信息
        List<Long> userList = customerFollowUpListVOList.stream().map(CustomerFollowUpListVO::getFollowUpMemberId).collect(Collectors.toList());
        Map<Long, UserEntity> map = userService.IdListToUserMap(userList);
        List<Long> customerIdList = customerFollowUpListVOList.stream().map(CustomerFollowUpListVO::getCustomerId).collect(Collectors.toList());
        List<CustomerEntity> customerls = customerService.listCustomers(customerIdList);
        Map<Long, String> customerMap = CollectionUtils.isEmpty(customerls) ? new HashMap<>() : customerls.stream()
                .collect(Collectors.toMap(CustomerEntity::getId, CustomerEntity::getCustomerName));
        List<Long> taskIdList = customerFollowUpListVOList.stream().map(CustomerFollowUpListVO::getTaskId).collect(Collectors.toList());
        Map<Long, TaskEntity> taskMap;
        if (!CollectionUtils.isEmpty(taskIdList)){
            LambdaQueryWrapper<TaskEntity> taskWrapper = new LambdaQueryWrapper<>();
            taskWrapper.in(TaskEntity::getId,taskIdList);
            taskWrapper.eq(TaskEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            taskMap = taskService.list(taskWrapper).stream().collect(Collectors.toMap(TaskEntity::getId, taskEntity -> taskEntity));
        } else {
            taskMap = new HashMap<>();
        }

        //查询跟进评论数量
        List<Long> customerFollowUpIdList = customerFollowUpListVOList.stream().map(CustomerFollowUpListVO::getId).collect(Collectors.toList());
        Map<Long,Integer> recordMap = recordCommentService.getRecordNumMap(ResourceTypeEnum.FOLLOW_UP.code,customerFollowUpIdList);

        Collection<UserEntity> users = userService.listByIds(userList);
        Map<Long, JobEntity> jobMap = jobService.getJobMap(users);


        customerFollowUpListVOList.forEach(customerFollowUpListVO -> {
            UserEntity userEntity = map.get(customerFollowUpListVO.getFollowUpMemberId());
            if (Objects.nonNull(userEntity)){
                customerFollowUpListVO.setFollowUpMemberName(userEntity.getRealName());
                customerFollowUpListVO.setFollowUpMemberAvatar(userEntity.getAvatar());
                JobEntity job = jobMap.get(userEntity.getJobId());
                if (Objects.nonNull(job)) {
                    customerFollowUpListVO.setOwnerByJobName(job.getName());
                }
            }
            if (Objects.nonNull(customerFollowUpListVO.getCustomerId())) {
                customerFollowUpListVO.setCustomerName(customerMap.getOrDefault(customerFollowUpListVO.getCustomerId(),""));
            }
            if (Objects.nonNull(customerFollowUpListVO.getResourceTypeId())) {
                String resourceName = getResourceTyepName(customerFollowUpListVO.getResourceType(),customerFollowUpListVO.getResourceTypeId().toString());
                customerFollowUpListVO.setResourceName(resourceName);
            }
            if (Objects.nonNull(customerFollowUpListVO.getTaskId())){
                customerFollowUpListVO.setTaskContent(taskMap.getOrDefault(customerFollowUpListVO.getTaskId(),new TaskEntity()).getTaskContent());
            }
            //返回评论数量
            customerFollowUpListVO.setRecordCommentCount(recordMap.getOrDefault(customerFollowUpListVO.getId(),0));
        });

        IPage<CustomerFollowUpListVO> pageVO =new Page<>(customerFollowUpSearchDTO.getPageIndex(), customerFollowUpSearchDTO.getPageSize());
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        pageVO.setRecords(customerFollowUpListVOList);
        pageVO.setCurrent(page.getCurrent());
        SysBaseField.orgFileds(pageVO.getRecords());
        SysBaseField.dictFileds(pageVO.getRecords());
        return Result.result(pageVO);
    }


    @Override
    public String getResourceTyepName(String resourceType, String resourceTypeId){
        if (MessageTypeEnum.CUSTOMER.getCode().equals(resourceType)
                || MessageTypeEnum.CLUS.getCode().equals(resourceType)) {
            CustomerEntity customer = customerService.getById(resourceTypeId);
            return  customer.getCustomerName();
        } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceType)) {
            // 联系人
            LiaisonEntity liaison = liaisonService.getById(resourceTypeId);
            if (Objects.nonNull(liaison)) {
                return liaison.getName();
            }

        } else if (MessageTypeEnum.BUSINESS.getCode().equals(resourceType)) {
            // 商机
            BusinessEntity business = businessService.getById(resourceTypeId);
            if (Objects.nonNull(business)) {
                return business.getTitle();
            }
        } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(resourceType)) {
            // 订单
            OrderFormEntity orderForm = orderFormService.getById(resourceTypeId);
            if (Objects.nonNull(orderForm)) {
                return orderForm.getTitle();
            }
        } else if (MessageTypeEnum.WORK_ORDER.getCode().equals(resourceType)) {
            // 工单
            WorkOrderEntity workOrder = workOrderService.getById(resourceTypeId);
            if (Objects.nonNull(workOrder)) {
                return workOrder.getTitle();
            }
        }
        return "";
    }

    public Long getResourceTyepId(String resourceType, Long resourceTypeId){
        if (MessageTypeEnum.CUSTOMER.getCode().equals(resourceType)
                || MessageTypeEnum.CLUS.getCode().equals(resourceType)) {
            return resourceTypeId;
        } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceType)) {
            // 联系人
            LiaisonEntity liaison = liaisonService.getById(resourceTypeId);
            if (Objects.nonNull(liaison)) {
                return liaison.getCustomerId();
            }

        } else if (MessageTypeEnum.BUSINESS.getCode().equals(resourceType)) {
            // 商机
            BusinessEntity business = businessService.getById(resourceTypeId);
            if (Objects.nonNull(business)) {
                return business.getCustomerId();
            }
        } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(resourceType)) {
            // 订单
            OrderFormEntity orderForm = orderFormService.getById(resourceTypeId);
            if (Objects.nonNull(orderForm)) {
                return orderForm.getCustomerId();
            }
        } else if (MessageTypeEnum.WORK_ORDER.getCode().equals(resourceType)) {
            // 工单
            WorkOrderEntity workOrder = workOrderService.getById(resourceTypeId);
            if (Objects.nonNull(workOrder)) {
                return workOrder.getCustomerId();
            }
        }
        return 0L;
    }

    @Override
    public String getResourceStatusTyepId(String resourceType, Long resourceTypeId){
        if (MessageTypeEnum.CUSTOMER.getCode().equals(resourceType)) {
            CustomerEntity customer = customerService.getById(resourceTypeId);
            if (Objects.nonNull(customer)) {
                CustomerVO vo  = new CustomerVO();
                BeanUtils.copyProperties(customer,vo);
                vo.dictFiled();
                return  vo.getCustomerStatusName();
            }
            return "";
        }  else if (MessageTypeEnum.CLUS.getCode().equals(resourceType)) {
            CustomerEntity customer = customerService.getById(resourceTypeId);
            if (Objects.nonNull(customer)) {
                CustomerVO vo  = new CustomerVO();
                BeanUtils.copyProperties(customer,vo);
                vo.dictFiled();
                return  vo.getClueStatusName();
            }
            return "";
        } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceType)) {
            // 联系人
//            LiaisonEntity liaison = liaisonService.getById(resourceTypeId);
//            if (Objects.nonNull(liaison)) {
//                return liaison.getCustomerId();
//            }
            return  "";

        } else if (MessageTypeEnum.BUSINESS.getCode().equals(resourceType)) {
            // 商机
            BusinessEntity business = businessService.getById(resourceTypeId);
            if (Objects.nonNull(business)) {
                BusinessDetailVO vo  = new BusinessDetailVO();
                BeanUtils.copyProperties(business,vo);
                vo.dictFiled();
                return vo.getStageName();
            }
            return "";
        } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(resourceType)) {
            // 订单
//            OrderFormEntity orderForm = orderFormService.getById(resourceTypeId);
//            if (Objects.nonNull(orderForm)) {
//                return orderForm.getCustomerId();
//            }
            return "";
        } else if (MessageTypeEnum.WORK_ORDER.getCode().equals(resourceType)) {
            // 工单
//            WorkOrderEntity workOrder = workOrderService.getById(resourceTypeId);
//            if (Objects.nonNull(workOrder)) {
//                return workOrder.getCustomerId();
//            }
            return "";
        }
        return "";
    }

    @Override
    public IPage<?> selectSimpleListVO(CustomerSearchSearchDTO customerSearchSearchDTO) {
        IPage<CustomerFollowUpEntity> page = new Page<>(customerSearchSearchDTO.getPageIndex(),customerSearchSearchDTO.getPageSize());
        LambdaQueryWrapper<CustomerFollowUpEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(CustomerFollowUpEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(customerSearchSearchDTO.getBlurry())) {
            queryWrapper.and(w -> w.like(CustomerFollowUpEntity::getSubject,customerSearchSearchDTO.getBlurry()).or().like(CustomerFollowUpEntity::getContent,customerSearchSearchDTO.getBlurry()));
        }

        Long loginUserId = customerSearchSearchDTO.getLoginUser().getId();

        StringBuilder mergeSql = new StringBuilder();
//        List<Long> customerIds = customerService.getCustomerIdList(loginUserId);
//        String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        String v1 = StrUtil.isBlank(customerSearchSearchDTO.getCustomerIdString()) ? "" : " customer_id in ( "+customerSearchSearchDTO.getCustomerIdString() +") ";
        mergeSql.append(v1);

//        String v2 = "owner_by in ("+customerSearchSearchDTO.getUserIdString()+")";
//        mergeSql.append(v2);
        IPage<CustomerFollowUpEntity> pageList = pageWithScope(page, queryWrapper,customerSearchSearchDTO,mergeSql.toString());
        IPage<CustomerFollowUpDetailVO> vos = SysBaseField.page(pageList, CustomerFollowUpDetailVO.class);
        return vos;
    }
}
