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

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.storlead.framework.common.constant.CodeGenerateInterface;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.enums.ResultCode;
import com.storlead.framework.common.util.HtmlUtils;
import com.storlead.framework.common.util.MD5Util;
import com.storlead.framework.common.util.StringUtil;
import com.storlead.framework.common.util.generate.CodeGenerate;
import com.storlead.es.pojo.vo.EsGenericVO;
import com.storlead.es.pojo.vo.EsQuerySimilarityVO;
import com.storlead.es.service.EsSearchCustomerService;
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.framework.redis.RedisService;
import com.storlead.sales.enums.QueryRangeTypeEnum;
import com.storlead.sales.pojo.dto.customer.*;
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.entity.mail.CustomerMailBingMarkEntity;
import com.storlead.sales.pojo.entity.systemrule.SystemRuleModuleConfigEntity;
import com.storlead.sales.pojo.vo.systemrule.CustomerTypeRulesVO;
import com.storlead.sales.pojo.vo.systemrule.FieldSimilarityConfigVO;
import com.storlead.sales.pojo.entity.task.TaskEntity;
import com.storlead.sales.mapper.customer.CustomerCompanyMapper;
import com.storlead.sales.mapper.customer.CustomerMapper;
import com.storlead.sales.mapper.customer.LiaisonMapper;
import com.storlead.sales.service.customer.*;
import com.storlead.mail.service.EmailsService;
import com.storlead.sales.service.CustomerMailBingMarkService;
import com.storlead.sales.service.CustomerMailRecordService;
import com.storlead.sales.service.sku.QuotationService;
import com.storlead.sales.service.systemrule.SystemRuleModuleConfigService;
import com.storlead.sales.service.task.TaskService;
import com.storlead.sales.util.SystemRuleModuleUtils;
import com.storlead.system.pojo.entity.SystemConfigItemEntity;
import com.storlead.system.service.SystemConfigItemService;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.IUserService;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户基本信息表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-04-12
 */
@Service
public class CustomerServiceImpl extends MyBaseServiceImpl<CustomerMapper, CustomerEntity> implements CustomerService {

    @Resource
    private CustomerCompanyService customerCompanyService;
    @Resource
    private BusinessService businessService;
    @Resource
    private OrderFormService orderFormService;
    @Resource
    private QuotationService quotationService;
    @Resource
    private LiaisonService liaisonService;

    @Resource
    private LiaisonResourceService liaisonResourceService;
    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Resource
    private TaskService taskService;
    @Resource
    private SendRecordService sendRecordService;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private SysResourceService sysResourceService;
    @Resource
    private  CustomerChangeLogService customerChangeLogService;
    @Resource
    private CustomerUserFollowService customerUserFollowService;
    @Resource
    private IUserService userService;
    @Resource
    private IDepartService departService;
    @Resource
    private SystemRuleModuleConfigService systemRuleModuleConfigService;
    @Resource
    private MessageAssembleService assembleService;
    @Resource
    private CustomerMailRecordService mailRecordService;
    @Resource
    private EmailsService emailsService;
    @Resource
    private CustomerOwnerRecordService customerOwnerService;
    @Resource
    private CustomerMailBingMarkService customerMailBingMarkService;
    @Resource
    private CustomerCompanyMapper customerCompanyMapper;
    @Resource
    private LiaisonMapper liaisonMapper;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private SystemConfigItemService systemConfigItemService;
    @Resource
    private EsSearchCustomerService searchCustomerService;
    @Resource
    private WorkDynamicsService workDynamicsService;
    @Resource
    private RedisService redisService;

    @Value("${environment}")
    private  String environment;

    private static String name = "\"indexFields\": [\n" +
            "        {\n" +
            "            \"indexName\" : \"${environment}customer_data_index\",\"resourceType\":${resourceType},\"fields\":[{\"fieldName\":\"customer_name.keyword\",\"fieldDescribe\":\"${customerTypeName}\"}]\n" +
            "        }\n" +
//            "        }\n" +
            "    ]\n" +
            "}";

    private static String website = "\"indexFields\": [\n" +
            "        {\n" +
            "            \"indexName\" : \"${environment}customer_company_data_index\",\"resourceType\":${resourceType},\"fields\":[{\"fieldName\":\"website.keyword\",\"fieldDescribe\":\"企业网址\"},{\"fieldName\":\"website1.keyword\",\"fieldDescribe\":\"企业备用网址1\"},{\"fieldName\":\"website2.keyword\",\"fieldDescribe\":\"企业备用网址2\"},{\"fieldName\":\"website3.keyword\",\"fieldDescribe\":\"企业备用网址3\"}]\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    private static String email = "\"indexFields\": [\n" +
            "        {\n" +
            "            \"indexName\" : \"${environment}liaison_data_index\",\"resourceType\":20,\"fields\":[{\"fieldName\":\"email.keyword\",\"fieldDescribe\":\"联系人邮箱\"},{\"fieldName\":\"email1.keyword\",\"fieldDescribe\":\"联系人备用邮箱1\"},{\"fieldName\":\"email2.keyword\",\"fieldDescribe\":\"联系人备用邮箱2\"},{\"fieldName\":\"email3.keyword\",\"fieldDescribe\":\"联系人备用邮箱3\"}]\n" +
            "        },{\n" +
            "            \"indexName\" : \"${environment}customer_company_data_index\",\"resourceType\":${resourceType},\"fields\":[{\"fieldName\":\"email.keyword\",\"fieldDescribe\":\"企业邮箱\"},{\"fieldName\":\"email1.keyword\",\"fieldDescribe\":\"企业备用邮箱1\"},{\"fieldName\":\"email2.keyword\",\"fieldDescribe\":\"企业备用邮箱2\"},{\"fieldName\":\"email3.keyword\",\"fieldDescribe\":\"企业备用邮箱3\"}]\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    private static String header = "{\n" +
            "    \"queryText\": \"${queryText}\",\n" +
            "    \"topN\": 100,\n" +
            "    \"fieldKey\": \"keyword\",\n" +
            "    \"minScore\": ${minScore},";

    @Override
    public Result<?> addNoCheckCustomer(CustomerAddDTO customerAddDTO) {
        //是否是客户
        boolean isCustomer = true;
        if (ResourceTypeEnum.CLUS.code.equals(customerAddDTO.getCustomerForm())) {
            isCustomer = false;
        }


        CustomerEntity customerEntity = new CustomerEntity();
        BeanUtils.copyProperties(customerAddDTO, customerEntity);
        if (ObjectUtils.isEmpty(customerEntity.getDataCode())){
            customerEntity.setDataCode(CodeGenerate.generate10Code(CodeGenerateInterface.CUSTOMER_CODE));
        }

        customerEntity.setLastFollowUpTime(LocalDateTime.now());
        if (isCustomer) {
            customerEntity.setOwnerTime(LocalDateTime.now());
        }
        boolean isOk = save(customerEntity);
        if (isOk){
            if (Objects.nonNull(customerAddDTO.getCustomerCompany())) {
                CustomerCompanyEntity companyCompanyEntity = new CustomerCompanyEntity();
                if (!ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())) {
                    BeanUtils.copyProperties(customerAddDTO.getCustomerCompany(), companyCompanyEntity);
                }
                companyCompanyEntity.setCustomerId(customerEntity.getId());
                customerCompanyService.save(companyCompanyEntity);
            }
            LiaisonEntity liaisonEntity = new LiaisonEntity();
            if (!ObjectUtils.isEmpty(customerAddDTO.getLiaison())) {
                BeanUtils.copyProperties(customerAddDTO.getLiaison(), liaisonEntity);
            }
            liaisonEntity.setCustomerId(customerEntity.getId());
            liaisonService.save(liaisonEntity);
            if (!ObjectUtils.isEmpty(customerAddDTO.getTask())){
                customerAddDTO.getTask().setResourceType(customerAddDTO.getCustomerForm().toString());
                customerAddDTO.getTask().setResourceTypeId(customerEntity.getId());
                taskService.addTask(customerAddDTO.getTask().setCustomerId(customerEntity.getId()));
            }

            //添加附件
            if (!CollectionUtils.isEmpty(customerAddDTO.getResourceIdList())){
                sysResourceService.updateResourceById(customerEntity.getId(),customerAddDTO.getCustomerForm().toString(),customerEntity.getId(),customerAddDTO.getResourceIdList());
            }
            if (ObjectUtils.isEmpty(customerAddDTO.getOwnerBy())){
                LambdaUpdateWrapper<CustomerEntity> customerEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                customerEntityLambdaUpdateWrapper.eq(CustomerEntity::getId,customerEntity.getId());
                customerEntityLambdaUpdateWrapper.set(CustomerEntity::getOwnerBy, null);
                update(customerEntityLambdaUpdateWrapper);

                LambdaUpdateWrapper<LiaisonEntity> liaisonEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                liaisonEntityLambdaUpdateWrapper.eq(LiaisonEntity::getId,liaisonEntity.getId());
                liaisonEntityLambdaUpdateWrapper.set(LiaisonEntity::getOwnerBy, null);
                liaisonService.update(liaisonEntityLambdaUpdateWrapper);
            }
            if(Boolean.TRUE.equals(customerAddDTO.getHasPublicCustomer())){
                LambdaUpdateWrapper<CustomerEntity> customerEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                customerEntityLambdaUpdateWrapper.eq(CustomerEntity::getId,customerEntity.getId());
                customerEntityLambdaUpdateWrapper.set(CustomerEntity::getOwnerBy,null);
                update(customerEntityLambdaUpdateWrapper);
                LambdaUpdateWrapper<LiaisonEntity> liaisonEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                liaisonEntityLambdaUpdateWrapper.eq(LiaisonEntity::getId,liaisonEntity.getId());
                liaisonEntityLambdaUpdateWrapper.set(LiaisonEntity::getOwnerBy, null);
                liaisonService.update(liaisonEntityLambdaUpdateWrapper);
            }
            return Result.result(customerEntity.getId());
        }
        return Result.error("添加失败！");
    }

    @Override
    public List<CustomerEntity> assembleCustomerLs(List<CustomerAddDTO> dtos) {
        List<CustomerEntity>  customers = new ArrayList<>();
        for (CustomerAddDTO dto : dtos) {
            CustomerEntity customerEntity = new CustomerEntity();
            BeanUtils.copyProperties(dto, customerEntity);
            if (ObjectUtils.isEmpty(customerEntity.getDataCode())){
                customerEntity.setDataCode(CodeGenerate.generate10Code(CodeGenerateInterface.CUSTOMER_CODE));
            }
            customerEntity.setLastFollowUpTime(LocalDateTime.now());
            //是否是客户
            boolean isCustomer = true;
            if (ResourceTypeEnum.CLUS.code.equals(dto.getCustomerForm())) {
                isCustomer = false;
            }
            if (isCustomer) {
                customerEntity.setOwnerTime(LocalDateTime.now());
            }
            customers.add(customerEntity);
        }
        return customers;
    }

    @Override
    public List<LiaisonEntity> assembleLiaisonLs(List<CustomerAddDTO> dtos) {
        List<LiaisonEntity> liaisons = new ArrayList<>();
        for (CustomerAddDTO dto : dtos) {
            LiaisonEntity liaisonEntity = new LiaisonEntity();
            if (!ObjectUtils.isEmpty(dto.getLiaison())) {
                BeanUtils.copyProperties(dto.getLiaison(), liaisonEntity);
                liaisonEntity.setCustomerId(dto.getCustomerId());
                if (Objects.nonNull(dto.getOwnerBy())) {
                    liaisonEntity.setOwnerBy(dto.getOwnerBy());
                }
                liaisons.add(liaisonEntity);
            }
        }
        return liaisons;
    }

    @Override
    public List<CustomerCompanyEntity> assembleCustomerCompanyLs(List<CustomerAddDTO> dtos) {
        List<CustomerCompanyEntity> companys = new ArrayList<>();
        for (CustomerAddDTO dto : dtos) {
            CustomerCompanyEntity companyCompanyEntity = new CustomerCompanyEntity();
            if (!ObjectUtils.isEmpty(dto.getCustomerCompany())) {
                BeanUtils.copyProperties(dto.getCustomerCompany(), companyCompanyEntity);
                companyCompanyEntity.setCustomerId(dto.getCustomerId());
                if (Objects.nonNull(dto.getOwnerBy())) {
                    companyCompanyEntity.setOwnerBy(dto.getOwnerBy());
                }
                companys.add(companyCompanyEntity);
            }
        }
        return companys;
    }

    @Override
    public Result<?> addCustomer(CustomerAddDTO customerAddDTO) {
        if (ObjectUtils.isEmpty(customerAddDTO)) {
            return Result.error("参数不能为空");
        }

        if (!ObjectUtils.isEmpty(customerAddDTO.getTask())) {
            if (Boolean.TRUE.equals(customerAddDTO.getTask().getIsCreateTask())) {
                if (Objects.isNull(customerAddDTO.getTask().getTaskBeginTime())) {
                    return Result.error("请选择任务开始时间");
                }
            }
        }
        //是否是客户
        boolean isCustomer = true;
        if (ResourceTypeEnum.CLUS.code.equals(customerAddDTO.getCustomerForm().toString())) {
            isCustomer = false;
        }
        boolean hasPublicCustomer = customerAddDTO.getHasPublicCustomer();

        LambdaQueryWrapper<SystemRuleModuleConfigEntity> sysWrapper = new LambdaQueryWrapper<>();
        sysWrapper.eq(SystemRuleModuleConfigEntity::getResourceType, customerAddDTO.getCustomerForm().toString());
        sysWrapper.last("limit 1");
        SystemRuleModuleConfigEntity systemRuleModuleConfig = systemRuleModuleConfigService.getOne(sysWrapper);
        if (!isCustomer && !hasPublicCustomer) {
            //线索规则

            if (systemRuleModuleConfig.getHasMaxMember()) {
                //查询当前用户是否超过上限
                LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CustomerEntity::getOwnerBy, customerAddDTO.getOwnerBy());
                wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(ResourceTypeEnum.CLUS.code));
                wrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerEntity::getId, customerAddDTO.getId());
                wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                Integer customerCount = count(wrapper);
                if (customerCount >= systemRuleModuleConfig.getMaxMemberNum()) {
                    return Result.error("线索数量超过上限");
                }
            }
        }

        if (isCustomer && !hasPublicCustomer) {
            if (Objects.nonNull(systemRuleModuleConfig) && systemRuleModuleConfig.getHasMaxMember()) {
                //查询当前用户是否超过上限
                LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CustomerEntity::getOwnerBy, customerAddDTO.getOwnerBy());
                wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(ResourceTypeEnum.CUSTOMER.code));
                wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                wrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerEntity::getId, customerAddDTO.getId());
                Integer customerCount = count(wrapper);
                if (customerCount >= systemRuleModuleConfig.getMaxMemberNum()) {
                    return Result.error("客户数量超过上限");
                }
            }
        }


        CustomerEntity customerEntity = new CustomerEntity();
        BeanUtils.copyProperties(customerAddDTO, customerEntity);
        if (ObjectUtils.isEmpty(customerEntity.getDataCode())){
            customerEntity.setDataCode(CodeGenerate.generate10Code(CodeGenerateInterface.CUSTOMER_CODE));
        }

        customerEntity.setLastFollowUpTime(LocalDateTime.now());
        if (isCustomer) {
            customerEntity.setOwnerTime(LocalDateTime.now());
        }
        boolean isOk = save(customerEntity);
        if (isOk){
            //添加客户工作动态
            WorkDynamicsEntity workDynamics = new WorkDynamicsEntity();
            workDynamics.setCustomerId(customerEntity.getId());
            workDynamics.setOperationType(1);
            workDynamics.setResourceType(ResourceTypeEnum.CUSTOMER.code);
            workDynamics.setResourceTypeId(customerEntity.getId());
            workDynamics.setOwnerBy(customerEntity.getOwnerBy());
            if (isCustomer) {
                workDynamics.setTitle("创建客户 " + HtmlUtils.clearContent(customerEntity.getCustomerName()));
            }else {
                workDynamics.setTitle("创建线索 " + HtmlUtils.clearContent(customerEntity.getCustomerName()));
            }

            try {
                // 创建 Gson 实例
                Gson gson = new Gson();
                // 将 CustomerEntity 对象转换为 JSON 字符串
                String workContent = gson.toJson(customerEntity);

                workDynamics.setContent(workContent);
            }catch (Exception e){
                return Result.error("工作动态写入异常");
            }
            workDynamicsService.save(workDynamics);

            systemRuleModuleConfigService.updateCustomerDate(customerEntity.getId());
            CustomerCompanyEntity companyCompanyEntity = new CustomerCompanyEntity();
            if (!ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())) {
                BeanUtils.copyProperties(customerAddDTO.getCustomerCompany(), companyCompanyEntity);
            }
            companyCompanyEntity.setCustomerId(customerEntity.getId());
            customerCompanyService.save(companyCompanyEntity);
            LiaisonEntity liaisonEntity = new LiaisonEntity();
            if (!ObjectUtils.isEmpty(customerAddDTO.getLiaison())) {
                BeanUtils.copyProperties(customerAddDTO.getLiaison(), liaisonEntity);
            }
            liaisonEntity.setCustomerId(customerEntity.getId());
//            liaisonEntity.setResourceType(customerAddDTO.getCustomerForm().toString());
//            liaisonEntity.setResourceTypeId(customerEntity.getId());

            liaisonService.save(liaisonEntity);

            //添加联系人工作动态
            WorkDynamicsEntity workDynamicsLiaison = new WorkDynamicsEntity();
            workDynamicsLiaison.setCustomerId(customerEntity.getId());
            workDynamicsLiaison.setOperationType(1);
            workDynamicsLiaison.setResourceType(ResourceTypeEnum.LIAISON.code);
            workDynamicsLiaison.setResourceTypeId(liaisonEntity.getId());
            workDynamicsLiaison.setTitle("创建联系人 "+ HtmlUtils.clearContent(liaisonEntity.getName()));
            workDynamicsLiaison.setOwnerBy(customerEntity.getOwnerBy());

            try {
                // 创建 Gson 实例
                Gson gson = new Gson();
                // 将 CustomerEntity 对象转换为 JSON 字符串
                String workContentLiaison = gson.toJson(liaisonEntity);

                workDynamicsLiaison.setContent(workContentLiaison);
            }catch (Exception e){
                return Result.error("联系人工作动态写入异常");
            }
            workDynamicsService.save(workDynamicsLiaison);

            if (!ObjectUtils.isEmpty(customerAddDTO.getTask())){
                customerAddDTO.getTask().setResourceType(customerAddDTO.getCustomerForm().toString());
                customerAddDTO.getTask().setResourceTypeId(customerEntity.getId());
                taskService.addTask(customerAddDTO.getTask().setCustomerId(customerEntity.getId()));
            }

            //添加附件
            if (!CollectionUtils.isEmpty(customerAddDTO.getResourceIdList())){
                sysResourceService.updateResourceById(customerEntity.getId(),customerAddDTO.getCustomerForm().toString(),customerEntity.getId(),customerAddDTO.getResourceIdList());
            }

            //发送消息
            //是否是客户
            if (isCustomer){
                assembleService.sendCustomerEventMessages(customerEntity.getId(),"ADD_CUSTOMER");
            }else {
                assembleService.sendCustomerEventMessages(customerEntity.getId(),"MEMBER_ADD_CLUE");
            }
            //发送查重消息
//            sendDuplicate(customerAddDTO.getErrorCanSaveVOList());

            if (ObjectUtils.isEmpty(customerAddDTO.getOwnerBy())){
                LambdaUpdateWrapper<CustomerEntity> customerEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                customerEntityLambdaUpdateWrapper.eq(CustomerEntity::getId,customerEntity.getId());
                customerEntityLambdaUpdateWrapper.set(CustomerEntity::getOwnerBy, null);
                update(customerEntityLambdaUpdateWrapper);
                LambdaUpdateWrapper<LiaisonEntity> liaisonEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                liaisonEntityLambdaUpdateWrapper.eq(LiaisonEntity::getId,liaisonEntity.getId());
                liaisonEntityLambdaUpdateWrapper.set(LiaisonEntity::getOwnerBy, null);
                liaisonService.update(liaisonEntityLambdaUpdateWrapper);
            }
            if(Boolean.TRUE.equals(customerAddDTO.getHasPublicCustomer())){
                LambdaUpdateWrapper<CustomerEntity> customerEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                customerEntityLambdaUpdateWrapper.eq(CustomerEntity::getId,customerEntity.getId());
                customerEntityLambdaUpdateWrapper.set(CustomerEntity::getOwnerBy,null);
                update(customerEntityLambdaUpdateWrapper);
                LambdaUpdateWrapper<LiaisonEntity> liaisonEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                liaisonEntityLambdaUpdateWrapper.eq(LiaisonEntity::getId,liaisonEntity.getId());
                liaisonEntityLambdaUpdateWrapper.set(LiaisonEntity::getOwnerBy, null);
                liaisonService.update(liaisonEntityLambdaUpdateWrapper);
            }

            List<SimilarityErrorVO>  errorCanSaveVOList = customerAddDTO.getErrorCanSaveVOList();
            if (!CollectionUtils.isEmpty(errorCanSaveVOList)) {
                List<SimilarityErrorVO> customerErrorVOList = errorCanSaveVOList.stream().filter(e -> e.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(customerErrorVOList)) {
                    Set<Long> customerIds = customerErrorVOList.stream().map(SimilarityErrorVO::getCustomerId).collect(Collectors.toSet());
                    if (!CollectionUtils.isEmpty(customerIds)) {
                        for (Long customerId : customerIds) {
                            assembleService.sendCustomerEventMessages(customerId, "DUPLICATE_WARNING_CUSTOMER");

                        }
                    }
                }

                List<SimilarityErrorVO> clusErrorVOList = errorCanSaveVOList.stream().filter(e -> e.getResourceType().equals(ResourceTypeEnum.CLUS.code)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(clusErrorVOList)) {
                    Set<Long> customerIds = clusErrorVOList.stream().map(SimilarityErrorVO::getCustomerId).collect(Collectors.toSet());
                    if (!CollectionUtils.isEmpty(customerIds)) {
                        for (Long customerId : customerIds) {
                            assembleService.sendCustomerEventMessages(customerId, "DUPLICATE_WARNING_CLUS");

                        }
                    }
                }
                List<SimilarityErrorVO> liaisonErrorVOList = errorCanSaveVOList.stream().filter(e -> e.getResourceType().equals(ResourceTypeEnum.LIAISON.code)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(liaisonErrorVOList)) {
                    Set<Long> liaisonIds = liaisonErrorVOList.stream().map(SimilarityErrorVO::getErrorId).collect(Collectors.toSet());
                    for (Long liaisonId : liaisonIds) {
                        assembleService.sendLiaisonEventMessages(liaisonId, "DUPLICATE_WARNING_LIAISON");
                    }

                }
            }

            CustomerEntity customerNow = getById(customerEntity.getId());
            //添加归属记录
            CustomerOwnerRecordEntity customerOwnerRecord = new CustomerOwnerRecordEntity();
            customerOwnerRecord.setCustomerId(customerNow.getId());
            customerOwnerRecord.setNowOwnerBy(customerNow.getOwnerBy());
            customerOwnerRecord.setOperatingType(3);

            try {
                // 创建 Gson 实例
                Gson gson = new Gson();
                CustomerAllVO customerAllVO =new CustomerAllVO();
                BeanUtils.copyProperties(customerNow,customerAllVO);
                customerAllVO.setCustomerCompany(customerCompanyService.getByCustomerId(customerNow.getId()));
                // 将 CustomerEntity 对象转换为 JSON 字符串
                String jsonString = gson.toJson(customerAllVO);

                customerOwnerRecord.setCustomerDetail(jsonString);
            }catch (Exception e){
                return Result.error("客户数据更新异常");
            }

            customerOwnerService.save(customerOwnerRecord);



            if (Objects.nonNull(customerEntity)) {
                List<String> cmails = assembleCustomerMails(companyCompanyEntity);
                List<String> lmails = assembleLiaisonMails(liaisonEntity);
                Long customerId = Objects.nonNull(customerEntity) ? customerEntity.getId() : null;
                Long liasionId = Objects.nonNull(liaisonEntity) ? liaisonEntity.getId() : null;
                if (Objects.nonNull(customerId) || Objects.nonNull(liasionId)) {
                    customerMailBingMarkService.updateCustomerMailBingMark(customerId,cmails,liasionId,lmails);
                }
            }
            return Result.result(customerEntity.getId());
        }


        return Result.error("添加失败！");
    }

    /***
      * @Description: 如果触发查重，则发送查重消息
      * @Param:
      * @return:
      * @Author: YPZ
      * @Date: 2025/4/29 11:38
      */
    private void sendDuplicate(List<SimilarityErrorVO> errorCanSaveVOList) {
        if(CollectionUtils.isEmpty(errorCanSaveVOList)){
            return;
        }
        for (SimilarityErrorVO errorCanSaveVO : errorCanSaveVOList){
            if (errorCanSaveVO.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code)){
                CustomerEntity customer = getById(errorCanSaveVO.getErrorId());
                assembleService.sendCustomerEventMessages(errorCanSaveVO.getErrorId(),"DUPLICATE_WARNING_CUSTOMER",Set.of(customer.getOwnerBy()));
            }
            if (errorCanSaveVO.getResourceType().equals(ResourceTypeEnum.CLUS.code)){
                CustomerEntity customer = getById(errorCanSaveVO.getErrorId());
                assembleService.sendCustomerEventMessages(errorCanSaveVO.getErrorId(),"DUPLICATE_WARNING_CLUS",Set.of(customer.getOwnerBy()));
            }
            if (errorCanSaveVO.getResourceType().equals(ResourceTypeEnum.LIAISON.code)){
                LiaisonEntity liaison = liaisonService.getById(errorCanSaveVO.getErrorId());
               assembleService.sendLiaisonEventMessages(errorCanSaveVO.getErrorId(),"DUPLICATE_WARNING_LIAISON",Set.of(liaison.getOwnerBy()));
            }
        }
        //            assembleService.sendCustomerEventMessages(customerListVO.getCustomerId(),"DUPLICATE_WARNING_CUSTOMER",Set.of(customerListVO.getOwnerBy()));

    }


    @Override
    public Result<?> addCheck(CustomerAddDTO customerAddDTO) {
        if (ObjectUtils.isEmpty(customerAddDTO)) {
            return Result.error("参数不能为空");
        }

        if (!ObjectUtils.isEmpty(customerAddDTO.getTask())) {
            if (Boolean.TRUE.equals(customerAddDTO.getTask().getIsCreateTask())) {
                if (Objects.isNull(customerAddDTO.getTask().getTaskBeginTime())) {
                    return Result.error("请选择任务开始时间");
                }
            }
        }

        // 收集所有邮箱用于检查
        Set<String> companyEmails = new HashSet<>();
        Set<String> liaisonEmails = new HashSet<>();

        // 收集企业邮箱
        if (!ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())) {
            CustomerCompanyAddDTO company = customerAddDTO.getCustomerCompany();

            // 检查企业邮箱内部是否重复
            if (StrUtil.isNotBlank(company.getEmail())) {
                companyEmails.add(company.getEmail().toLowerCase());
            }
            if (StrUtil.isNotBlank(company.getEmail1())) {
                if (companyEmails.contains(company.getEmail1().toLowerCase())) {
                    return Result.error("企业邮箱重复: " + company.getEmail1());
                }
                companyEmails.add(company.getEmail1().toLowerCase());
            }
            if (StrUtil.isNotBlank(company.getEmail2())) {
                if (companyEmails.contains(company.getEmail2().toLowerCase())) {
                    return Result.error("企业邮箱重复: " + company.getEmail2());
                }
                companyEmails.add(company.getEmail2().toLowerCase());
            }
            if (StrUtil.isNotBlank(company.getEmail3())) {
                if (companyEmails.contains(company.getEmail3().toLowerCase())) {
                    return Result.error("企业邮箱重复: " + company.getEmail3());
                }
                companyEmails.add(company.getEmail3().toLowerCase());
            }
        }

        // 收集联系人邮箱
        if (!ObjectUtils.isEmpty(customerAddDTO.getLiaison())) {
            LiaisonAddDTO liaison = customerAddDTO.getLiaison();

            // 检查联系人邮箱内部是否重复
            if (StrUtil.isNotBlank(liaison.getEmail())) {
                String email = liaison.getEmail().toLowerCase();
                // 检查是否与企业邮箱重复
                if (companyEmails.contains(email)) {
                    return Result.error("联系人邮箱与企业邮箱重复: " + liaison.getEmail());
                }
                liaisonEmails.add(email);
            }
            if (StrUtil.isNotBlank(liaison.getEmail1())) {
                String email = liaison.getEmail1().toLowerCase();
                if (liaisonEmails.contains(email)) {
                    return Result.error("联系人邮箱重复: " + liaison.getEmail1());
                }
                if (companyEmails.contains(email)) {
                    return Result.error("联系人备用邮箱1与企业邮箱重复: " + liaison.getEmail1());
                }
                liaisonEmails.add(email);
            }
            if (StrUtil.isNotBlank(liaison.getEmail2())) {
                String email = liaison.getEmail2().toLowerCase();
                if (liaisonEmails.contains(email)) {
                    return Result.error("联系人邮箱重复: " + liaison.getEmail2());
                }
                if (companyEmails.contains(email)) {
                    return Result.error("联系人备用邮箱2与企业邮箱重复: " + liaison.getEmail2());
                }
                liaisonEmails.add(email);
            }
            if (StrUtil.isNotBlank(liaison.getEmail3())) {
                String email = liaison.getEmail3().toLowerCase();
                if (liaisonEmails.contains(email)) {
                    return Result.error("联系人邮箱重复: " + liaison.getEmail3());
                }
                if (companyEmails.contains(email)) {
                    return Result.error("联系人备用邮箱3与企业邮箱重复: " + liaison.getEmail3());
                }
                liaisonEmails.add(email);
            }
        }
        //是否是客户
        boolean isCustomer = true;
        if (ResourceTypeEnum.CLUS.code.equals(customerAddDTO.getCustomerForm().toString())) {
            isCustomer = false;
        }

        //判断是否公共客户/线索
        boolean hasPublicCustomer = false;
        if (ObjectUtils.isEmpty(customerAddDTO.getOwnerBy())) {
            hasPublicCustomer = true;
        }
        // 获取旧VO对象
        CustomerAllVO customerAllVO = null;
        if (Objects.nonNull(customerAddDTO.getId())) {
            CustomerSearchDTO customerSearchDTO = new CustomerSearchDTO();
            customerSearchDTO.setId(customerAddDTO.getId());
            customerAllVO = this.getCustomerAllVOById(customerSearchDTO);
        }
        //查询写入规则
//        if (!ObjectUtils.isEmpty(customerAddDTO.getOwnerBy())) {
        LambdaQueryWrapper<SystemRuleModuleConfigEntity> sysWrapper = new LambdaQueryWrapper<>();
        if (!isCustomer) {
            //线索规则
            sysWrapper.eq(SystemRuleModuleConfigEntity::getResourceType, customerAddDTO.getCustomerForm().toString());
            sysWrapper.last("limit 1");
            SystemRuleModuleConfigEntity systemRuleModuleConfig = systemRuleModuleConfigService.getOne(sysWrapper);
//            if (!hasPublicCustomer) {
//                if (systemRuleModuleConfig.getHasMaxMember()) {
//                    //查询当前用户是否超过上限
//                    LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
//                    wrapper.eq(CustomerEntity::getOwnerBy, customerAddDTO.getOwnerBy());
//                    wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(ResourceTypeEnum.CLUS.code));
//                    wrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerEntity::getId, customerAddDTO.getId());
//                    wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
//                    Integer customerCount = count(wrapper);
//                    if (customerCount >= systemRuleModuleConfig.getMaxMemberNum()) {
//                        return Result.error("线索数量超过上限");
//                    }
//                }
//            }

            //验证规则
            if (systemRuleModuleConfig.getHasPlagiarismRules()) {


                List<FieldSimilarityConfigVO> rules = JSON.parseArray(systemRuleModuleConfig.getPlagiarismRules(), FieldSimilarityConfigVO.class);
                if (CollectionUtils.isEmpty(rules)){
                    return Result.ok();
                }

                List<SimilarityErrorVO> errorCanSaveVOList= new ArrayList<>();
                List<SimilarityErrorVO> errorVOList= new ArrayList<>();
                for (FieldSimilarityConfigVO rule : rules){
                    BigDecimal similarityValue = rule.getSimilarityValue().divide(new BigDecimal(100));
                    if (rule.getFieldCode().equals("customerName") && !ObjectUtils.isEmpty(customerAddDTO.getCustomerName())){
                        //验证线索名称重复
                        List<EsQuerySimilarityVO> customerErrList = findErrList("name",customerAddDTO.getId(), customerAddDTO.getCustomerName(),"线索名称",11,rule.getSimilarityValue());
                        changeErrorList(customerErrList,errorVOList,errorCanSaveVOList,rule);
                    }
                    if (rule.getFieldCode().equals("customerCompany.website") && !ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())){
                        //验证企业网址重复
                        if (checkWebsiteDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getWebsite(), "企业网址", errorCanSaveVOList, errorVOList, 11, similarityValue, customerAddDTO.getCustomerCompany().getWebsite())){
                            if (checkWebsiteDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getWebsite1(), "企业备用网址1", errorCanSaveVOList, errorVOList, 11, similarityValue, customerAddDTO.getCustomerCompany().getWebsite1())){
                                if (checkWebsiteDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getWebsite2(), "企业备用网址2", errorCanSaveVOList, errorVOList, 11, similarityValue, customerAddDTO.getCustomerCompany().getWebsite2())){
                                    checkWebsiteDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getWebsite3(), "企业备用网址3", errorCanSaveVOList, errorVOList, 11, similarityValue, customerAddDTO.getCustomerCompany().getWebsite3());
                                }
                            }
                        }
                    }
                    if (rule.getFieldCode().equals("customerCompany.email") && !ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())){
                        //验证企业邮箱重复
                        if (checkCompanyEmailDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getEmail(), "企业邮箱", errorCanSaveVOList, errorVOList, 11, similarityValue, customerAddDTO.getCustomerCompany().getEmail())){
                            if (checkCompanyEmailDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getEmail1(), "企业备用邮箱1", errorCanSaveVOList, errorVOList, 11, similarityValue, customerAddDTO.getCustomerCompany().getEmail1())){
                                if (checkCompanyEmailDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getEmail2(), "企业备用邮箱2", errorCanSaveVOList, errorVOList, 11, similarityValue, customerAddDTO.getCustomerCompany().getEmail2())){
                                    checkCompanyEmailDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getEmail3(), "企业备用邮箱3", errorCanSaveVOList, errorVOList, 11, similarityValue, customerAddDTO.getCustomerCompany().getEmail3());
                                }
                            }
                        }
                    }

                    if (rule.getFieldCode().equals("liaison.email") && !ObjectUtils.isEmpty(customerAddDTO.getLiaison())){
                        //验证联系人邮箱重复
                        if (checkEmailDuplicates(customerAddDTO, rule, customerAddDTO.getLiaison().getEmail(), "联系人邮箱", errorCanSaveVOList, errorVOList, 20, similarityValue, customerAddDTO.getLiaison().getEmail())){
                            if (checkEmailDuplicates(customerAddDTO, rule, customerAddDTO.getLiaison().getEmail1(), "联系人备用邮箱1", errorCanSaveVOList, errorVOList, 20, similarityValue, customerAddDTO.getLiaison().getEmail1())){
                                if (checkEmailDuplicates(customerAddDTO, rule, customerAddDTO.getLiaison().getEmail2(), "联系人备用邮箱2", errorCanSaveVOList, errorVOList, 20, similarityValue, customerAddDTO.getLiaison().getEmail2())){
                                    checkEmailDuplicates(customerAddDTO, rule, customerAddDTO.getLiaison().getEmail3(), "联系人备用邮箱3", errorCanSaveVOList, errorVOList, 20, similarityValue, customerAddDTO.getLiaison().getEmail3());
                                }
                            }
                        }
                    }
                }

                if (!CollectionUtils.isEmpty(errorVOList)){
                    SysBaseField.orgFileds(errorVOList);
                    for (SimilarityErrorVO errorVO : errorVOList){
                        if (errorVO.getResourceType().equals(ResourceTypeEnum.LIAISON.code) && !ObjectUtils.isEmpty(errorVO.getCustomerId())){
                            CustomerEntity customer = getById(errorVO.getCustomerId());
                            errorVO.setCustomerName(customer.getCustomerName());
                            errorVO.setResourceType(customer.getCustomerForm().toString());
                        }
                    }
                    Result result = new Result();
                    result.setSuccess(false);
                    result.setCode(ResultCode.SUCCESS.getCode());
                    result.setResult(errorVOList);
                    return result;
                }
                if (!CollectionUtils.isEmpty(errorCanSaveVOList)){
                    SysBaseField.orgFileds(errorCanSaveVOList);
                    for (SimilarityErrorVO errorVO : errorCanSaveVOList){
                        if (errorVO.getResourceType().equals(ResourceTypeEnum.LIAISON.code) && !ObjectUtils.isEmpty(errorVO.getCustomerId())){
                            CustomerEntity customer = getById(errorVO.getCustomerId());
                            errorVO.setCustomerName(customer.getCustomerName());
                            errorVO.setResourceType(customer.getCustomerForm().toString());
                        }
                    }
                    return Result.result(errorCanSaveVOList);
                }


            }
        } else {
            //客户规则
            sysWrapper.eq(SystemRuleModuleConfigEntity::getResourceType, customerAddDTO.getCustomerForm().toString());
            sysWrapper.last("limit 1");
            SystemRuleModuleConfigEntity systemRuleModuleConfig = systemRuleModuleConfigService.getOne(sysWrapper);
//            if (!hasPublicCustomer) {
//                if (Objects.nonNull(systemRuleModuleConfig) && systemRuleModuleConfig.getHasMaxMember()) {
//                    //查询当前用户是否超过上限
//                    LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
//                    wrapper.eq(CustomerEntity::getOwnerBy, customerAddDTO.getOwnerBy());
//                    wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(ResourceTypeEnum.CUSTOMER.code));
//                    wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
//                    wrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerEntity::getId, customerAddDTO.getId());
//                    Integer customerCount = count(wrapper);
//                    if (customerCount >= systemRuleModuleConfig.getMaxMemberNum()) {
//                        return Result.error("客户数量超过上限");
//                    }
//                }
//            }

            //验证规则
            if (Objects.nonNull(systemRuleModuleConfig) && systemRuleModuleConfig.getHasPlagiarismRules()) {


                List<FieldSimilarityConfigVO> rules = JSON.parseArray(systemRuleModuleConfig.getPlagiarismRules(), FieldSimilarityConfigVO.class);
                if (CollectionUtils.isEmpty(rules)){
                    return Result.ok();
                }

                List<SimilarityErrorVO> errorCanSaveVOList= new ArrayList<>();
                List<SimilarityErrorVO> errorVOList= new ArrayList<>();
                for (FieldSimilarityConfigVO rule : rules){
                    BigDecimal similarityValue = rule.getSimilarityValue().divide(new BigDecimal(100));
                    if (rule.getFieldCode().equals("customerName") && !ObjectUtils.isEmpty(customerAddDTO.getCustomerName())){
                        //验证客户名称重复
                        List<EsQuerySimilarityVO> customerErrList = findErrList("name",customerAddDTO.getId(), customerAddDTO.getCustomerName(),"客户名称",10,rule.getSimilarityValue());
                        changeErrorList(customerErrList,errorVOList,errorCanSaveVOList,rule);
                    }
                    if (rule.getFieldCode().equals("customerCompany.website") && !ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())){
                        //验证企业网址重复
                        if (checkWebsiteDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getWebsite(), "企业网址", errorCanSaveVOList, errorVOList, 10, similarityValue, customerAddDTO.getCustomerCompany().getWebsite())){
                            if (checkWebsiteDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getWebsite1(), "企业备用网址1", errorCanSaveVOList, errorVOList, 10, similarityValue, customerAddDTO.getCustomerCompany().getWebsite1())){
                                if (checkWebsiteDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getWebsite2(), "企业备用网址2", errorCanSaveVOList, errorVOList, 10, similarityValue, customerAddDTO.getCustomerCompany().getWebsite2())){
                                    checkWebsiteDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getWebsite3(), "企业备用网址3", errorCanSaveVOList, errorVOList, 10, similarityValue, customerAddDTO.getCustomerCompany().getWebsite3());
                                }
                            }
                        }
                    }
                    if (rule.getFieldCode().equals("customerCompany.email") && !ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())){
                        //验证企业邮箱
                        if (checkCompanyEmailDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getEmail(), "企业邮箱", errorCanSaveVOList, errorVOList, 10, similarityValue, customerAddDTO.getCustomerCompany().getEmail())){
                            if (checkCompanyEmailDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getEmail1(), "企业备用邮箱1", errorCanSaveVOList, errorVOList, 10, similarityValue, customerAddDTO.getCustomerCompany().getEmail1())){
                                if (checkCompanyEmailDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getEmail2(), "企业备用邮箱2", errorCanSaveVOList, errorVOList, 10, similarityValue, customerAddDTO.getCustomerCompany().getEmail2())){
                                    checkCompanyEmailDuplicates(customerAddDTO, rule, customerAddDTO.getCustomerCompany().getEmail3(), "企业备用邮箱3", errorCanSaveVOList, errorVOList, 10, similarityValue, customerAddDTO.getCustomerCompany().getEmail3());
                                }
                            }
                        }
                    }

                    if (rule.getFieldCode().equals("liaison.email") && !ObjectUtils.isEmpty(customerAddDTO.getLiaison())){
                        //验证联系人邮箱
                        if (checkEmailDuplicates(customerAddDTO, rule, customerAddDTO.getLiaison().getEmail(), "联系人邮箱", errorCanSaveVOList, errorVOList, 20, similarityValue, customerAddDTO.getLiaison().getEmail())){
                            if (checkEmailDuplicates(customerAddDTO, rule, customerAddDTO.getLiaison().getEmail1(), "联系人备用邮箱1", errorCanSaveVOList, errorVOList, 20, similarityValue, customerAddDTO.getLiaison().getEmail1())){
                                if (checkEmailDuplicates(customerAddDTO, rule, customerAddDTO.getLiaison().getEmail2(), "联系人备用邮箱2", errorCanSaveVOList, errorVOList, 20, similarityValue, customerAddDTO.getLiaison().getEmail2())){
                                    checkEmailDuplicates(customerAddDTO, rule, customerAddDTO.getLiaison().getEmail3(), "联系人备用邮箱3", errorCanSaveVOList, errorVOList, 20, similarityValue, customerAddDTO.getLiaison().getEmail3());
                                }
                            }
                        }
                    }
                }

                if (!CollectionUtils.isEmpty(errorVOList)){
                    SysBaseField.orgFileds(errorVOList);
                    for (SimilarityErrorVO errorVO : errorVOList){
                        if (errorVO.getResourceType().equals(ResourceTypeEnum.LIAISON.code) && !ObjectUtils.isEmpty(errorVO.getCustomerId())){
                            CustomerEntity customer = getById(errorVO.getCustomerId());
                            errorVO.setCustomerName(customer.getCustomerName());
                            errorVO.setResourceType(customer.getCustomerForm().toString());
                        }
                    }

                    Result result = new Result();
                    result.setSuccess(false);
                    result.setCode(ResultCode.SUCCESS.getCode());
                    result.setResult(errorVOList);
                    return result;
                }
                if (!CollectionUtils.isEmpty(errorCanSaveVOList)){
                    SysBaseField.orgFileds(errorCanSaveVOList);
                    for (SimilarityErrorVO errorVO : errorCanSaveVOList){
                        if (errorVO.getResourceType().equals(ResourceTypeEnum.LIAISON.code) && !ObjectUtils.isEmpty(errorVO.getCustomerId())){
                            CustomerEntity customer = getById(errorVO.getCustomerId());
                            errorVO.setCustomerName(customer.getCustomerName());
                            errorVO.setResourceType(customer.getCustomerForm().toString());
                        }
                    }
                    return Result.result(errorCanSaveVOList);
                }
            }
        }

        return Result.ok();
    }

    private void changeErrorList(List<EsQuerySimilarityVO> customerErrList, List<SimilarityErrorVO> errorVOList, List<SimilarityErrorVO> errorCanSaveVOList, FieldSimilarityConfigVO rule) {
        if (!CollectionUtils.isEmpty(customerErrList)) {
            //复制list给VO类
            List<SimilarityErrorVO> similarityErrorVOList = new ArrayList();
            for (EsQuerySimilarityVO customerErr : customerErrList){
                SimilarityErrorVO similarityErrorVO = new SimilarityErrorVO();
                BeanUtils.copyProperties(customerErr,similarityErrorVO);
                similarityErrorVO.setCanSave(rule.getCanSave());
                similarityErrorVO.setErrorId(customerErr.getId());
                similarityErrorVOList.add(similarityErrorVO);
            }
            if (rule.getCanSave()){
                errorCanSaveVOList.addAll(similarityErrorVOList);
            }else {
                errorVOList.addAll(similarityErrorVOList);
            }
        }
    }

    private List<EsQuerySimilarityVO> findErrList(String keyword,Long customerId, String queryText,String fieldText, Integer resourceType, BigDecimal similarityValue) {
        String sql = "";
        String evn = this.environment;
        if(evn.equals("prod")){
            evn = "";
        }else {
            evn = "test_";
        }
//        List<CustomerCompanyListVO> list = new ArrayList();
        List<EsQuerySimilarityVO> esList = new ArrayList();
        if (keyword.equals("name")){
            sql = header+name;
            sql=sql.replace("${resourceType}", resourceType.toString())
            .replace("${environment}", evn)
            .replace("${queryText}", queryText)
            .replace("${minScore}", similarityValue.toString());
            if (resourceType.toString().equals(ResourceTypeEnum.CLUS.code)){
                sql=sql.replace("${customerTypeName}", "线索名称");
            }else {
                sql=sql.replace("${customerTypeName}", "客户名称");
            }
        }
        if (keyword.equals("website")){
            sql = header+website;
            sql=sql.replace("${resourceType}", resourceType.toString())
                    .replace("${environment}", evn)
                    .replace("${queryText}", queryText)
                    .replace("${minScore}", similarityValue.toString());
        }
        if (keyword.equals("email")){
            sql = header+email;
            sql=sql.replace("${resourceType}", resourceType.toString())
                    .replace("${environment}", evn)
                    .replace("${environment}", evn)
                    .replace("${queryText}", queryText)
                    .replace("${minScore}", similarityValue.toString());
        }
        if (StringUtils.isEmpty(sql)){
            return esList;
        }
        Gson gson = new Gson();
        EsGenericVO vo = gson.fromJson(sql, EsGenericVO.class);
        if (!ObjectUtils.isEmpty(vo) && keyword.equals("name")){
            vo.setCustomerForm(resourceType);
        }
        esList = searchCustomerService.listComparisonSimilarity(vo);
        List<EsQuerySimilarityVO> esListNew = new ArrayList();
        if (ObjectUtils.isEmpty(customerId)){
            esListNew = esList;
        }
        if (!CollectionUtils.isEmpty(esList) && !ObjectUtils.isEmpty(customerId)){
            for (EsQuerySimilarityVO es: esList){
                if (ObjectUtils.isEmpty(es.getCustomerId()) || !es.getCustomerId().equals(customerId)){
                    esListNew.add(es);
                }
            }
//            esList = esList.stream().filter(e -> !e.getCustomerId().equals(customerId)).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(esListNew)){
            Set<Long> customerIds = esListNew.stream().map(e -> e.getCustomerId()).collect(Collectors.toSet());
            Map<Long,  CustomerEntity> customerMap = baseMapper.selectList(new LambdaQueryWrapper<CustomerEntity>().in(CustomerEntity::getId, customerIds)).stream().collect(Collectors.toMap(CustomerEntity::getId, e -> e));
            for (EsQuerySimilarityVO es: esListNew){
                if (!ObjectUtils.isEmpty(customerMap.containsKey(es.getCustomerId())) && customerMap.containsKey(es.getCustomerId())){
                    es.setCustomerName(customerMap.get(es.getCustomerId()).getCustomerName());
                    es.setLastFollowUpTime(customerMap.get(es.getCustomerId()).getLastFollowUpTime());
                    es.setNoFollowUpDate(customerMap.get(es.getCustomerId()).getNoFollowUpDate());
                    es.setCreateTime(customerMap.get(es.getCustomerId()).getCreateTime());
                    es.setResourceType(customerMap.get(es.getCustomerId()).getCustomerForm().toString());
                }
                if(es.getResourceType().equals(ResourceTypeEnum.LIAISON.code)){
                    LiaisonEntity liaison = liaisonService.getById(es.getId());
                    es.setName(liaison.getName());
                    es.setCreateTime(liaison.getCreateTime());
                    if (ObjectUtils.isEmpty(es.getCustomerId())){
                        es.setCustomerName(liaison.getName());
                    }

                }
                es.setDuplicateFieldNow(fieldText);
                es.setDuplicateValueNow(queryText);

            }
        }

        return esListNew;
    }


    @Override
    public Result<?> addCheckNew(CustomerAddDTO customerAddDTO) {
        if (ObjectUtils.isEmpty(customerAddDTO)) {
            return Result.error("参数不能为空");
        }

        if (!ObjectUtils.isEmpty(customerAddDTO.getTask())) {
            if (Boolean.TRUE.equals(customerAddDTO.getTask().getIsCreateTask())) {
                if (Objects.isNull(customerAddDTO.getTask().getTaskBeginTime())) {
                    return Result.error("请选择任务开始时间");
                }
            }
        }
        //是否是客户
        boolean isCustomer = true;
        if (ResourceTypeEnum.CLUS.code.equals(customerAddDTO.getCustomerForm().toString())) {
            isCustomer = false;
        }

        //判断是否公共客户/线索
        boolean hasPublicCustomer = false;
        if (ObjectUtils.isEmpty(customerAddDTO.getOwnerBy())) {
            hasPublicCustomer = true;
        }
        // 获取旧VO对象
        CustomerAllVO customerAllVO = null;
        if (Objects.nonNull(customerAddDTO.getId())) {
            CustomerSearchDTO customerSearchDTO = new CustomerSearchDTO();
            customerSearchDTO.setId(customerAddDTO.getId());
            customerAllVO = this.getCustomerAllVOById(customerSearchDTO);
        }
        //查询写入规则
//        if (!ObjectUtils.isEmpty(customerAddDTO.getOwnerBy())) {
        LambdaQueryWrapper<SystemRuleModuleConfigEntity> sysWrapper = new LambdaQueryWrapper<>();
        if (!isCustomer) {
            //线索规则
            sysWrapper.eq(SystemRuleModuleConfigEntity::getResourceType, customerAddDTO.getCustomerForm().toString());
            sysWrapper.last("limit 1");
            SystemRuleModuleConfigEntity systemRuleModuleConfig = systemRuleModuleConfigService.getOne(sysWrapper);
            if (!hasPublicCustomer) {
                if (systemRuleModuleConfig.getHasMaxMember()) {
                    //查询当前用户是否超过上限
                    LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(CustomerEntity::getOwnerBy, customerAddDTO.getOwnerBy());
                    wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(ResourceTypeEnum.CLUS.code));
                    wrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerEntity::getId, customerAddDTO.getId());
                    wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                    Integer customerCount = count(wrapper);
                    if (customerCount >= systemRuleModuleConfig.getMaxMemberNum()) {
                        return Result.error("线索数量超过上限");
                    }
                }
            }

            //验证规则
            if (systemRuleModuleConfig.getHasPlagiarismRules()) {


                LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
//                    wrapper.eq(CustomerEntity::getOwnerBy, customerAddDTO.getOwnerBy());
                wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(ResourceTypeEnum.CLUS.code));
                wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                wrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerEntity::getId, customerAddDTO.getId());
                List<CustomerEntity> customerEntities = list(wrapper);
                SysBaseField.orgFileds(customerEntities);
                SysBaseField.dictFileds(customerEntities);


                if (!CollectionUtils.isEmpty(customerEntities)) {
                    DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
                    List<CustomerListVO> customerListVO = mapperFactory.getMapperFacade().mapAsList(customerEntities,CustomerListVO.class);
                    customerListVO.forEach(customerListVO1 -> {
                        //补充最后跟进时间及未跟进时长
                        Integer notFollowUpDate = 0;
                        if (!ObjectUtils.isEmpty(customerListVO1.getLastFollowUpTime())) {
                            notFollowUpDate = Integer.valueOf((int) ChronoUnit.DAYS.between(customerListVO1.getLastFollowUpTime(), LocalDateTime.now()));
                            if (notFollowUpDate < 0) {
                                notFollowUpDate = 0;
                            }
                        }
                        customerListVO1.setNotFollowUpDate(notFollowUpDate);
                        customerListVO1.setResourceType(ResourceTypeEnum.CUSTOMER.code);
                    });
                    SysBaseField.orgFileds(customerListVO);
                    SysBaseField.dictFileds(customerListVO);

                    List<FieldSimilarityConfigVO> rules = JSON.parseArray(systemRuleModuleConfig.getPlagiarismRules(), FieldSimilarityConfigVO.class);

                    if (!CollectionUtils.isEmpty(rules)) {
                        List<SimilarityErrorVO> errorCanSaveVOList= new ArrayList<>();
                        List<SimilarityErrorVO> errorVOList= new ArrayList<>();
                        List<FieldSimilarityConfigVO> rulesC = rules.stream().filter(rule -> !rule.getFieldCode().contains(".")).collect(Collectors.toList());
                        if (Objects.nonNull(customerAllVO) && !CollectionUtils.isEmpty(rulesC)) {
                            Iterator<FieldSimilarityConfigVO> iterator = rulesC.iterator();
                            while (iterator.hasNext()) {
                                FieldSimilarityConfigVO rule = iterator.next();
                                try {
                                    String fieldCode = rule.getFieldCode();
                                    String newValue = String.valueOf(FieldUtils.readField(customerAddDTO,fieldCode, true));
                                    String oldValue = String.valueOf(FieldUtils.readField(customerAllVO,fieldCode, true));
                                    if (StrUtil.isNotBlank(newValue) && newValue.equals(oldValue)) {
                                        iterator.remove();
                                    }
                                }catch (Exception e1) {
                                    log.error("-------------error",e1);
                                }

                            }
                        }
                        Result<SimilarityCheckVo> canAddResultC = SystemRuleModuleUtils.checkFieldSimilarity(customerAddDTO, customerListVO, rulesC,ResourceTypeEnum.CUSTOMER.code);
                        //规则校验失败
                        if (!CollectionUtils.isEmpty(canAddResultC.getResult().getSimilarityErrors())) {
                            for (SimilarityErrorVO errorVO : canAddResultC.getResult().getSimilarityErrors()){
                                if (errorVO.getCanSave()){
                                    errorCanSaveVOList.add(errorVO);
                                }else {
                                    errorVOList.add(errorVO);
                                }
                            }
//                            errorVOList.addAll(canAddResultC.getResult().getSimilarityErrors());
                        }
                        if (!ObjectUtils.isEmpty(customerAddDTO.getLiaison())) {
                            LambdaQueryWrapper<LiaisonEntity> liaisonWrapper = new LambdaQueryWrapper<>();
                            liaisonWrapper.eq(LiaisonEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                            liaisonWrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getLiaison().getId()), LiaisonEntity::getId, customerAddDTO.getLiaison().getId());
                            List<LiaisonEntity> liaisonList = liaisonService.list(liaisonWrapper);
                            SysBaseField.orgFileds(liaisonList);
                            List<FieldSimilarityConfigVO> rulesL = rules.stream().filter(rule -> rule.getFieldCode().contains("liaison.")).collect(Collectors.toList());
                            for (FieldSimilarityConfigVO rule :rulesL){
                                if (Objects.nonNull(customerAllVO.getLiaison())) {
                                    try {
                                        String fieldCode = rule.getFieldCode();
                                        String newValue = String.valueOf(FieldUtils.readField(customerAddDTO.getLiaison(),fieldCode, true));
                                        String oldValue = String.valueOf(FieldUtils.readField(customerAllVO.getLiaison(),fieldCode, true));
                                        if (StrUtil.isNotBlank(newValue) && newValue.equals(oldValue)) {
                                            continue;
                                        }
                                    }catch (Exception e1) {
                                        log.error("-------------error",e1);
                                    }
                                }
                                rule.setFieldCode(rule.getFieldCode().replace("liaison.", ""));
                            }
                            if (!CollectionUtils.isEmpty(liaisonList) && !CollectionUtils.isEmpty(rulesL)){
                                List<LiaisonListVO> liaisonListVO = mapperFactory.getMapperFacade().mapAsList(liaisonList,LiaisonListVO.class);
                                liaisonListVO.forEach(liaisonListVO1 -> {
                                    //补充最后跟进时间及未跟进时长
                                    Integer notFollowUpDate = 0;
                                    if (!ObjectUtils.isEmpty(liaisonListVO1.getLastFollowUpTime())) {
                                        notFollowUpDate = Integer.valueOf((int) ChronoUnit.DAYS.between(liaisonListVO1.getLastFollowUpTime(), LocalDateTime.now()));
                                        if (notFollowUpDate < 0) {
                                            notFollowUpDate = 0;
                                        }
                                    }
                                    liaisonListVO1.setNotFollowUpDate(notFollowUpDate);
                                    liaisonListVO1.setResourceType(ResourceTypeEnum.LIAISON.code);
                                });

                                SysBaseField.orgFileds(liaisonListVO);
                                SysBaseField.dictFileds(liaisonListVO);
                                Result<SimilarityCheckVo> canAddResultL = SystemRuleModuleUtils.checkFieldSimilarity(customerAddDTO.getLiaison(), liaisonListVO, rulesL,ResourceTypeEnum.LIAISON.code);
                                if (!CollectionUtils.isEmpty(canAddResultL.getResult().getSimilarityErrors())) {
                                    for (SimilarityErrorVO errorVO : canAddResultL.getResult().getSimilarityErrors()){
                                        if (errorVO.getCanSave()){
                                            errorCanSaveVOList.add(errorVO);
                                        }else {
                                            errorVOList.add(errorVO);
                                        }
                                    }
//                                    errorVOList.addAll(canAddResultL.getResult().getSimilarityErrors());
                                }
                            }
                        }
                        if (!ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())) {
                            LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyWrapper = new LambdaQueryWrapper<>();
                            customerCompanyWrapper.eq(CustomerCompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                            customerCompanyWrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerCompanyEntity::getCustomerId, customerAddDTO.getId());
                            List<CustomerCompanyEntity> customerCompanyList = customerCompanyService.list(customerCompanyWrapper);
                            SysBaseField.orgFileds(customerCompanyList);
                            List<FieldSimilarityConfigVO> rulesCC = rules.stream().filter(rule -> rule.getFieldCode().contains("customerCompany.")).collect(Collectors.toList());

                            for (FieldSimilarityConfigVO rule :rulesCC){
                                if (Objects.nonNull(customerAllVO.getCustomerCompany())) {
                                    try {
                                        String fieldCode = rule.getFieldCode();
                                        String newValue = String.valueOf(FieldUtils.readField(customerAddDTO.getCustomerCompany(),fieldCode, true));
                                        String oldValue = String.valueOf(FieldUtils.readField(customerAllVO.getCustomerCompany(),fieldCode, true));
                                        if (StrUtil.isNotBlank(newValue) && newValue.equals(oldValue)) {
                                            continue;
                                        }
                                    }catch (Exception e1) {
                                        log.error("-------------error",e1);
                                    }
                                }
                                rule.setFieldCode(rule.getFieldCode().replace("customerCompany.", ""));
                            }
                            if (!CollectionUtils.isEmpty(customerCompanyList) && !CollectionUtils.isEmpty(rulesCC)){
                                Set<Long> customerIds = customerCompanyList.stream().map(CustomerCompanyEntity::getCustomerId).collect(Collectors.toSet());
                                Map<Long, CustomerEntity> customerListVOMap = getCustomerMap(customerIds);
                                List<CustomerCompanyListVO> customerCompanyListVOList = new ArrayList<>();
                                for (CustomerCompanyEntity customerCompanyEntity : customerCompanyList) {
                                    CustomerCompanyListVO customerCompanyListVO = new CustomerCompanyListVO();
                                    BeanUtils.copyProperties(customerListVOMap.get(customerCompanyEntity.getCustomerId()), customerCompanyListVO);
                                    customerCompanyListVO.setEmail(customerCompanyEntity.getEmail());
                                    customerCompanyListVO.setWebsite(customerCompanyEntity.getWebsite());
                                    //补充最后跟进时间及未跟进时长
                                    Integer notFollowUpDate = 0;
                                    if (!ObjectUtils.isEmpty(customerCompanyListVO.getLastFollowUpTime())) {
                                        notFollowUpDate = Integer.valueOf((int) ChronoUnit.DAYS.between(customerCompanyListVO.getLastFollowUpTime(), LocalDateTime.now()));
                                        if (notFollowUpDate < 0) {
                                            notFollowUpDate = 0;
                                        }
                                    }
                                    customerCompanyListVO.setNotFollowUpDate(notFollowUpDate);
                                    customerCompanyListVO.setResourceType(ResourceTypeEnum.CUSTOMER.code);
                                    customerCompanyListVOList.add(customerCompanyListVO);
                                }
                                SysBaseField.orgFileds(customerCompanyListVOList);
                                SysBaseField.dictFileds(customerCompanyListVOList);

                                Result<SimilarityCheckVo> canAddResultCC = SystemRuleModuleUtils.checkFieldSimilarity(customerAddDTO.getCustomerCompany(), customerCompanyListVOList, rulesCC,ResourceTypeEnum.CUSTOMER.code);
                                if (!CollectionUtils.isEmpty(canAddResultCC.getResult().getSimilarityErrors())) {
                                    for (SimilarityErrorVO errorVO : canAddResultCC.getResult().getSimilarityErrors()){
                                        if (errorVO.getCanSave()){
                                            errorCanSaveVOList.add(errorVO);
                                        }else {
                                            errorVOList.add(errorVO);
                                        }
                                    }
//                                    errorVOList.addAll(canAddResultCC.getResult().getSimilarityErrors());
                                }
                            }
                        }
                        if (!CollectionUtils.isEmpty(errorVOList)){

                            Result result = new Result();
                            result.setSuccess(false);
                            result.setCode(ResultCode.SUCCESS.getCode());
                            result.setResult(errorVOList);
                            return result;
                        }
                        if (!CollectionUtils.isEmpty(errorCanSaveVOList)){
//                            List<SimilarityErrorVO> customerErrorVOList = errorCanSaveVOList.stream().filter(e->e.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code)).collect(Collectors.toList());
//                            if (!CollectionUtils.isEmpty(customerErrorVOList)){
//                                Set<Long> customerIds = customerErrorVOList.stream().map(SimilarityErrorVO::getErrorId).collect(Collectors.toSet());
//                                for (Long customerId : customerIds){
//                                    assembleService.sendCustomerEventMessages(customerId,"DUPLICATE_WARNING_CLUS");
//                                }
//                            }
//                            List<SimilarityErrorVO> liaisonErrorVOList = errorCanSaveVOList.stream().filter(e->e.getResourceType().equals(ResourceTypeEnum.LIAISON.code)).collect(Collectors.toList());
//                            if (!CollectionUtils.isEmpty(liaisonErrorVOList)) {
//                                Set<Long> liaisonIds = liaisonErrorVOList.stream().map(SimilarityErrorVO::getErrorId).collect(Collectors.toSet());
//                                for (Long liaisonId : liaisonIds){
//                                    assembleService.sendLiaisonEventMessages(liaisonId,"DUPLICATE_WARNING_LIAISON");
//                                }
//
//                            }
                            return Result.result(errorCanSaveVOList);
                        }

                    }
                }
            }
        } else {
            //客户规则
            sysWrapper.eq(SystemRuleModuleConfigEntity::getResourceType, customerAddDTO.getCustomerForm().toString());
            sysWrapper.last("limit 1");
            SystemRuleModuleConfigEntity systemRuleModuleConfig = systemRuleModuleConfigService.getOne(sysWrapper);
            if (!hasPublicCustomer) {
                if (Objects.nonNull(systemRuleModuleConfig) && systemRuleModuleConfig.getHasMaxMember()) {
                    //查询当前用户是否超过上限
                    LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(CustomerEntity::getOwnerBy, customerAddDTO.getOwnerBy());
                    wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(ResourceTypeEnum.CUSTOMER.code));
                    wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                    wrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerEntity::getId, customerAddDTO.getId());
                    Integer customerCount = count(wrapper);
                    if (customerCount >= systemRuleModuleConfig.getMaxMemberNum()) {
                        return Result.error("客户数量超过上限");
                    }
                }
            }

            //验证规则
            if (Objects.nonNull(systemRuleModuleConfig) && systemRuleModuleConfig.getHasPlagiarismRules()) {
                LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
//                    wrapper.eq(CustomerEntity::getOwnerBy, customerAddDTO.getOwnerBy());
                wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(ResourceTypeEnum.CUSTOMER.code));
                wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                wrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerEntity::getId, customerAddDTO.getId());
                List<CustomerEntity> customerEntities = list(wrapper);
                SysBaseField.orgFileds(customerEntities);
                if (!CollectionUtils.isEmpty(customerEntities)) {
                    DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
                    List<CustomerListVO> customerListVO = mapperFactory.getMapperFacade().mapAsList(customerEntities,CustomerListVO.class);
                    customerListVO.forEach(customerListVO1 -> {
                        //补充最后跟进时间及未跟进时长
                        Integer notFollowUpDate = 0;
                        if (!ObjectUtils.isEmpty(customerListVO1.getLastFollowUpTime())) {
                            notFollowUpDate = Integer.valueOf((int) ChronoUnit.DAYS.between(customerListVO1.getLastFollowUpTime(), LocalDateTime.now()));
                            if (notFollowUpDate < 0) {
                                notFollowUpDate = 0;
                            }
                        }
                        customerListVO1.setNotFollowUpDate(notFollowUpDate);
                        customerListVO1.setResourceType(ResourceTypeEnum.CUSTOMER.code);
                    });
                    SysBaseField.orgFileds(customerListVO);
                    SysBaseField.dictFileds(customerListVO);
                    List<FieldSimilarityConfigVO> rules = JSON.parseArray(systemRuleModuleConfig.getPlagiarismRules(), FieldSimilarityConfigVO.class);
                    if (!CollectionUtils.isEmpty(rules)) {
                        List<SimilarityErrorVO> errorVOList= new ArrayList<>();
                        List<SimilarityErrorVO> errorCanSaveVOList= new ArrayList<>();
                        List<FieldSimilarityConfigVO> rulesC = rules.stream().filter(rule -> !rule.getFieldCode().contains(".")).collect(Collectors.toList());
                        if (Objects.nonNull(customerAllVO) && !CollectionUtils.isEmpty(rulesC)) {
                            Iterator<FieldSimilarityConfigVO> iterator = rulesC.iterator();
                            while (iterator.hasNext()) {
                                FieldSimilarityConfigVO rule = iterator.next();
                                try {
                                    String fieldCode = rule.getFieldCode();
                                    String newValue = String.valueOf(FieldUtils.readField(customerAddDTO,fieldCode, true));
                                    String oldValue = String.valueOf(FieldUtils.readField(customerAllVO,fieldCode, true));
                                    if (StrUtil.isNotBlank(newValue) && newValue.equals(oldValue)) {
                                        iterator.remove();
                                    }
                                }catch (Exception e1) {
                                    log.error("-------------error",e1);
                                }

                            }
                        }
                        Result<SimilarityCheckVo> canAddResultC = SystemRuleModuleUtils.checkFieldSimilarity(customerAddDTO, customerListVO, rulesC,ResourceTypeEnum.CUSTOMER.code);
                        //规则校验失败
                        if (Objects.nonNull(canAddResultC.getResult()) && !CollectionUtils.isEmpty(canAddResultC.getResult().getSimilarityErrors())) {
                            for (SimilarityErrorVO errorVO : canAddResultC.getResult().getSimilarityErrors()){
                                if (errorVO.getCanSave()){
                                    errorCanSaveVOList.add(errorVO);
                                }else {
                                    errorVOList.add(errorVO);
                                }
                            }
//                            errorVOList.addAll(canAddResultC.getResult().getSimilarityErrors());
                        }
                        if (!ObjectUtils.isEmpty(customerAddDTO.getLiaison())) {
                            LambdaQueryWrapper<LiaisonEntity> liaisonWrapper = new LambdaQueryWrapper<>();
                            liaisonWrapper.eq(LiaisonEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                            liaisonWrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getLiaison().getId()), LiaisonEntity::getId, customerAddDTO.getLiaison().getId());
                            List<LiaisonEntity> liaisonList = liaisonService.list(liaisonWrapper);
                            SysBaseField.orgFileds(liaisonList);
                            List<FieldSimilarityConfigVO> rulesL = rules.stream().filter(rule -> rule.getFieldCode().contains("liaison.")).collect(Collectors.toList());
                            for (FieldSimilarityConfigVO rule :rulesL){
                                if (Objects.nonNull(customerAllVO.getLiaison())) {
                                    try {
                                        String fieldCode = rule.getFieldCode();
                                        String newValue = String.valueOf(FieldUtils.readField(customerAddDTO.getLiaison(),fieldCode, true));
                                        String oldValue = String.valueOf(FieldUtils.readField(customerAllVO.getLiaison(),fieldCode, true));
                                        if (StrUtil.isNotBlank(newValue) && newValue.equals(oldValue)) {
                                            continue;
                                        }
                                    }catch (Exception e1) {
                                        log.error("-------------error",e1);
                                    }
                                }
                                rule.setFieldCode(rule.getFieldCode().replace("liaison.", ""));
                            }
                            if (!CollectionUtils.isEmpty(liaisonList) && !CollectionUtils.isEmpty(rulesL)){
                                List<LiaisonListVO> liaisonListVO = mapperFactory.getMapperFacade().mapAsList(liaisonList,LiaisonListVO.class);
                                liaisonListVO.forEach(liaisonListVO1 -> {
                                    //补充最后跟进时间及未跟进时长
                                    Integer notFollowUpDate = 0;
                                    if (!ObjectUtils.isEmpty(liaisonListVO1.getLastFollowUpTime())) {
                                        notFollowUpDate = Integer.valueOf((int) ChronoUnit.DAYS.between(liaisonListVO1.getLastFollowUpTime(), LocalDateTime.now()));
                                        if (notFollowUpDate < 0) {
                                            notFollowUpDate = 0;
                                        }
                                    }
                                    liaisonListVO1.setNotFollowUpDate(notFollowUpDate);
                                    liaisonListVO1.setResourceType(ResourceTypeEnum.LIAISON.code);
                                });
                                SysBaseField.orgFileds(liaisonListVO);
                                SysBaseField.dictFileds(liaisonListVO);
                                Result<SimilarityCheckVo> canAddResultL = SystemRuleModuleUtils.checkFieldSimilarity(customerAddDTO.getLiaison(), liaisonListVO, rulesL,ResourceTypeEnum.LIAISON.code);
                                if (!CollectionUtils.isEmpty(canAddResultL.getResult().getSimilarityErrors())) {
                                    for (SimilarityErrorVO errorVO : canAddResultL.getResult().getSimilarityErrors()){
                                        if (errorVO.getCanSave()){
                                            errorCanSaveVOList.add(errorVO);
                                        }else {
                                            errorVOList.add(errorVO);
                                        }
                                    }
//                                    errorVOList.addAll(canAddResultL.getResult().getSimilarityErrors());
                                }
                            }
                        }
                        if (!ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())) {
                            LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyWrapper = new LambdaQueryWrapper<>();
                            customerCompanyWrapper.eq(CustomerCompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                            customerCompanyWrapper.ne(!ObjectUtils.isEmpty(customerAddDTO.getId()), CustomerCompanyEntity::getCustomerId, customerAddDTO.getId());
                            List<CustomerCompanyEntity> customerCompanyList = customerCompanyService.list(customerCompanyWrapper);
                            SysBaseField.orgFileds(customerCompanyList);
                            List<FieldSimilarityConfigVO> rulesCC = rules.stream().filter(rule -> rule.getFieldCode().contains("customerCompany.")).collect(Collectors.toList());

                            for (FieldSimilarityConfigVO rule :rulesCC){
                                if (Objects.nonNull(customerAllVO.getCustomerCompany())) {
                                    try {
                                        String fieldCode = rule.getFieldCode();
                                        String newValue = String.valueOf(FieldUtils.readField(customerAddDTO.getCustomerCompany(),fieldCode, true));
                                        String oldValue = String.valueOf(FieldUtils.readField(customerAllVO.getCustomerCompany(),fieldCode, true));
                                        if (StrUtil.isNotBlank(newValue) && newValue.equals(oldValue)) {
                                            continue;
                                        }
                                    }catch (Exception e1) {
                                        log.error("-------------error",e1);
                                    }
                                }
                                rule.setFieldCode(rule.getFieldCode().replace("customerCompany.", ""));
                            }
                            if (!CollectionUtils.isEmpty(customerCompanyList) && !CollectionUtils.isEmpty(rulesCC)){
                                Set<Long> customerIds = customerCompanyList.stream().map(CustomerCompanyEntity::getCustomerId).collect(Collectors.toSet());
                                Map<Long, CustomerEntity> customerListVOMap = getCustomerMap(customerIds);
                                List<CustomerCompanyListVO> customerCompanyListVOList = new ArrayList<>();
                                for (CustomerCompanyEntity customerCompanyEntity : customerCompanyList) {
                                    CustomerCompanyListVO customerCompanyListVO = new CustomerCompanyListVO();
                                    BeanUtils.copyProperties(customerListVOMap.get(customerCompanyEntity.getCustomerId()), customerCompanyListVO);
                                    customerCompanyListVO.setEmail(customerCompanyEntity.getEmail());
                                    customerCompanyListVO.setWebsite(customerCompanyEntity.getWebsite());
                                    //补充最后跟进时间及未跟进时长
                                    Integer notFollowUpDate = 0;
                                    if (!ObjectUtils.isEmpty(customerCompanyListVO.getLastFollowUpTime())) {
                                        notFollowUpDate = Integer.valueOf((int) ChronoUnit.DAYS.between(customerCompanyListVO.getLastFollowUpTime(), LocalDateTime.now()));
                                        if (notFollowUpDate < 0) {
                                            notFollowUpDate = 0;
                                        }
                                    }
                                    customerCompanyListVO.setNotFollowUpDate(notFollowUpDate);
                                    SysBaseField.orgFileds(customerCompanyListVO);
                                    customerCompanyListVO.setResourceType(ResourceTypeEnum.CUSTOMER.code);

                                    customerCompanyListVOList.add(customerCompanyListVO);
                                }
                                SysBaseField.orgFileds(customerCompanyListVOList);
                                SysBaseField.dictFileds(customerCompanyListVOList);

                                Result<SimilarityCheckVo> canAddResultCC = SystemRuleModuleUtils.checkFieldSimilarity(customerAddDTO.getCustomerCompany(), customerCompanyListVOList, rulesCC,ResourceTypeEnum.CUSTOMER.code);
                                if (!CollectionUtils.isEmpty(canAddResultCC.getResult().getSimilarityErrors())) {
                                    for (SimilarityErrorVO errorVO : canAddResultCC.getResult().getSimilarityErrors()){
                                        if (errorVO.getCanSave()){
                                            errorCanSaveVOList.add(errorVO);
                                        }else {
                                            errorVOList.add(errorVO);
                                        }
                                    }
//                                    errorVOList.addAll(canAddResultCC.getResult().getSimilarityErrors());
                                }
                            }
                        }
                        if (!CollectionUtils.isEmpty(errorVOList)){
                            Result result = new Result();
                            result.setSuccess(false);
                            result.setCode(ResultCode.SUCCESS.getCode());
                            result.setResult(errorVOList);
                            return result;
                        }
                        if (!CollectionUtils.isEmpty(errorCanSaveVOList)){
                            return Result.result(errorCanSaveVOList);
                        }

                    }
                }
            }
        }

        return Result.ok();
    }
    @Override
    public Result<?> editCustomer(CustomerAddDTO customerAddDTO) {
        if (ObjectUtils.isEmpty(customerAddDTO)){
            return Result.error("参数不能为空");
        }

        boolean isCustomer = true;
        if (ResourceTypeEnum.CLUS.code.equals(customerAddDTO.getCustomerForm().toString())){
            isCustomer = false;
        }
        CustomerEntity customerOld = getById(customerAddDTO.getId());
        CustomerEntity customerEntity = new CustomerEntity();
        CustomerCompanyEntity oldCompany = null;
        LiaisonEntity oldLiaison = null;

        BeanUtils.copyProperties(customerAddDTO, customerEntity);
        if (!ObjectUtils.isEmpty(customerEntity.getOwnerBy())){
            if (!customerEntity.getOwnerBy().equals(customerOld.getOwnerBy()) || ObjectUtils.isEmpty(customerOld.getOwnerBy())){
                customerEntity.setOwnerTime(LocalDateTime.now());
                customerEntity.setFormerOwnerBy(customerOld.getOwnerBy());
            }
        }

        boolean isOk = updateById(customerEntity);
        if (isOk){
            CustomerCompanyEntity companyCompanyOld = customerCompanyService.getOne(new LambdaQueryWrapper<CustomerCompanyEntity>().eq(CustomerCompanyEntity::getCustomerId,customerEntity.getId()).eq(CustomerCompanyEntity::getIsDelete,CommonConstant.DEL_FLAG_0).last("limit 1"));
            if (ObjectUtils.isEmpty(companyCompanyOld)){
                companyCompanyOld = new CustomerCompanyEntity();
                companyCompanyOld.setCustomerId(customerEntity.getId());
                customerCompanyService.save(companyCompanyOld);
            }
            CustomerCompanyEntity companyCompanyEntity = new CustomerCompanyEntity();
            if (!ObjectUtils.isEmpty(customerAddDTO.getCustomerCompany())) {
                BeanUtils.copyProperties(customerAddDTO.getCustomerCompany(), companyCompanyEntity);
            }

            if (Objects.nonNull(companyCompanyEntity.getId())) {
                oldCompany = customerCompanyService.getByCustomerId(customerAddDTO.getId());
            }
            LambdaUpdateWrapper<CustomerCompanyEntity> customerCompanyUpdateWrapper = new LambdaUpdateWrapper<>();
            customerCompanyUpdateWrapper.eq(CustomerCompanyEntity::getCustomerId, customerEntity.getId());
            customerCompanyService.update(companyCompanyEntity,customerCompanyUpdateWrapper);
            // 发送消息
            assembleService.sendCustomerEventMessages(customerEntity.getId(), "DATA_CHANGE");
            LiaisonEntity liaisonEntity = new LiaisonEntity();
            if (!ObjectUtils.isEmpty(customerAddDTO.getLiaison())) {
                BeanUtils.copyProperties(customerAddDTO.getLiaison(), liaisonEntity);
                if (ObjectUtils.isEmpty(liaisonEntity.getId())){
                    liaisonService.save(liaisonEntity);
                }else {
                    if (Objects.nonNull(customerAddDTO.getLiaison().getId())) {
                        oldLiaison = liaisonService.getById(liaisonEntity.getId());
                    }
                    liaisonService.updateById(liaisonEntity);
                }
            }

            if (!ObjectUtils.isEmpty(customerAddDTO.getTask())){
                customerAddDTO.getTask().setResourceType(ResourceTypeEnum.CUSTOMER.code);
                customerAddDTO.getTask().setResourceTypeId(customerAddDTO.getId());
                taskService.addTask(customerAddDTO.getTask().setCustomerId(customerEntity.getId()));
            }
            //添加附件
            if (!CollectionUtils.isEmpty(customerAddDTO.getResourceIdList())){
                sysResourceService.updateResourceById(customerEntity.getId(),ResourceTypeEnum.CUSTOMER.code,customerEntity.getId(),customerAddDTO.getResourceIdList());
            }


            if (ObjectUtils.isEmpty(customerAddDTO.getOwnerBy())){
                LambdaUpdateWrapper<CustomerEntity> customerEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                customerEntityLambdaUpdateWrapper.eq(CustomerEntity::getId,customerEntity.getId());
                customerEntityLambdaUpdateWrapper.set(CustomerEntity::getOwnerBy, null);
                update(customerEntityLambdaUpdateWrapper);
            }

            List<SimilarityErrorVO>  errorCanSaveVOList = customerAddDTO.getErrorCanSaveVOList();
            if (!CollectionUtils.isEmpty(errorCanSaveVOList)) {
                List<SimilarityErrorVO> customerErrorVOList = errorCanSaveVOList.stream().filter(e -> e.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(customerErrorVOList)) {
                    Set<Long> customerIds = customerErrorVOList.stream().map(SimilarityErrorVO::getCustomerId).collect(Collectors.toSet());
                    if (!CollectionUtils.isEmpty(customerIds)) {
                        for (Long customerId : customerIds) {
                                assembleService.sendCustomerEventMessages(customerId, "DUPLICATE_WARNING_CUSTOMER");

                        }
                    }
                }
                List<SimilarityErrorVO> clus = errorCanSaveVOList.stream().filter(e -> e.getResourceType().equals(ResourceTypeEnum.CLUS.code)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(clus)) {
                    Set<Long> customerIds = clus.stream().map(SimilarityErrorVO::getCustomerId).collect(Collectors.toSet());
                    if (!CollectionUtils.isEmpty(customerIds)) {
                        for (Long customerId : customerIds) {
                                assembleService.sendCustomerEventMessages(customerId, "DUPLICATE_WARNING_CLUS");

                        }
                    }
                }
                List<SimilarityErrorVO> liaisonErrorVOList = errorCanSaveVOList.stream().filter(e -> e.getResourceType().equals(ResourceTypeEnum.LIAISON.code)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(liaisonErrorVOList)) {
                    Set<Long> liaisonIds = liaisonErrorVOList.stream().map(SimilarityErrorVO::getErrorId).collect(Collectors.toSet());
                    for (Long liaisonId : liaisonIds) {
                        assembleService.sendLiaisonEventMessages(liaisonId, "DUPLICATE_WARNING_LIAISON");
                    }

                }
            }
            if (Objects.nonNull(customerOld)) {
                String oldCustomerMail = Objects.nonNull(oldCompany) ? oldCompany.getEmail() : "";
                String newCustomerMail = Objects.nonNull(customerAddDTO.getCustomerCompany()) ? customerAddDTO.getCustomerCompany().getEmail() : "";

                String oldLiaisonMail = Objects.nonNull(oldLiaison) ? oldLiaison.getEmail() : "";
                String newLiaisonMail = Objects.nonNull(customerAddDTO.getLiaison()) ? customerAddDTO.getLiaison().getEmail() : "";
                Long customerId = customerOld.getId();
                Long liasionId = null;
                if (Objects.nonNull(oldLiaison) && StrUtil.isNotBlank(oldLiaisonMail) && StrUtil.isNotBlank(newLiaisonMail) && !oldLiaisonMail.equals(newLiaisonMail)) {
                    liasionId = oldLiaison.getId();
                }
                if (Objects.nonNull(customerId) || Objects.nonNull(liasionId)) {
                    List<String> cmails = assembleCustomerMails(companyCompanyEntity);
                    List<String> lmails = assembleLiaisonMails(liaisonEntity);
                    customerMailBingMarkService.updateCustomerMailBingMark(customerId,cmails,liasionId,lmails);
                }
            }
            return Result.result("修改成功");
        }
        return Result.error("修改失败！");
    }

    @Override
    public CustomerVO getCustomerVOById(Long id) {

        if (!ObjectUtils.isEmpty(id)){
            CustomerEntity customerEntity = getById(id);
            if (!ObjectUtils.isEmpty(customerEntity)){
                CustomerVO customerVO = new CustomerVO();
                BeanUtils.copyProperties(customerEntity, customerVO);
                LiaisonEntity liaison = liaisonService.getByCustomerId(customerEntity.getId());
                if (Objects.nonNull(liaison)) {
                    liaison.dictFiled();
                    SysBaseField.orgFileds(liaison);
                    customerVO.setLiaison(liaison);
                }
                customerVO.dictFiled();
                SysBaseField.orgFileds(customerVO);
                //添加最后跟进时间
                String type  = ResourceTypeEnum.CUSTOMER.code;
                if (ResourceTypeEnum.CLUS.code.equals(customerVO.getCustomerForm())){
                    type  = ResourceTypeEnum.CLUS.code;
                }
//                Map<Long, CustomerFollowUpLastVO> followUpLastVOMap = customerFollowUpService.getFollowUpLastVOMap(Arrays.asList(customerEntity.getId()),type);
//                CustomerFollowUpLastVO customerFollowUpLastVO = followUpLastVOMap.get(customerVO.getId());
                //如果没有最后跟进时间，改为创建时间
                Integer regularFollowDays = Integer.valueOf((int)ChronoUnit.DAYS.between(customerVO.getLastFollowUpTime(), LocalDateTime.now()));
                customerVO.setNotFollowUpDate(regularFollowDays);

                //添加代理合作客户
                if (!ObjectUtils.isEmpty(customerVO.getCooperativeCustomerId()) && !customerVO.getCooperativeCustomerId().equals(0L)){
                    CustomerEntity cooperativeCustomer = getById(customerVO.getCooperativeCustomerId());
                    if (!ObjectUtils.isEmpty(cooperativeCustomer)){
                        customerVO.setCooperativeCustomerName(cooperativeCustomer.getCustomerName());
                    }
                }

                //添加客户企业信息
                customerVO.setCustomerCompany(customerCompanyService.getByCustomerId(customerEntity.getId()));

                //添加是否是重点关注
                LoginUser loginUser = LoginUserUtil.getLoginUser();
                if (Objects.nonNull(loginUser)) {
                    LambdaQueryWrapper<CustomerUserFollowEntity> followWrapper = new LambdaQueryWrapper<>();
                    followWrapper.eq(CustomerUserFollowEntity::getCustomerId, customerEntity.getId());
                    followWrapper.eq(CustomerUserFollowEntity::getIsDelete, CommonConstant.DEL_FLAG_0);

                    followWrapper.eq(CustomerUserFollowEntity::getUserId, loginUser.getId());
                    followWrapper.last("limit 1");
                    if (!ObjectUtils.isEmpty(customerUserFollowService.getOne(followWrapper))){
                        customerVO.setHasFollow(true);
                    }
                }


                //添加协作人员姓名
                if (!ObjectUtils.isEmpty(customerVO.getCollaborator())){
                    List<Long> collaboratorList = Arrays.stream(customerVO.getCollaborator().split(",")).map(Long::valueOf).collect(Collectors.toList());
                    List<UserEntity> userEntityList = userService.listByIds(collaboratorList);
                    if (!CollectionUtils.isEmpty(userEntityList)){
                        customerVO.setCollaboratorName(userEntityList.stream().map(UserEntity::getRealName).collect(Collectors.joining(",")));
                    }
                }
                //添加客户保护期
                customerVO.setProtectionDate(getProtectionDate(customerEntity));


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

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

    @Override
    public CustomerEntity getCustomerIdByName(String customerName) {
        CustomerEntity customerEntity = getOne(new QueryWrapper<CustomerEntity>().eq("customer_name", customerName).eq("is_delete", CommonConstant.DEL_FLAG_0).last(" limit 1"));
        if (!ObjectUtils.isEmpty(customerEntity)){
            return customerEntity;
        }
        return null;
    }

    @Override
    public CustomerEntity getCustomerIdByNameAndOwnerBy(String customerName,Long ownerBy) {
        CustomerEntity customerEntity = getOne(new QueryWrapper<CustomerEntity>().eq("owner_by",ownerBy).eq("customer_name", customerName).eq("is_delete", CommonConstant.DEL_FLAG_0).last(" limit 1"));
        if (!ObjectUtils.isEmpty(customerEntity)){
            return customerEntity;
        }
        return null;
    }


    @Override
    public CustomerAllVO getCustomerAllVOById(CustomerSearchDTO customerSearchDTO) {
        Long id = customerSearchDTO.getId();
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        if (ObjectUtils.isEmpty(id)){
            return null;
        }
        CustomerEntity customerEntity = getById(id);

        if (ObjectUtils.isEmpty(customerEntity)){
            return null;
        }
        CustomerAllVO customerVO = new CustomerAllVO();
        BeanUtils.copyProperties(customerEntity, customerVO);
        LiaisonEntity liaison = liaisonService.getByCustomerId(customerEntity.getId());
        if (!ObjectUtils.isEmpty(liaison)){
            liaison.dictFiled();
            SysBaseField.orgFileds(liaison);
            customerVO.setLiaison(liaison);
        }

        //添加代理合作客户
        if (!ObjectUtils.isEmpty(customerVO.getCooperativeCustomerId()) && !customerVO.getCooperativeCustomerId().equals(0L)){
            CustomerEntity cooperativeCustomer = getById(customerVO.getCooperativeCustomerId());
            if (!ObjectUtils.isEmpty(cooperativeCustomer)){
                customerVO.setCooperativeCustomerName(cooperativeCustomer.getCustomerName());
            }
        }

        //添加企业信息
        LambdaQueryWrapper<CustomerCompanyEntity> companyWrapper = new LambdaQueryWrapper<>();
        companyWrapper.eq(CustomerCompanyEntity::getCustomerId, customerEntity.getId());
        companyWrapper.eq(CustomerCompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        companyWrapper.last("limit 1");
        customerVO.setCustomerCompany(customerCompanyService.getOne(companyWrapper));

        //添加所属成员部门信息
        if (!ObjectUtils.isEmpty(customerVO.getOwnerBy())){
            customerVO.setDeptName(userService.getUserInfoById(customerVO.getOwnerBy()).getDeptName());
        }
        //添加最后跟进时间
        String type  = ResourceTypeEnum.CUSTOMER.code;
        if (ResourceTypeEnum.CLUS.code.equals(customerVO.getCustomerForm())){
            type  = ResourceTypeEnum.CLUS.code;
        }
        //如果没有最后跟进时间，改为创建时间
        if (!ObjectUtils.isEmpty(customerVO.getLastFollowUpTime())) {
            Integer regularFollowDays = Integer.valueOf((int) ChronoUnit.DAYS.between(customerVO.getLastFollowUpTime(), LocalDateTime.now()));
            customerVO.setNotFollowUpDate(regularFollowDays);
        }

        //添加下次跟进时间
        if (!ObjectUtils.isEmpty(customerVO.getCustomerForm()) && customerVO.getCustomerForm() == 10){
            LocalDateTime nextFollowUpTime = taskService.getNextFollowUpTime(customerVO.getId(), ResourceTypeEnum.CUSTOMER.code);
            customerVO.setNextFollowUpTime(nextFollowUpTime);
        }else {
            LocalDateTime nextFollowUpTime = taskService.getNextFollowUpTime(customerVO.getId(), ResourceTypeEnum.CLUS.code);
            customerVO.setNextFollowUpTime(nextFollowUpTime);
        }

        //添加是否是重点关注
        LambdaQueryWrapper<CustomerUserFollowEntity> followWrapper = new LambdaQueryWrapper<>();
        followWrapper.eq(CustomerUserFollowEntity::getCustomerId, customerEntity.getId());
        followWrapper.eq(CustomerUserFollowEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        followWrapper.eq(CustomerUserFollowEntity::getUserId, loginUser.getId());
        followWrapper.last("limit 1");
        if (!ObjectUtils.isEmpty(customerUserFollowService.getOne(followWrapper))){
            customerVO.setHasFollow(true);
        }

        //添加协作人员姓名
        if (!ObjectUtils.isEmpty(customerVO.getCollaborator())){
            List<Long> collaboratorList = Arrays.stream(customerVO.getCollaborator().split(",")).map(Long::valueOf).collect(Collectors.toList());
            List<UserEntity> userEntityList = userService.listByIds(collaboratorList);
            if (!CollectionUtils.isEmpty(userEntityList)){
                customerVO.setCollaboratorName(userEntityList.stream().map(UserEntity::getRealName).collect(Collectors.joining(",")));
            }
        }

        //计算客户/线索保护到期时间
//        customerVO.setProtectionDate(getProtectionDate(customerEntity));
        if (!ObjectUtils.isEmpty(customerVO.getPublicDate())){
            customerVO.setProtectionDate(customerVO.getPublicDate().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate()
                    .atTime(9, 0, 0));
        }

        //添加下一个id
//        CustomerEntity next = getNextById(id, new LambdaQueryWrapper<CustomerEntity>().ge(CustomerEntity::getId, id).eq(CustomerEntity::getCustomerForm,customerVO.getCustomerForm()).eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0).orderByAsc(CustomerEntity::getId).last("limit 10"));
//        if (!ObjectUtils.isEmpty(next)){
//            customerVO.setNextId(next.getId());
//
//        }
//        //添加上一个id
//        CustomerEntity previous = getPreviousById(id, new LambdaQueryWrapper<CustomerEntity>().le(CustomerEntity::getId, id).eq(CustomerEntity::getCustomerForm,customerVO.getCustomerForm()).eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0).orderByDesc(CustomerEntity::getId).last("limit 10"));
//        if (!ObjectUtils.isEmpty(previous)){
//            customerVO.setPreviousId(previous.getId());
//        }

        if (Objects.nonNull(customerVO.getCustomerCompany())) {
            customerVO.getCustomerCompany().dictFiled();
        }
        SysBaseField.orgFileds(customerVO);
        customerVO.dictFiled();
        if (Objects.nonNull(customerVO.getFormerOwnerBy())) {
            UserEntity fuser = userService.getById(customerVO.getFormerOwnerBy());
            if (Objects.nonNull(fuser)) {
                DeptEntity fDept = departService.getById(fuser.getDeptId());
                if (Objects.nonNull(fDept)) {
                    customerVO.setFormerDeptName(fDept.getName());
                }
            }
            UserEntity user = userService.getById(customerVO.getOwnerBy());
            if (Objects.nonNull(user)) {
                DeptEntity dept = departService.getById(fuser.getDeptId());
                if (Objects.nonNull(dept)) {
                    customerVO.setFormerDeptName(dept.getName());
                }
            }
        }
        return customerVO;
    }

    private LocalDateTime getProtectionDate(CustomerEntity customerVO) {
        LocalDateTime protectionDate = null;
        Integer mrFollowNum = 0;
        Integer mrTransactionNum = 0;
        try {
            if (customerVO.getCustomerForm().toString().equals(ResourceTypeEnum.CUSTOMER.code)){
                if (customerVO.getHasOrderForm() == 1){
                    return null;
                }
                //客户保护期计算
                LambdaQueryWrapper<SystemRuleModuleConfigEntity> wrapperR = new LambdaQueryWrapper<>();
                wrapperR.eq(SystemRuleModuleConfigEntity::getResourceType, ResourceTypeEnum.CUSTOMER.code);
                wrapperR.eq(SystemRuleModuleConfigEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                wrapperR.last("limit 1");
                SystemRuleModuleConfigEntity systemRuleModuleConfigEntity = systemRuleModuleConfigService.getOne(wrapperR);
                //获取当前未跟进天数
                Integer regularFollowDays = Integer.valueOf((int)ChronoUnit.DAYS.between(customerVO.getLastFollowUpTime(), LocalDateTime.now()));
                //获取当前未成交天数
                Integer regularTransactionDays = Integer.valueOf((int)ChronoUnit.DAYS.between(customerVO.getOwnerTime(), LocalDateTime.now()));

                if (systemRuleModuleConfigEntity.getHasPublicClues()){
                    //开启了置公
                    protectionDate = customerVO.getLastFollowUpTime().plusDays(systemRuleModuleConfigEntity.getMaxPublicCluesNum());
                }
                Integer maxFollowNum = 0;
                Integer maxTransactionNum = 0;

                if (systemRuleModuleConfigEntity.getHasDistinguishKeyRegular()){
                    //开启了重点客户区分
                    if (customerVO.getHasFollowCustomer()){
                        //重点客户
                        maxFollowNum = systemRuleModuleConfigEntity.getKeyFollowDate();
                        maxTransactionNum = systemRuleModuleConfigEntity.getKeyTransactionDate();
                    }else {
                        //普通客户
                        maxFollowNum = systemRuleModuleConfigEntity.getRegularFollowDate();
                        maxTransactionNum = systemRuleModuleConfigEntity.getRegularTransactionDate();
                    }

                    mrFollowNum = maxFollowNum - regularFollowDays;
                    mrTransactionNum = maxTransactionNum - regularTransactionDays;
                    if ((mrFollowNum) < (mrTransactionNum) ){
                        protectionDate = LocalDateTime.now().plusDays(mrFollowNum);
                    }else {
                        protectionDate = LocalDateTime.now().plusDays(mrTransactionNum);
                    }
                }
                if (systemRuleModuleConfigEntity.getHasDistinguishCustomerType()) {
                    //开启了客户类型区分
                    ObjectMapper objectMapper = new ObjectMapper();
                    List<CustomerTypeRulesVO> customerTypeRulesList = objectMapper.readValue(systemRuleModuleConfigEntity.getCustomerTypeRules(),
                            objectMapper.getTypeFactory().constructCollectionType(List.class,  CustomerTypeRulesVO.class));
                    List<CustomerTypeRulesVO> customerTypeList = customerTypeRulesList.stream().filter(e->e.getCustomerTypeDictValue().equals(customerVO.getCustomerTypeDictValue())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(customerTypeList)){
                        maxFollowNum = customerTypeList.get(0).getCustomerTypeFollowDate();
                        maxTransactionNum = customerTypeList.get(0).getCustomerTypeTransactionDate();
                    }
                    mrFollowNum = maxFollowNum - regularFollowDays;
                    mrTransactionNum = maxTransactionNum - regularTransactionDays;
                    if ((mrFollowNum) < (mrTransactionNum) ){
                        protectionDate = LocalDateTime.now().plusDays(mrFollowNum);
                    }else {
                        protectionDate = LocalDateTime.now().plusDays(mrTransactionNum);
                    }
                }

            }else{
                //线索保护期计算
                LambdaQueryWrapper<SystemRuleModuleConfigEntity> wrapperR = new LambdaQueryWrapper<>();
                wrapperR.eq(SystemRuleModuleConfigEntity::getResourceType, ResourceTypeEnum.CLUS.code);
                wrapperR.eq(SystemRuleModuleConfigEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                wrapperR.last("limit 1");
                SystemRuleModuleConfigEntity systemRuleModuleConfigEntity = systemRuleModuleConfigService.getOne(wrapperR);
                if (systemRuleModuleConfigEntity.getHasPublicClues()){
                    //开启了置公
//                    mrFollowNum =
                    protectionDate = customerVO.getLastFollowUpTime().plusDays(systemRuleModuleConfigEntity.getMaxPublicCluesNum());
                }
            }
        }catch (Exception e){
            return null;
        }

        if (protectionDate.isBefore(LocalDateTime.now())){
            protectionDate = LocalDateTime.now();
        }
        return protectionDate;

    }

    @Override
    public boolean glAllDelete(Long id) {
        //删除客户及客户关联的全部数据（商机、订单、联系人、跟进记录、任务、工单、报价单）
        boolean isSuccess = lgDelete(id);
        if (isSuccess){
            customerCompanyService.lgCustomerDelete(id);
            //删除商机
            businessService.lgCustomerDelete(id);
            //删除订单
            orderFormService.lgCustomerDelete(id);
            //删除联系人
            liaisonService.lgCustomerDelete(id);
            //删除跟进记录
            customerFollowUpService.lgCustomerDelete(id);
            //删除寄样记录
            sendRecordService.lgCustomerDelete(id);
            //删除任务
            taskService.lgCustomerDelete(id);
            //删除工单
            workOrderService.lgCustomerDelete(id);
            //删除报价单
            quotationService.lgCustomerDelete(id);
            //删除附件
            sysResourceService.lgCustomerDelete(id);
            return true;
        }
        return false;
    }

    @Override
    public boolean glAllListDelete(List<Long> idList) {
        //删除客户及客户关联的全部数据（商机、订单、联系人、跟进记录、任务、工单、报价单）
//        boolean isSuccess = lgCustomerListDelete(idList);
        boolean isSuccess = lgDelete(idList);
        if (isSuccess){
            //删除客户关联数据
            customerCompanyService.lgCustomerListDelete(idList);
            //删除商机
            businessService.lgCustomerListDelete(idList);
            //删除订单
            orderFormService.lgCustomerListDelete(idList);
            //删除联系人
            liaisonService.lgCustomerListDelete(idList);
            //删除跟进记录
            customerFollowUpService.lgCustomerListDelete(idList);
            //删除寄样
            sendRecordService.lgCustomerListDelete(idList);
            //删除任务
            taskService.lgCustomerListDelete(idList);
            //删除工单
            workOrderService.lgCustomerListDelete(idList);
            //删除报价单
            quotationService.lgCustomerListDelete(idList);
            //删除附件
            sysResourceService.lgCustomerListDelete(idList);
            return true;
        }
        return false;
    }

    @Override
    public Map<Long, CustomerEntity> getCustomerMap(Set<Long> customerIdList) {

        if (!CollectionUtils.isEmpty(customerIdList)){
            Collection<CustomerEntity> customerEntityList = listByIds(customerIdList);
            if (!CollectionUtils.isEmpty(customerEntityList)){
                Map<Long, CustomerEntity> customerEntityMap = customerEntityList.stream().collect(Collectors.toMap(CustomerEntity::getId, customerEntity -> customerEntity));
                return customerEntityMap;
            }
        }
        return new HashMap<>();
    }

    @Override
    public List<CustomerEntity> listCustomers(List<Long> customerIdList) {
        if (!CollectionUtils.isEmpty(customerIdList)){
            List<CustomerEntity> customerEntityList = listByIds(customerIdList);
            return customerEntityList;
        }
        return new ArrayList<>();
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> mergeCustomer(CustomerMergeDTO customerMergeDTO) {
        if (ObjectUtils.isEmpty(customerMergeDTO)){
            return Result.error("参数不能为空");
        }
        if (ObjectUtils.isEmpty(customerMergeDTO.getFromId())){
            return Result.error("合并客户信息异常");
        }

        CustomerEntity customerEntity = new CustomerEntity();
        BeanUtils.copyProperties(customerMergeDTO, customerEntity);
        boolean isOk = updateById(customerEntity);

        boolean delOk = lgDelete(customerMergeDTO.getFromId());

        if (isOk && delOk){
            CustomerChangeLogEntity changeLogEntity = new CustomerChangeLogEntity();
            changeLogEntity.setCustomerId(customerEntity.getId());
            changeLogEntity.setFromId(customerMergeDTO.getFromId());
            customerChangeLogService.save(changeLogEntity);
            //修改企业详情
            CustomerCompanyEntity companyCompanyOld = new CustomerCompanyEntity();
            LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customerCompanyEntityLambdaQueryWrapper.eq(CustomerCompanyEntity::getCustomerId, customerMergeDTO.getId());
            customerCompanyEntityLambdaQueryWrapper.eq(CustomerCompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            customerCompanyEntityLambdaQueryWrapper.last("limit 1");
            companyCompanyOld = customerCompanyService.getOne(customerCompanyEntityLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(companyCompanyOld)){
                CustomerCompanyEntity companyCompanyEntity = new CustomerCompanyEntity();
                if (!ObjectUtils.isEmpty(customerMergeDTO.getCustomerCompany())) {
                    BeanUtils.copyProperties(customerMergeDTO.getCustomerCompany(), companyCompanyEntity);
                }
                companyCompanyEntity.setId(companyCompanyOld.getId());
                companyCompanyEntity.setCustomerId(customerEntity.getId());
                customerCompanyService.updateById(companyCompanyEntity);
            }

//            LambdaUpdateWrapper<CustomerCompanyEntity> customerCompanyUpdateWrapper = new LambdaUpdateWrapper<>();
//            customerCompanyUpdateWrapper.eq(CustomerCompanyEntity::getCustomerId, customerEntity.getId());
//            customerCompanyService.update(companyCompanyEntity,customerCompanyUpdateWrapper);

            //修改全部客户关联业务表关联客户id
            changeAllCustomerId(customerMergeDTO.getFromId(), customerEntity.getId());

            //修改主要联系人及归属人
            CustomerEntity customer = getById(customerEntity.getId());

            LambdaUpdateWrapper<CustomerCompanyEntity> ccWrapper = new LambdaUpdateWrapper<>();
            ccWrapper.eq(CustomerCompanyEntity::getCustomerId,customerMergeDTO.getId())
                    .set(CustomerCompanyEntity::getOwnerBy,customer.getOwnerBy());
            customerCompanyService.update(ccWrapper);

            LambdaUpdateWrapper<LiaisonEntity> liaisonUpdateWrapper = new LambdaUpdateWrapper<>();
            liaisonUpdateWrapper.eq(LiaisonEntity::getCustomerId, customerMergeDTO.getId());
//            liaisonUpdateWrapper.eq(LiaisonEntity::getHasPrimaryLialison,true);
            liaisonUpdateWrapper.set(LiaisonEntity::getHasPrimaryLialison,false);
            liaisonUpdateWrapper.set(LiaisonEntity::getOwnerBy,customer.getOwnerBy());
            liaisonService.update(liaisonUpdateWrapper);

            if (!ObjectUtils.isEmpty(customerMergeDTO.getLiaison())) {
                LambdaUpdateWrapper<LiaisonEntity> liaisonPrimaryUpdateWrapper = new LambdaUpdateWrapper<>();
                liaisonPrimaryUpdateWrapper.eq(LiaisonEntity::getId, customerMergeDTO.getLiaison().getId());
//            liaisonPrimaryUpdateWrapper.eq(LiaisonEntity::getHasPrimaryLialison,true);
                liaisonPrimaryUpdateWrapper.set(LiaisonEntity::getHasPrimaryLialison, true);
//                liaisonPrimaryUpdateWrapper.set(LiaisonEntity::getOwnerBy, customer.getOwnerBy());
                liaisonService.update(liaisonPrimaryUpdateWrapper);
            }
            assembleService.sendCustomerEventMessages(customerMergeDTO.getFromId(),"CUSTOMER_MERGE");

            return Result.result("客户合并成功");
        }
        return Result.error("客户合并失败！");
    }

    @Override
    public Result<?> convertToCustomer(CustomerConvertDTO customerConvert) {
        if (ObjectUtils.isEmpty(customerConvert)){
            return Result.error("参数不能为空");
        }
        CustomerEntity customerOld = getById(customerConvert.getId());

        //判断用户线索上限
        Boolean hasExceed = maxMemberNum(1, customerOld.getOwnerBy(),ResourceTypeEnum.CUSTOMER.code);
        if (hasExceed){
            return Result.error("客户数量超过上限");
        }

        CustomerEntity customerEntity = new CustomerEntity();
        BeanUtils.copyProperties(customerConvert, customerEntity);
        customerEntity.setCustomerForm(10);
        customerEntity.setHasFromClue(true);
        customerEntity.setHasPublicCustomer(false);
        customerEntity.setOwnerTime(LocalDateTime.now());
        customerEntity.setLastFollowUpTime(LocalDateTime.now());
        boolean isOk = updateById(customerEntity);
        if (isOk){

            //将置公时间置空
            LambdaUpdateWrapper<CustomerEntity> customerUpdateWrapper = new LambdaUpdateWrapper<>();
            customerUpdateWrapper.eq(CustomerEntity::getId,customerEntity.getId());
            customerUpdateWrapper.set(CustomerEntity::getPublicDate,null);
            customerUpdateWrapper.set(CustomerEntity::getPublicRemindDate,null);
            customerUpdateWrapper.set(CustomerEntity::getGarbageDate,null);
            customerUpdateWrapper.set(CustomerEntity::getGarbageRemindDate,null);
            customerUpdateWrapper.set(CustomerEntity::getDeleteDate,null);
            customerUpdateWrapper.set(CustomerEntity::getDeleteRemindDate,null);
            update(customerUpdateWrapper);
            systemRuleModuleConfigService.updateCustomerDate(customerEntity.getId());
//            if (!ObjectUtils.isEmpty(customerConvert.getLiaison())) {
//                LambdaUpdateWrapper<LiaisonEntity> liaisonUpdateWrapper = new LambdaUpdateWrapper<>();
//                liaisonUpdateWrapper.eq(LiaisonEntity::getCustomerId, customerEntity.getId());
//                liaisonService.update(customerConvert.getLiaison(), liaisonUpdateWrapper);
//            }
            //更改跟进及任务关联类型
            LambdaUpdateWrapper<TaskEntity> taskUpdateWrapper = new LambdaUpdateWrapper<>();
            taskUpdateWrapper.eq(TaskEntity::getResourceType, ResourceTypeEnum.CLUS.code);
            taskUpdateWrapper.eq(TaskEntity::getResourceTypeId, customerEntity.getId());
            taskUpdateWrapper.set(TaskEntity::getResourceType, ResourceTypeEnum.CUSTOMER.code);
            taskService.update(taskUpdateWrapper);

            LambdaUpdateWrapper<CustomerFollowUpEntity> followUpUpdateWrapper = new LambdaUpdateWrapper<>();
            followUpUpdateWrapper.eq(CustomerFollowUpEntity::getResourceType, ResourceTypeEnum.CLUS.code);
            followUpUpdateWrapper.eq(CustomerFollowUpEntity::getResourceTypeId, customerEntity.getId());
            followUpUpdateWrapper.set(CustomerFollowUpEntity::getResourceType, ResourceTypeEnum.CUSTOMER.code);
            customerFollowUpService.update(followUpUpdateWrapper);
            //发送消息
            assembleService.sendCustomerEventMessages(customerConvert.getId(),"CONVERT_TO_CUSTOMER");

            return Result.result("转为客户成功");

        }
        return Result.error("转为客户失败！");
    }

    @Override
    public Result<?> collectClues(CustomerCollectCluesDTO collectCluesDTO) {


        if (ObjectUtils.isEmpty(collectCluesDTO) || CollectionUtils.isEmpty(collectCluesDTO.getIdList())){
            return Result.error("参数不能为空");
        }
        CustomerEntity customerOld1 = getById(collectCluesDTO.getIdList().get(0));
        //判断用户线索上限
        Integer num = collectCluesDTO.getIdList().size();
        Boolean hasExceed = maxMemberNum(num, LoginUserUtil.getCurrentUserId(),customerOld1.getCustomerForm().toString());
        if (hasExceed){
            if (customerOld1.getCustomerForm() == 10){
                return Result.error("领取客户数量超过上限");
            }
            return Result.error("领取线索数量超过上限");
        }
        LocalDateTime currentTime = LocalDateTime.now();
        List<CustomerEntity> customerList = new ArrayList<>();
        for (Long id : collectCluesDTO.getIdList()){
            CustomerEntity customerEntity = new CustomerEntity();
            customerEntity.setId(id);
            customerEntity.setOwnerBy(LoginUserUtil.getCurrentUserId());
            customerEntity.setHasPublicCustomer(false);
            customerEntity.setOwnerTime(LocalDateTime.now());
            customerEntity.setLastFollowUpTime(currentTime);
            customerEntity.setHasGarbageCustomer(false);
            customerList.add(customerEntity);
        }
        if (updateBatchById(customerList)){
            //将置公时间置空
            LambdaUpdateWrapper<CustomerEntity> customerUpdateWrapper = new LambdaUpdateWrapper<>();
            customerUpdateWrapper.in(CustomerEntity::getId, collectCluesDTO.getIdList());
            customerUpdateWrapper.set(CustomerEntity::getPublicDate,null);
            customerUpdateWrapper.set(CustomerEntity::getPublicRemindDate,null);
            customerUpdateWrapper.set(CustomerEntity::getGarbageDate,null);
            customerUpdateWrapper.set(CustomerEntity::getGarbageRemindDate,null);
            customerUpdateWrapper.set(CustomerEntity::getDeleteDate,null);
            customerUpdateWrapper.set(CustomerEntity::getDeleteRemindDate,null);
            update(customerUpdateWrapper);
            for (CustomerEntity customerEntity : customerList){
                systemRuleModuleConfigService.updateCustomerDate(customerEntity.getId());
            }

            LambdaUpdateWrapper<CustomerCompanyEntity> ccWrapper = new LambdaUpdateWrapper<>();
            ccWrapper.in(CustomerCompanyEntity::getCustomerId,collectCluesDTO.getIdList())
                    .set(CustomerCompanyEntity::getOwnerBy,LoginUserUtil.getCurrentUserId());
            customerCompanyService.update(ccWrapper);


            //修改联系人归属
            LambdaUpdateWrapper<LiaisonEntity> liaisonUpdateWrapper = new LambdaUpdateWrapper<>();
            liaisonUpdateWrapper.in(LiaisonEntity::getCustomerId, collectCluesDTO.getIdList());
            liaisonUpdateWrapper.set(LiaisonEntity::getOwnerBy,LoginUserUtil.getCurrentUserId());
            liaisonUpdateWrapper.set(LiaisonEntity::getLastFollowUpTime,currentTime);
            liaisonService.update(liaisonUpdateWrapper);
            //发送消息
            assembleService.sendCustomerEventMessages(collectCluesDTO.getIdList().get(0),"MEMBER_RECEIVE_CLUE");
            for (Long id : collectCluesDTO.getIdList()) {
                CustomerEntity customerNow = getById(id);
                //添加归属记录
                CustomerOwnerRecordEntity customerOwnerRecord = new CustomerOwnerRecordEntity();
                customerOwnerRecord.setCustomerId(id);
                customerOwnerRecord.setNowOwnerBy(customerNow.getOwnerBy());
                customerOwnerRecord.setOperatingType(1);

                try {
                    // 创建ObjectMapper实例
//                    ObjectMapper objectMapper = new ObjectMapper();
//                    // 将CustomerEntity对象转换为JSON字符串
//                    String jsonString = objectMapper.writeValueAsString(customerNow);

                    // 创建 Gson 实例
                    Gson gson = new Gson();
                    CustomerAllVO customerAllVO =new CustomerAllVO();
                    BeanUtils.copyProperties(customerNow,customerAllVO);
                    customerAllVO.setCustomerCompany(customerCompanyService.getByCustomerId(customerNow.getId()));
                    // 将 CustomerEntity 对象转换为 JSON 字符串
                    String jsonString = gson.toJson(customerAllVO);
                    customerOwnerRecord.setCustomerDetail(jsonString);
                } catch (Exception e) {
                    log.error(e.getMessage());
                    return Result.error("客户数据更新异常");
                }
                customerOwnerService.save(customerOwnerRecord);
            }
            return Result.result("领取成功");
        }
        return Result.error("领取失败");
    }

    @Override
    public Result<?> assignClues(CustomerAssignCluesDTO customerAssignCluesDTO) {
        if (ObjectUtils.isEmpty(customerAssignCluesDTO) || CollectionUtils.isEmpty(customerAssignCluesDTO.getIdList())){
            return Result.error("参数不能为空");
        }

        //判断用户线索上限
        Integer num = customerAssignCluesDTO.getIdList().size();
        Boolean hasExceed = maxMemberNum(num, customerAssignCluesDTO.getOwnerBy(),ResourceTypeEnum.CLUS.code);
        if (hasExceed){
            return Result.error("线索数量超过上限");
        }

        List<CustomerEntity> customerList = new ArrayList<>();
        for (Long id : customerAssignCluesDTO.getIdList()){
            CustomerEntity customerEntity = new CustomerEntity();
            customerEntity.setId(id);
            customerEntity.setOwnerBy(customerAssignCluesDTO.getOwnerBy());
            customerEntity.setHasPublicCustomer(false);
            customerEntity.setRemark(customerAssignCluesDTO.getRemark());
            customerEntity.setLastFollowUpTime(LocalDateTime.now());
            customerEntity.setOwnerTime(LocalDateTime.now());
            customerList.add(customerEntity);
        }
        if (updateBatchById(customerList)){
            //将置公时间置空
            LambdaUpdateWrapper<CustomerEntity> customerUpdateWrapper = new LambdaUpdateWrapper<>();
            customerUpdateWrapper.in(CustomerEntity::getId,customerAssignCluesDTO.getIdList());
            customerUpdateWrapper.set(CustomerEntity::getPublicDate,null);
            customerUpdateWrapper.set(CustomerEntity::getPublicRemindDate,null);
            customerUpdateWrapper.set(CustomerEntity::getGarbageDate,null);
            customerUpdateWrapper.set(CustomerEntity::getGarbageRemindDate,null);
            customerUpdateWrapper.set(CustomerEntity::getDeleteDate,null);
            customerUpdateWrapper.set(CustomerEntity::getDeleteRemindDate,null);
            update(customerUpdateWrapper);
            for (CustomerEntity customerEntity : customerList){
                systemRuleModuleConfigService.updateCustomerDate(customerEntity.getId());
            }

            LambdaUpdateWrapper<CustomerCompanyEntity> ccWrapper = new LambdaUpdateWrapper<>();
            ccWrapper.in(CustomerCompanyEntity::getCustomerId,customerAssignCluesDTO.getIdList())
                    .set(CustomerCompanyEntity::getOwnerBy,customerAssignCluesDTO.getOwnerBy());
            customerCompanyService.update(ccWrapper);
            //修改联系人归属人为新分配人
//            List<Long> customerIdList = customerAssignCluesDTO.getIdList();
            LambdaUpdateWrapper<LiaisonEntity> liaisonEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            liaisonEntityLambdaUpdateWrapper.in(LiaisonEntity::getCustomerId,customerAssignCluesDTO.getIdList());
            liaisonEntityLambdaUpdateWrapper.set(LiaisonEntity::getOwnerBy, customerAssignCluesDTO.getOwnerBy());
            liaisonService.update(liaisonEntityLambdaUpdateWrapper);
            //发送消息
            assembleService.sendCustomerEventMessages(customerAssignCluesDTO.getIdList().get(0),"DISTRIBUTE_CLUE",new HashSet<>(Arrays.asList(customerAssignCluesDTO.getOwnerBy())));
            for (Long id : customerAssignCluesDTO.getIdList()) {
                CustomerEntity customerNow = getById(id);
                //添加归属记录
                CustomerOwnerRecordEntity customerOwnerRecord = new CustomerOwnerRecordEntity();
                customerOwnerRecord.setCustomerId(customerNow.getId());
                customerOwnerRecord.setOldOwnerBy(customerNow.getFormerOwnerBy());
                customerOwnerRecord.setNowOwnerBy(customerNow.getOwnerBy());
                customerOwnerRecord.setOperatingType(2);

                try {
                    // 创建 Gson 实例
                    Gson gson = new Gson();
                    CustomerAllVO customerAllVO =new CustomerAllVO();
                    BeanUtils.copyProperties(customerNow,customerAllVO);
                    customerAllVO.setCustomerCompany(customerCompanyService.getByCustomerId(customerNow.getId()));
                    // 将 CustomerEntity 对象转换为 JSON 字符串
                    String jsonString = gson.toJson(customerAllVO);
                    customerOwnerRecord.setCustomerDetail(jsonString);
                } catch (Exception e) {
                    return Result.error("客户数据更新异常");
                }
                customerOwnerService.save(customerOwnerRecord);
            }
            return Result.result("分配成功");
        }
        return Result.error("分配失败");
    }

    @Override
    public Result<?> forReson(CustomerForReasonDTO customerForReason) {

//        CustomerEntity customerEntity = new CustomerEntity();
        if (ObjectUtils.isEmpty(customerForReason) || CollectionUtils.isEmpty(customerForReason.getIdList())){
            return Result.error("参数不能为空");
        }
        List<CustomerEntity> customerEntityList = new ArrayList<>();
        for (Long id : customerForReason.getIdList()){
            CustomerEntity customer = new CustomerEntity();
            customer.setId(id);
            customer.setReasonPublicCustomerDictValue(customerForReason.getReasonPublicCustomerDictValue());
            customer.setHasPublicCustomer(true);
            customer.setGiveUpTime(LocalDateTime.now());
            customer.setLastFollowUpTime(LocalDateTime.now());
            customer.setHasGarbageCustomer(false);
            customerEntityList.add(customer);
        }
        if (updateBatchById(customerEntityList)){

            // 修改归属人为空
            // 修改前归属人人
            LambdaUpdateWrapper<CustomerEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.setSql("former_owner_by = owner_by")
                    .set(CustomerEntity::getOwnerBy, null)
                    .set(CustomerEntity::getPublicDate, null)
                    .set(CustomerEntity::getPublicRemindDate, null)
                    .set(CustomerEntity::getGarbageDate, null)
                    .set(CustomerEntity::getGarbageRemindDate, null)
                    .set(CustomerEntity::getDeleteDate, null)
                    .set(CustomerEntity::getDeleteRemindDate, null)
                    .in(CustomerEntity::getId, customerForReason.getIdList());
            update(updateWrapper);
            for (CustomerEntity customerEntity : customerEntityList) {
                systemRuleModuleConfigService.updateCustomerDate(customerEntity.getId());
            }

            LambdaUpdateWrapper<CustomerCompanyEntity> customerCompanyLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            customerCompanyLambdaUpdateWrapper.in(CustomerCompanyEntity::getCustomerId,customerForReason.getIdList());
            customerCompanyLambdaUpdateWrapper.set(CustomerCompanyEntity::getOwnerBy, null);
            customerCompanyService.update(customerCompanyLambdaUpdateWrapper);

            LambdaUpdateWrapper<LiaisonEntity> liaisonEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            liaisonEntityLambdaUpdateWrapper.in(LiaisonEntity::getCustomerId,customerForReason.getIdList());
            liaisonEntityLambdaUpdateWrapper.set(LiaisonEntity::getOwnerBy, null);
            liaisonService.update(liaisonEntityLambdaUpdateWrapper);

            CustomerEntity customerEntityOld = getById(customerForReason.getIdList().get(0));

            if (customerEntityOld.getCustomerForm().toString().equals(ResourceTypeEnum.CLUS.code)) {
                for (Long id : customerForReason.getIdList()){
                    assembleService.sendCustomerPublicMessages(id, "MOVE_TO_PUBLIC_CLUS");
                }

            }else {
                for (Long id : customerForReason.getIdList()){
                    assembleService.sendCustomerPublicMessages(id, "MOVE_TO_PUBLIC");
                }
            }
            for (Long id : customerForReason.getIdList()){
                CustomerEntity customerNow = getById(id);
                //添加归属记录
                CustomerOwnerRecordEntity customerOwnerRecord = new CustomerOwnerRecordEntity();
                customerOwnerRecord.setCustomerId(customerNow.getId());
                customerOwnerRecord.setOldOwnerBy(customerNow.getFormerOwnerBy());
                customerOwnerRecord.setOperatingType(4);

                try {
                    // 创建 Gson 实例
                    Gson gson = new Gson();
                    CustomerAllVO customerAllVO =new CustomerAllVO();
                    BeanUtils.copyProperties(customerNow,customerAllVO);
                    customerAllVO.setCustomerCompany(customerCompanyService.getByCustomerId(customerNow.getId()));
                    // 将 CustomerEntity 对象转换为 JSON 字符串
                    String jsonString = gson.toJson(customerAllVO);
                    customerOwnerRecord.setCustomerDetail(jsonString);
                }catch (Exception e){
                    return Result.error("客户数据更新异常");
                }
                customerOwnerService.save(customerOwnerRecord);
            }

            return Result.result("置公成功");
        }
        return Result.error("置公失败");
    }

    @Override
    public Result<?> collaborator(CustomerCollaboratorDTO customerCollaboratorDTO) {
        List<Long> customerIdList = customerCollaboratorDTO.getResourceIdList();
        if (!CollectionUtils.isEmpty(customerIdList)){
            LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(CustomerEntity::getId, customerIdList);
            List<CustomerEntity> customerEntityList = list(wrapper);
            if (CollectionUtils.isEmpty(customerEntityList)){
                return Result.error("未找到商机");
            }
            for (CustomerEntity customerEntity : customerEntityList){
                List<Long> longList = StringUtil.stringToLongList(customerEntity.getCollaborator());
                if (customerCollaboratorDTO.getType() == 1){
                    //新增协作人员
                    longList.addAll(customerCollaboratorDTO.getUserIdList());
                    Set<Long> longSet = new HashSet<>(longList);
                    customerEntity.setCollaborator(longSet.stream()
                            .map(Object::toString)
                            .collect(Collectors.joining(",")));
                }else {
                    //删除协作人员
                    longList.removeAll(customerCollaboratorDTO.getUserIdList());
                    Set<Long> longSet = new HashSet<>(longList);
                    customerEntity.setCollaborator(longSet.stream()
                            .map(Object::toString)
                            .collect(Collectors.joining(",")));
                }
            }
            if (updateBatchById(customerEntityList)){
                //发送消息
                if (customerCollaboratorDTO.getType() == 1){
                    assembleService.sendCustomerEventMessages(customerEntityList.get(0).getId(), "CUSTOMER_COLLABORATION",new HashSet<>(customerCollaboratorDTO.getUserIdList()));
                }
                return Result.ok();
            }
        }
        return Result.error("操作失败！");
    }


    @Override
    public Result<IPage<CustomerListVO>> selectListVO(CustomerSearchDTO customerSearchDTO) {
        //去掉customerSearchDTO.getBlurry()前后空格
        if (!ObjectUtils.isEmpty(customerSearchDTO.getBlurry())){
            customerSearchDTO.setBlurry(customerSearchDTO.getBlurry().trim());
        }
        if (!ObjectUtils.isEmpty(customerSearchDTO.getCustomerName())){
            customerSearchDTO.setCustomerName(customerSearchDTO.getCustomerName().trim());
        }
        if (!ObjectUtils.isEmpty(customerSearchDTO.getLiaisonName())){
            customerSearchDTO.setLiaisonName(customerSearchDTO.getLiaisonName().trim());
        }
        String jsonKey = JSON.toJSONString(customerSearchDTO.getScopeMenuId()+"_"+customerSearchDTO.getCustomerBelongType()+"_"+LoginUserUtil.getCurrentUserId());
        log.error("jsonKey = "+jsonKey);
        String preNexKey = MD5Util.MD5Encode(jsonKey,"UTF-8");
//        log.error("preNexKey---MD5 ="+preNexKey);
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        IPage<CustomerListVO> pageVO =new Page<>(customerSearchDTO.getPageIndex(), customerSearchDTO.getPageSize());

        IPage<CustomerEntity> page = new Page<>(customerSearchDTO.getPageIndex(), customerSearchDTO.getPageSize());
        LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
        if (customerSearchDTO.getHasFollowMode()){
            //跟进模式
            Set<Long> followCustomerIdList = new HashSet<>();
            //获取有未读邮件的客户
            LambdaQueryWrapper<CustomerMailBingMarkEntity> customerMailBingMarkEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customerMailBingMarkEntityLambdaQueryWrapper.isNull(CustomerMailBingMarkEntity::getFollowUpId);
            customerMailBingMarkEntityLambdaQueryWrapper.isNotNull(CustomerMailBingMarkEntity::getCustomerId);
            List<CustomerMailBingMarkEntity> customerMailBingMarkEntityList = customerMailBingMarkService.list(customerMailBingMarkEntityLambdaQueryWrapper);
            //返回客户idSet
            Set<Long> customerIdSet = customerMailBingMarkEntityList.stream()
                    .map(CustomerMailBingMarkEntity::getCustomerId)
                    .collect(Collectors.toSet());
                followCustomerIdList.addAll(customerIdSet);
            //获取有未完成任务的客户
            LambdaQueryWrapper<TaskEntity> taskEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            taskEntityLambdaQueryWrapper.eq(TaskEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            taskEntityLambdaQueryWrapper.in(TaskEntity::getTaskStatus,Arrays.asList(1,3,4));
            List<TaskEntity> taskList = taskService.list(taskEntityLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(taskList)){
                Set<Long> taskCustomerIds = taskList.stream().map(TaskEntity::getCustomerId).collect(Collectors.toSet());
                followCustomerIdList.addAll(taskCustomerIds);
            }
            if (CollectionUtils.isEmpty(followCustomerIdList)){
                return Result.result(pageVO);
            }
            wrapper.in(CustomerEntity::getId,followCustomerIdList);

        }
//        if (StrUtil.isNotBlank(customerSearchDTO.getBlurry())) {
//            LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            customerCompanyEntityLambdaQueryWrapper.eq(CustomerCompanyEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
//            customerCompanyEntityLambdaQueryWrapper.and(w -> w.like(CustomerCompanyEntity::getWebsite,customerSearchDTO.getBlurry()).or().like(CustomerCompanyEntity::getEmail,customerSearchDTO.getBlurry()));
//
//            List<CustomerCompanyEntity> customerCompanyEntityList = customerCompanyService.list(customerCompanyEntityLambdaQueryWrapper);
//            if (!CollectionUtils.isEmpty(customerCompanyEntityList)){
//                List<Long> customerIds = customerCompanyEntityList.stream().map(CustomerCompanyEntity::getCustomerId).collect(Collectors.toList());
//                wrapper.and(w -> w.like(CustomerEntity::getCustomerName,customerSearchDTO.getBlurry()).or().like(CustomerEntity::getDataCode,customerSearchDTO.getBlurry()).or().in(CustomerEntity::getId,customerIds));
//            }else {
//                wrapper.and(w -> w.like(CustomerEntity::getCustomerName,customerSearchDTO.getBlurry()).or().like(CustomerEntity::getDataCode,customerSearchDTO.getBlurry()));
//            }
//
//        }
        if (StrUtil.isNotBlank(customerSearchDTO.getBlurry())) {
            LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customerCompanyEntityLambdaQueryWrapper.eq(CustomerCompanyEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            customerCompanyEntityLambdaQueryWrapper.and(w -> w.like(CustomerCompanyEntity::getWebsite,customerSearchDTO.getBlurry()).or().like(CustomerCompanyEntity::getEmail,customerSearchDTO.getBlurry()));

            List<CustomerCompanyEntity> customerCompanyEntityList = customerCompanyService.list(customerCompanyEntityLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(customerCompanyEntityList)){
                List<Long> customerIds = customerCompanyEntityList.stream().map(CustomerCompanyEntity::getCustomerId).collect(Collectors.toList());
                wrapper.and(w -> w.like(CustomerEntity::getCustomerName,customerSearchDTO.getBlurry()).or().like(CustomerEntity::getDataCode,customerSearchDTO.getBlurry()).or().in(CustomerEntity::getId,customerIds));
            }else {
                wrapper.and(w -> w.like(CustomerEntity::getCustomerName,customerSearchDTO.getBlurry()).or().like(CustomerEntity::getDataCode,customerSearchDTO.getBlurry()));
            }

        }
        //客户线索名称、企业网址
//        if (StrUtil.isNotBlank(customerSearchDTO.getCustomerName())) {
//            LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            customerCompanyEntityLambdaQueryWrapper.eq(CustomerCompanyEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
//            customerCompanyEntityLambdaQueryWrapper.and(w -> w.like(CustomerCompanyEntity::getWebsite,customerSearchDTO.getCustomerName()).or().like(CustomerCompanyEntity::getEmail,customerSearchDTO.getCustomerName()));
//
//            List<CustomerCompanyEntity> customerCompanyEntityList = customerCompanyService.list(customerCompanyEntityLambdaQueryWrapper);
//            if (!CollectionUtils.isEmpty(customerCompanyEntityList)){
//                List<Long> customerIds = customerCompanyEntityList.stream().map(CustomerCompanyEntity::getCustomerId).collect(Collectors.toList());
//                wrapper.and(w -> w.like(CustomerEntity::getCustomerName,customerSearchDTO.getCustomerName()).or().in(CustomerEntity::getId,customerIds));
//            }else {
//                wrapper.and(w -> w.like(CustomerEntity::getCustomerName,customerSearchDTO.getCustomerName()));
//            }
//        }
        //联系人(联系人姓名、联系人邮箱)
        if (StrUtil.isNotBlank(customerSearchDTO.getLiaisonName())) {
            LambdaQueryWrapper<LiaisonEntity> liaisonEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            liaisonEntityLambdaQueryWrapper.eq(LiaisonEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            liaisonEntityLambdaQueryWrapper.and(w -> w.like(LiaisonEntity::getName,customerSearchDTO.getLiaisonName()).or().like(LiaisonEntity::getEmail,customerSearchDTO.getLiaisonName()));

            List<LiaisonEntity> liaisonEntityList = liaisonService.list(liaisonEntityLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(liaisonEntityList)){
                List<Long> customerIds = liaisonEntityList.stream().map(LiaisonEntity::getCustomerId).collect(Collectors.toList());
                wrapper.in(CustomerEntity::getId,customerIds);
            }else {
                return Result.result(pageVO);
            }
        }
        wrapper.eq( CustomerEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerForm()),CustomerEntity::getCustomerForm,customerSearchDTO.getCustomerForm());
        wrapper.like(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerName()),CustomerEntity::getCustomerName,customerSearchDTO.getCustomerName());
//        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerName()),CustomerEntity::getCustomerName,customerSearchDTO.getCustomerName());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getOwnerBy()),CustomerEntity::getOwnerBy,customerSearchDTO.getOwnerBy());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getId()),CustomerEntity::getId,customerSearchDTO.getId());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getHasPublicCustomer()),CustomerEntity::getHasPublicCustomer,customerSearchDTO.getHasPublicCustomer());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getHasGarbageCustomer()),CustomerEntity::getHasGarbageCustomer,customerSearchDTO.getHasGarbageCustomer());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCountry()),CustomerEntity::getCountry,customerSearchDTO.getCountry());
        LocalDateTime lastFollowUpTime = customerSearchDTO.getLastFollowUpTime();
        if (!ObjectUtils.isEmpty(lastFollowUpTime)){
            wrapper.apply("DATE(last_follow_up_time) = {0}",
                    lastFollowUpTime);
        }
        wrapper.eq(!ObjectUtils.isEmpty(lastFollowUpTime),CustomerEntity::getLastFollowUpTime,lastFollowUpTime);
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerStatusDictValue()), CustomerEntity::getCustomerStatusDictValue,customerSearchDTO.getCustomerStatusDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerSourceDictValue()), CustomerEntity::getCustomerSourceDictValue,customerSearchDTO.getCustomerSourceDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerTypeDictValue()), CustomerEntity::getCustomerTypeDictValue,customerSearchDTO.getCustomerTypeDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerLevelDictValue()), CustomerEntity::getCustomerLevelDictValue,customerSearchDTO.getCustomerLevelDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerEconomicNatureDictValue()), CustomerEntity::getCustomerEconomicNatureDictValue,customerSearchDTO.getCustomerEconomicNatureDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getCustomerCreditLevelDictValue()), CustomerEntity::getCustomerCreditLevelDictValue,customerSearchDTO.getCustomerCreditLevelDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getHasOrderForm()), CustomerEntity::getHasOrderForm,customerSearchDTO.getHasOrderForm());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getHasFromClue()), CustomerEntity::getHasFromClue,customerSearchDTO.getHasFromClue());
        wrapper.ge(!ObjectUtils.isEmpty(customerSearchDTO.getLastFollowUpBeginTime()), CustomerEntity::getLastFollowUpTime, customerSearchDTO.getLastFollowUpBeginTime());
        wrapper.le(!ObjectUtils.isEmpty(customerSearchDTO.getLastFollowUpEndTime()), CustomerEntity::getLastFollowUpTime, customerSearchDTO.getLastFollowUpEndTime());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getOwnerBy()),CustomerEntity::getOwnerBy, customerSearchDTO.getOwnerBy());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getFormerOwnerBy()),CustomerEntity::getFormerOwnerBy, customerSearchDTO.getFormerOwnerBy());
        wrapper.in(!CollectionUtils.isEmpty(customerSearchDTO.getFormerOwnerByList()),CustomerEntity::getFormerOwnerBy, customerSearchDTO.getFormerOwnerByList());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getClueStatusDictValue()),CustomerEntity::getClueStatusDictValue,customerSearchDTO.getClueStatusDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerSearchDTO.getReasonPublicCustomerDictValue()),CustomerEntity::getReasonPublicCustomerDictValue,customerSearchDTO.getReasonPublicCustomerDictValue());
        wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.in(!CollectionUtils.isEmpty(customerSearchDTO.getOwnerByIds()),CustomerEntity::getOwnerBy, customerSearchDTO.getOwnerByIds());

        //根据客户归属分类查询

        StringBuilder mergeSql = new StringBuilder();
        if (Objects.nonNull(customerSearchDTO.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(customerSearchDTO.getQueryRangeType(),LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                wrapper.apply(queryRangeSql);
            }
            else if(QueryRangeTypeEnum.QUERY_COOPERA_SQL.getCode().equals(customerSearchDTO.getQueryRangeType())){
                //重点客户
//                List<CustomerUserFollowEntity> customerUserFollowEntityList = customerUserFollowService.list(new LambdaQueryWrapper<CustomerUserFollowEntity>().eq(CustomerUserFollowEntity::getUserId,loginUser.getId()));
//                List<Long> customerIdList = customerUserFollowEntityList.stream().map(CustomerUserFollowEntity::getCustomerId).collect(Collectors.toList());
//                if (CollectionUtils.isEmpty(customerIdList)){
//                    return Result.result(pageVO);
//                }
//                wrapper.in(CustomerEntity::getId,customerIdList);
                wrapper.eq(CustomerEntity::getHasFollowCustomer,true);
            }else if(QueryRangeTypeEnum.QUERY_MY_COOPERA_SQL.getCode().equals(customerSearchDTO.getQueryRangeType())){
                //我协作的
                wrapper.apply("FIND_IN_SET("+loginUser.getId()+", collaborator) ");
            }else if(QueryRangeTypeEnum.QUERY_SUBORDINATE_COOPERA_SQL.getCode().equals(customerSearchDTO.getQueryRangeType())){
                //下属协作的
                List<Long> subUserIds = userService.getAllSubordinate(loginUser.getId());
                if (CollectionUtils.isEmpty(subUserIds)){
                    return Result.result(pageVO);
                }
                wrapper.and(queryWrapper1->queryWrapper1.apply("CONCAT(',',collaborator,',') REGEXP ',"+concatRegexp(subUserIds)+",'"));
            } else if(QueryRangeTypeEnum.QUERY_TRANSFERRED_CUSTOMER_SQL.getCode().equals(customerSearchDTO.getQueryRangeType())){
                //已转客户
                wrapper.eq(CustomerEntity::getHasFromClue,true);
            }

        }
//        if(!ObjectUtils.isEmpty(customerSearchDTO.getCommonQueryOrderBy()) && customerSearchDTO.getCommonQueryOrderBy().equals("lastFollowUpTime")){
//            if(!ObjectUtils.isEmpty(customerSearchDTO.getSortMethod()) && customerSearchDTO.getSortMethod().equals("desc")) {
//                wrapper.orderByDesc(CustomerEntity::getLastFollowUpTime);
//            }else {
//                wrapper.orderByAsc(CustomerEntity::getLastFollowUpTime);
//            }
//        }
        //权限范围内能看到的所有数据
//        if(QueryRangeTypeEnum.ALL_USER_SQL.getCode().equals(customerSearchDTO.getQueryRangeType())
//                || Integer.valueOf(1).equals(customerSearchDTO.getCommonScope())){
            String v1 = "owner_by = "+loginUser.getId();
            mergeSql.append(v1);
            String v2 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+loginUser.getId()+",managers))";
            mergeSql.append(" or ");
            mergeSql.append(v2);
            List<Long> subUserIds = userService.getAllSubordinate(loginUser.getId());
            if (!CollectionUtils.isEmpty(subUserIds)){
                String v3 = "CONCAT(',',collaborator,',') REGEXP ',"+concatRegexp(subUserIds)+",'";
                mergeSql.append(" or ");
                mergeSql.append(v3);
            }
            String v4 = "FIND_IN_SET("+loginUser.getId()+", collaborator)";
            mergeSql.append(" or ");
            mergeSql.append(v4);
            if (String.valueOf(5).equals(customerSearchDTO.getCustomerTypeDictValue())) {
                String v5 = "owner_by in (select id from `user` WHERE dept_id = "+loginUser.getDeptId()+")";
                mergeSql.append(" or ");
                mergeSql.append(v5);
            }
//        }

//        if (QueryRangeTypeEnum.ALL_USER_SQL.getCode().equals(customerSearchDTO.getQueryRangeType())
//                || Integer.valueOf(1).equals(customerSearchDTO.getCommonScope())){
            if (Boolean.TRUE.equals(customerSearchDTO.getHasPublicCustomer())
                    || Boolean.TRUE.equals(customerSearchDTO.getHasGarbageCustomer())) {
                customerSearchDTO.setReviewTag(1);
                // LoginUserUtil.setReviewTag(1);
            }
            page = pageWithScope(page, wrapper,customerSearchDTO,mergeSql.toString());

            wrapper.select(CustomerEntity::getId);
            int pageIndex1 = customerSearchDTO.getPageIndex() > 5 ? customerSearchDTO.getPageIndex() - 5 : 1;
            IPage<CustomerEntity> pagePre1 = new Page<>(pageIndex1, customerSearchDTO.getPageSize() * 10);
            pagePre1 = pageWithScope(pagePre1, wrapper,customerSearchDTO,mergeSql.toString());
            if(!CollectionUtils.isEmpty(pagePre1.getRecords())) {
                List<Long> cIds = pagePre1.getRecords().stream().map(CustomerEntity::getId).collect(Collectors.toList());
                log.error("ids ----="+cIds);
                redisService.setCacheObject(preNexKey, cIds, 60 * 60L, TimeUnit.SECONDS);
            }

//      }else {
//          page = page(page, wrapper);
//      }

        if (CollectionUtils.isEmpty(page.getRecords())){
            return Result.result(pageVO);
        }
//        List<CustomerListVO> customerListVO = new ArrayList<>();
        //复制list给VO类
//        DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder()
//                .useBuiltinConverters(false)  // 禁用内置转换器（包括 CloneableConverter）
//                .build();
//        List<CustomerListVO> customerListVO = mapperFactory.getMapperFacade().mapAsList(page.getRecords(),CustomerListVO.class);
        List<CustomerListVO> customerListVO = new ArrayList<>();
        for (CustomerEntity entity : page.getRecords()) {
            CustomerListVO vo = new CustomerListVO();
            BeanUtils.copyProperties(entity, vo);
            customerListVO.add(vo);
        }
        //获取企业详细信息
        List<Long> customerIdList = customerListVO.stream().map(CustomerListVO::getId).collect(Collectors.toList());
        Map<Long, CustomerCompanyEntity> customerCompanyMap =  customerCompanyService.customerIdListToCompanyMap(customerIdList);
        //获取首要联系人信息
        Map<Long, LiaisonEntity> liaisonMap = liaisonService.customerIdListToLiaisonMap(customerIdList);
        //补充返回跟进记录
        String type  = ResourceTypeEnum.CUSTOMER.code;
        if (ResourceTypeEnum.CLUS.code.equals(customerSearchDTO.getCustomerForm())){
            type  = ResourceTypeEnum.CLUS.code;
        }
//        Map<Long, CustomerFollowUpLastVO> followUpLastVOMap = customerFollowUpService.getFollowUpLastVOMap(customerIdList,type);
        if (!CollectionUtils.isEmpty(customerListVO)){
            customerListVO.forEach(customerListVO1 -> {
                if (Objects.nonNull(customerCompanyMap)) {
                    CustomerCompanyEntity customerCompanyEntity = customerCompanyMap.get(customerListVO1.getId());
                    if (!ObjectUtils.isEmpty(customerCompanyEntity)){
                        customerListVO1.setCustomerCompany(customerCompanyEntity);
                    }
                }
                if (Objects.nonNull(liaisonMap)) {
                    LiaisonEntity liaisonEntity = liaisonMap.get(customerListVO1.getId());
                    if (!ObjectUtils.isEmpty(liaisonEntity)){
                        customerListVO1.setLiaison(liaisonEntity);
                    }
                }
                //补充最后跟进时间及未跟进时长
                Integer notFollowUpDate = 0;
                if (!ObjectUtils.isEmpty(customerListVO1.getLastFollowUpTime())) {
                    notFollowUpDate = Integer.valueOf((int) ChronoUnit.DAYS.between(customerListVO1.getLastFollowUpTime(), LocalDateTime.now()));
                    if (notFollowUpDate < 0) {
                        notFollowUpDate = 0;
                    }
                }
                customerListVO1.setNotFollowUpDate(notFollowUpDate);
            });
        }
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        pageVO.setRecords(customerListVO);
        pageVO.setCurrent(page.getCurrent());
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        return Result.result(pageVO);
    }

    @Override
    public IPage<?> selectSimpleListVO(CustomerSearchSearchDTO customerSearchSearchDTO,String resourceType) {
        LoginUser loginUser = customerSearchSearchDTO.getLoginUser();
        Long loginUserId = loginUser.getId();

        IPage<CustomerListVO> pageVO =new Page<>(customerSearchSearchDTO.getPageIndex(), customerSearchSearchDTO.getPageSize());

        IPage<CustomerEntity> page = new Page<>(customerSearchSearchDTO.getPageIndex(), customerSearchSearchDTO.getPageSize());
        LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotBlank(customerSearchSearchDTO.getBlurry())) {
            LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customerCompanyEntityLambdaQueryWrapper.eq(CustomerCompanyEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            customerCompanyEntityLambdaQueryWrapper.and(w -> w.like(CustomerCompanyEntity::getWebsite,customerSearchSearchDTO.getBlurry()).or().like(CustomerCompanyEntity::getEmail,customerSearchSearchDTO.getBlurry()));

            List<CustomerCompanyEntity> customerCompanyEntityList = customerCompanyService.list(customerCompanyEntityLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(customerCompanyEntityList)){
                List<Long> customerIds = customerCompanyEntityList.stream().map(CustomerCompanyEntity::getCustomerId).collect(Collectors.toList());
                wrapper.and(w -> w.like(CustomerEntity::getCustomerName,customerSearchSearchDTO.getBlurry()).or().like(CustomerEntity::getDataCode,customerSearchSearchDTO.getBlurry()).or().in(CustomerEntity::getId,customerIds));
            }else {
                wrapper.and(w -> w.like(CustomerEntity::getCustomerName,customerSearchSearchDTO.getBlurry()).or().like(CustomerEntity::getDataCode,customerSearchSearchDTO.getBlurry()));
            }

        }
        //联系人(联系人姓名、联系人邮箱)
        wrapper.eq( CustomerEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        wrapper.eq( CustomerEntity::getCustomerForm,resourceType);

        //根据客户归属分类查询

        StringBuilder mergeSql = new StringBuilder();
        String v1 = "owner_by = "+loginUserId;
        mergeSql.append(v1);
//        String v2 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+loginUser.getId()+",managers))";
        if (!ObjectUtils.isEmpty(customerSearchSearchDTO.getUserIdString())) {
            String v2 = "owner_by in (" + customerSearchSearchDTO.getUserIdString() + ")";
            mergeSql.append(" or ");
            mergeSql.append(v2);
        }
        List<Long> subUserIds = userService.getAllSubordinate(loginUserId);
        if (!CollectionUtils.isEmpty(subUserIds)){
            String v3 = "CONCAT(',',collaborator,',') REGEXP ',"+concatRegexp(subUserIds)+",'";
            mergeSql.append(" or ");
            mergeSql.append(v3);
        }
        String v4 = "FIND_IN_SET("+loginUserId+", collaborator)";
        mergeSql.append(" or ");
        mergeSql.append(v4);
//        }

//        if (QueryRangeTypeEnum.ALL_USER_SQL.getCode().equals(customerSearchDTO.getQueryRangeType())
//                || Integer.valueOf(1).equals(customerSearchDTO.getCommonScope())){
        page = pageWithScope(page, wrapper,customerSearchSearchDTO,mergeSql.toString());
//        }else {
//            page = page(page, wrapper);
//        }

        if (CollectionUtils.isEmpty(page.getRecords())){
            return pageVO;
        }
        //复制list给VO类
        DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<CustomerListVO> customerListVO = mapperFactory.getMapperFacade().mapAsList(page.getRecords(),CustomerListVO.class);
        //获取企业详细信息
        List<Long> customerIdList = customerListVO.stream().map(CustomerListVO::getId).collect(Collectors.toList());
        Map<Long, CustomerCompanyEntity> customerCompanyMap =  customerCompanyService.customerIdListToCompanyMap(customerIdList);
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        pageVO.setRecords(customerListVO);
        pageVO.setCurrent(page.getCurrent());
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());
        return pageVO;
    }

    /**
     * @Description: 查询用户权限范围内客户
     * @Param:
     * @return:
     * @Author: YPZ
     * @Date: 2024/5/21 17:58
     */
    @Override
    public List<Long> getCustomerIdList(Long userId) {
        if (Objects.isNull(userId)){
            userId = LoginUserUtil.getCurrentUserId();
        }
        LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(CustomerEntity::getId);
        wrapper.eq(CustomerEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        List<Long> customerIdList = new ArrayList<>();

        StringBuilder mergeSql = new StringBuilder();
        String v1 = "owner_by = "+userId;
        mergeSql.append(v1);
        String v2 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+userId+",managers))";
        mergeSql.append(" or ");
        mergeSql.append(v2);
        List<Long> subUserIds = userService.getAllSubordinate(userId);
        if (!CollectionUtils.isEmpty(subUserIds)){
            String v3 = "CONCAT(',',collaborator,',') REGEXP ',"+concatRegexp(subUserIds)+",'";
            mergeSql.append(" or ");
            mergeSql.append(v3);
        }
        String v4 = "FIND_IN_SET("+userId+", collaborator)";
        mergeSql.append(" or ");
        mergeSql.append(v4);
        List<CustomerEntity> customerEntityList = listWithScope(wrapper,mergeSql.toString());
        if (CollectionUtils.isEmpty(customerEntityList)){
            return customerIdList;
        }
        customerIdList = customerEntityList.stream().map(CustomerEntity::getId).collect(Collectors.toList());
        return customerIdList;

    }


    /**
     * @Description: 修改全部客户关联业务表关联客户id
     *          关联的业务有：联系人、跟进、邮件、任务、寄样、工单、商机、订单、报价、发票、退款、费用、附件等
     * @Param:
     * @return:
     * @Author: YPZ
     * @Date: 2024/5/21 17:58
     */
    private boolean changeAllCustomerId(Long fromId, Long customerId) {

        boolean changedA = liaisonService.changeCustomerId(fromId, customerId);
        boolean changedA2 = liaisonResourceService.changeResourceTypeId(ResourceTypeEnum.CUSTOMER.code,fromId, customerId);

        boolean changedB = customerFollowUpService.changeCustomerId(fromId, customerId);
        //修改跟进关联客户资源
        boolean changedB2 = customerFollowUpService.changeResourceTypeId(ResourceTypeEnum.CUSTOMER.code,fromId, customerId);

        boolean changedC = taskService.changeCustomerId(fromId, customerId);
        boolean changedC2 = taskService.changeResourceTypeId(ResourceTypeEnum.CUSTOMER.code,fromId, customerId);

        boolean changedD = orderFormService.changeCustomerId(fromId, customerId);

        boolean changedE = sendRecordService.changeCustomerId(fromId, customerId);
        boolean changedE2 = sendRecordService.changeResourceTypeId(ResourceTypeEnum.CUSTOMER.code,fromId, customerId);
        boolean changedJ = sysResourceService.changeCustomerId(fromId, customerId);
        boolean changedJ2 = sysResourceService.changeResourceTypeId(ResourceTypeEnum.CUSTOMER.code,fromId, customerId);

        boolean changedM = mailRecordService.changeCustomerId(fromId, customerId);

        boolean changedF = workOrderService.changeCustomerId(fromId, customerId);

        boolean changedG = customerCompanyService.lgCustomerDelete(fromId);

        boolean changedH = businessService.changeCustomerId(fromId,customerId);
        boolean changedI = quotationService.changeCustomerId(fromId,customerId);
        boolean changedK = customerMailBingMarkService.changeCustomerId(fromId,customerId);

//        boolean changedG = sysResourceService.changeResourceCustomerId(fromId, customerId);
//        if(!changedG){
//            return false;
//        }
        return true;
    }

    private String concatRegexp(List<Long> ids){
        if(ids.size()==0){
            return "-";
        }else {
            return ids.stream().map(String::valueOf).collect(Collectors.joining("|"));
        }
    }
    /***
      * @Description: 判断用户客户/线索是否超过上限
      * @Param:
      * @return: true 超过上限 false 未超过上限
      * @Author: YPZ
      * @Date: 2024/11/1 11:15
      */
    @Override
    public Boolean maxMemberNum(Integer num, Long ownerBy, String resourceType){
        LambdaQueryWrapper<SystemRuleModuleConfigEntity> sysWrapper = new LambdaQueryWrapper<>();
        sysWrapper.eq(SystemRuleModuleConfigEntity::getResourceType, resourceType);
        sysWrapper.last("limit 1");
        SystemRuleModuleConfigEntity systemRuleModuleConfig = systemRuleModuleConfigService.getOne(sysWrapper);
        if (systemRuleModuleConfig.getHasMaxMember()) {
            //查询当前用户是否超过上限
            LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CustomerEntity::getOwnerBy, ownerBy);
            wrapper.eq(CustomerEntity::getCustomerForm, Integer.valueOf(resourceType));
            wrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            Integer customerCount = count(wrapper);
            if (customerCount+num > systemRuleModuleConfig.getMaxMemberNum()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void updateFollowUpTimeByEmail(Set<String> emailsList,LocalDateTime currentTime){
        if (CollectionUtils.isEmpty(emailsList)){
            return;
        }
        List<Long> customerIdList = new ArrayList<>();
        //通过联系人邮箱查询对应的客户
        if (Objects.isNull(currentTime)) {
            currentTime = LocalDateTime.now();
        }

        String inValues = emailsList.stream()
                .map(e -> "'" + e.toLowerCase() + "'")
                .collect(Collectors.joining(","));

        LambdaQueryWrapper<LiaisonEntity> liaisonWrapper = new LambdaQueryWrapper<>();
        liaisonWrapper.select(LiaisonEntity::getId,LiaisonEntity::getCustomerId);
        liaisonWrapper.eq(LiaisonEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        liaisonWrapper.and(qw -> qw.apply("LOWER(email) IN (" + inValues + ")")
                .or()
                .apply("LOWER(email1) IN (" + inValues + ")")
                .or()
                .apply("LOWER(email2) IN (" + inValues + ")")
                .or()
                .apply("LOWER(email3) IN (" + inValues + ")"));

        List<LiaisonEntity> liaisonList = liaisonService.list(liaisonWrapper);
        if (!CollectionUtils.isEmpty(liaisonList)){
            List<Long> customerIds = liaisonList.stream().map(LiaisonEntity::getCustomerId).collect(Collectors.toList());
            List<Long> liaisonIds = liaisonList.stream().map(LiaisonEntity::getId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(customerIds)) {
                customerIdList.addAll(customerIds);
            }
            if (!CollectionUtils.isEmpty(liaisonIds)) {
                LambdaUpdateWrapper<LiaisonEntity> upliaisonWrapper = new LambdaUpdateWrapper<>();
                upliaisonWrapper.in(LiaisonEntity::getId, liaisonIds);
                upliaisonWrapper.set(LiaisonEntity::getLastFollowUpTime, currentTime);
                liaisonService.update(upliaisonWrapper);
            }
        }
        //通过客户邮箱查询对应的客户
        LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyWrapper = new LambdaQueryWrapper<>();
        customerCompanyWrapper.select(CustomerCompanyEntity::getId,CustomerCompanyEntity::getCustomerId);
        customerCompanyWrapper.eq(CustomerCompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        customerCompanyWrapper.and(qw -> qw.apply("LOWER(email) IN (" + inValues + ")")
                .or()
                .apply("LOWER(email1) IN (" + inValues + ")")
                .or()
                .apply("LOWER(email2) IN (" + inValues + ")")
                .or()
                .apply("LOWER(email3) IN (" + inValues + ")"));

        List<CustomerCompanyEntity> customerCompanyList = customerCompanyService.list(customerCompanyWrapper);
        if (!CollectionUtils.isEmpty(customerCompanyList)){
            List<Long> customerIds = customerCompanyList.stream().map(CustomerCompanyEntity::getCustomerId).collect(Collectors.toList());
            customerIdList.addAll(customerIds);
        }

        if (!CollectionUtils.isEmpty(customerIdList)){
            LambdaQueryWrapper<CustomerEntity> l = new LambdaQueryWrapper<>();
            l.in(CustomerEntity::getId,customerIdList);
            List<CustomerEntity> customerEntities = this.list(l);
            if (!CollectionUtils.isEmpty(customerEntities)) {
                List<Long> upCustomerIdList = new ArrayList<>();
                for (CustomerEntity customer : customerEntities) {
                    Date createTime = customer.getCreateTime();
                    if (Objects.isNull(createTime)) {
                        continue;
                    }
                    LocalDateTime localCreateTime = createTime.toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDateTime();
                    if (currentTime.isAfter(localCreateTime) && (Objects.nonNull(customer.getLastFollowUpTime()) && currentTime.isAfter(customer.getLastFollowUpTime()))) {
                        upCustomerIdList.add(customer.getId());
                    }
                }
                if (!CollectionUtils.isEmpty(upCustomerIdList)) {
                    LambdaUpdateWrapper<CustomerEntity> customerWrapper = new LambdaUpdateWrapper<>();
                    customerWrapper.in(CustomerEntity::getId, upCustomerIdList);
                    customerWrapper.set(CustomerEntity::getLastFollowUpTime, currentTime);
                    update(customerWrapper);
                    //补充未跟进天数
                    updateCustomerNoFollowUpDate(upCustomerIdList);
                }
            }
        }
    }

    @Override
    public Set<String> findEmailByCustomerId(Long customerId) {
        if (ObjectUtils.isEmpty(customerId)){
            return new HashSet<>();
        }
        Set<String> emailList = new HashSet<>();
        List<CustomerCompanyEntity> customerCompanyList = customerCompanyService.list(new LambdaQueryWrapper<CustomerCompanyEntity>().eq(CustomerCompanyEntity::getCustomerId,customerId));
        if (!CollectionUtils.isEmpty(customerCompanyList)){
            emailList.addAll(customerCompanyList.stream().map(CustomerCompanyEntity::getEmail).collect(Collectors.toSet()));
        }
        List<LiaisonEntity> liaisonList = liaisonService.list(new LambdaQueryWrapper<LiaisonEntity>().eq(LiaisonEntity::getCustomerId,customerId));
        if (!CollectionUtils.isEmpty(liaisonList)){
            emailList.addAll(liaisonList.stream().map(LiaisonEntity::getEmail).collect(Collectors.toSet()));
        }
        return emailList;
    }

    @Override
    public void addWebClue() {
        LambdaQueryWrapper<SystemConfigItemEntity> systemConfigItemEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemConfigItemEntityLambdaQueryWrapper.eq(SystemConfigItemEntity::getItemCode,"STORLEAD_USER_ID");
        systemConfigItemEntityLambdaQueryWrapper.last("limit 1");
        SystemConfigItemEntity systemConfigItemEntity = systemConfigItemService.getOne(systemConfigItemEntityLambdaQueryWrapper);
        if (ObjectUtils.isEmpty(systemConfigItemEntity)){
            return;
        }
        Long maxUserId = systemConfigItemEntity.getItemFormatValue() == null ? 0 : Long.parseLong(systemConfigItemEntity.getItemFormatValue());
        //查询官网是否有新用户注册
//        LambdaQueryWrapper<UserInfoEntity> userInfoEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        userInfoEntityLambdaQueryWrapper.gt(UserInfoEntity::getUserId,maxUserId);
////        userInfoEntityLambdaQueryWrapper.eq(UserInfoEntity::getInvestedId,null);
//        userInfoEntityLambdaQueryWrapper.isNull(UserInfoEntity::getInvestedId);
//        userInfoEntityLambdaQueryWrapper.ne(UserInfoEntity::getFocusModule,"采购公告");
//        userInfoEntityLambdaQueryWrapper.orderByAsc(UserInfoEntity::getUserId);
        List<UserInfoEntity> userInfoList = userInfoService.queryUserInfoListByType(maxUserId);
        if (CollectionUtils.isEmpty(userInfoList)){
            return;
        }
        Long userId = userInfoList.get(userInfoList.size()-1).getUserId();
        for (UserInfoEntity userInfoEntity : userInfoList) {
            CustomerEntity customerEntity = new CustomerEntity();
            customerEntity.setCustomerForm(11);
            customerEntity.setCustomerName("官网注册客户"+"("+userInfoEntity.getUserId()+")");
            customerEntity.setDataCode(CodeGenerate.generate10Code(CodeGenerateInterface.CUSTOMER_CODE));
            customerEntity.setHasPublicCustomer(true);
            customerEntity.setCustomerSourceDictValue("15");
            String remark = "关注领存:"+userInfoEntity.getFocusModule()+"。意向合作业务:"+userInfoEntity.getCooperationBusinessType()+"。";
            customerEntity.setRemark(remark);
            customerEntity.setOwnerBy(null);
            customerEntity.setLastFollowUpTime(LocalDateTime.now());
            boolean isOk = save(customerEntity);
            if (isOk){
                CustomerCompanyEntity customerCompany = new CustomerCompanyEntity();
                customerCompany.setCustomerId(customerEntity.getId());
                customerCompanyService.save(customerCompany);

                LiaisonEntity liaisonEntity = new LiaisonEntity();
                liaisonEntity.setCustomerId(customerEntity.getId());
                liaisonEntity.setName(userInfoEntity.getUserName());
                liaisonEntity.setTelephone(userInfoEntity.getMobile());
                liaisonEntity.setHasPrimaryLialison(true);
                liaisonEntity.setOwnerBy(null);
                liaisonService.save(liaisonEntity);

                LambdaQueryWrapper<SystemConfigItemEntity> webSystemConfigItemEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                webSystemConfigItemEntityLambdaQueryWrapper.eq(SystemConfigItemEntity::getItemCode,"STORLEAD_MESSAGE_USER_ID");
                webSystemConfigItemEntityLambdaQueryWrapper.last("limit 1");
                SystemConfigItemEntity webSystemConfigItemEntity = systemConfigItemService.getOne(webSystemConfigItemEntityLambdaQueryWrapper);
                if (!ObjectUtils.isEmpty(webSystemConfigItemEntity) && !ObjectUtils.isEmpty(webSystemConfigItemEntity.getItemFormatValue())){
                    //逗号分割的字符串webSystemConfigItemEntity.getItemFormatValue()转为Set<Long>
                    Set<Long> toUserIds = Arrays.stream(webSystemConfigItemEntity.getItemFormatValue().split(",")).map(Long::parseLong).collect(Collectors.toSet());
                    assembleService.sendWebAddClusEventMessages(customerEntity,liaisonEntity,"WEB_ADD_CLUE",toUserIds);

                }

            }


        }
        //对已同步数据做标记
        for (UserInfoEntity userInfo : userInfoList){
            userInfo.setToCrm(true);
        }
        userInfoService.updateBatchById(userInfoList);
        systemConfigItemEntity.setItemFormatValue(userId.toString());
        systemConfigItemService.updateById(systemConfigItemEntity);

    }



    private boolean checkWebsiteDuplicates(CustomerAddDTO customerAddDTO, FieldSimilarityConfigVO rule, String websiteField,
                                           String errorMsg, List<SimilarityErrorVO> errorCanSaveVOList, List<SimilarityErrorVO> errorVOList,
                                           Integer resourceType, BigDecimal similarityValue, String duplicateValue) {

        boolean canSave = true;
        if (ObjectUtils.isEmpty(websiteField)){
            return canSave;
        }
        List<EsQuerySimilarityVO> customerErrList = findErrList("website",customerAddDTO.getId(), websiteField,errorMsg,resourceType,rule.getSimilarityValue());
        changeErrorList(customerErrList,errorVOList,errorCanSaveVOList,rule);
        if (!CollectionUtils.isEmpty(customerErrList)){
            canSave = false;
        }
        return canSave;
    }

    private boolean checkEmailDuplicates(CustomerAddDTO customerAddDTO, FieldSimilarityConfigVO rule, String emailField,
                                         String errorMsg, List<SimilarityErrorVO> errorCanSaveVOList, List<SimilarityErrorVO> errorVOList,
                                         int resourceType, BigDecimal similarityValue, String duplicateValue){
        boolean canSave = true;
        if (ObjectUtils.isEmpty(emailField)){
            return canSave;
        }
        List<EsQuerySimilarityVO> customerErrList = findErrList("email",customerAddDTO.getId(), emailField,errorMsg,resourceType,rule.getSimilarityValue());
        changeErrorList(customerErrList,errorVOList,errorCanSaveVOList,rule);
        if (!CollectionUtils.isEmpty(customerErrList)){
            canSave = false;
        }
        return canSave;

    }

    private boolean checkCompanyEmailDuplicates(CustomerAddDTO customerAddDTO, FieldSimilarityConfigVO rule, String emailField,
                                                String errorMsg, List<SimilarityErrorVO> errorCanSaveVOList, List<SimilarityErrorVO> errorVOList,
                                                int resourceType, BigDecimal similarityValue, String duplicateValue) {
        boolean canSave = true;
        if (ObjectUtils.isEmpty(emailField)){
            return canSave;
        }
        List<EsQuerySimilarityVO> customerErrList = findErrList("email",customerAddDTO.getId(), emailField,errorMsg,resourceType,rule.getSimilarityValue());
        changeErrorList(customerErrList,errorVOList,errorCanSaveVOList,rule);
        if (!CollectionUtils.isEmpty(customerErrList)){
            canSave = false;
        }
        return canSave;
    }


    @Override
    public List<String> assembleLiaisonMails(LiaisonEntity liaisonEntity) {
        List<String> mails = new ArrayList<>();
        if (StrUtil.isNotBlank(liaisonEntity.getEmail())) {
            mails.add(liaisonEntity.getEmail());
        }
        if (StrUtil.isNotBlank(liaisonEntity.getEmail1())) {
            mails.add(liaisonEntity.getEmail1());
        }
        if (StrUtil.isNotBlank(liaisonEntity.getEmail2())) {
            mails.add(liaisonEntity.getEmail2());
        }
        if (StrUtil.isNotBlank(liaisonEntity.getEmail3())) {
            mails.add(liaisonEntity.getEmail3());
        }
        return mails;
    }
    @Override
    public List<String> assembleCustomerMails(CustomerCompanyEntity customerEntity) {
        List<String> mails = new ArrayList<>();
        if (StrUtil.isNotBlank(customerEntity.getEmail())) {
            mails.add(customerEntity.getEmail());
        }
        if (StrUtil.isNotBlank(customerEntity.getEmail1())) {
            mails.add(customerEntity.getEmail1());
        }
        if (StrUtil.isNotBlank(customerEntity.getEmail2())) {
            mails.add(customerEntity.getEmail2());
        }
        if (StrUtil.isNotBlank(customerEntity.getEmail3())) {
            mails.add(customerEntity.getEmail3());
        }
        return mails;
    }

    @Override
    public void updateCustomerNoFollowUpDate(List<Long> idList) {
        baseMapper.updateCustomerNoFollowUpDate(idList);
    }

    @Override
    public Result<?> chengeClusStatus(CustomerAddDTO customerAddDTO) {
        CustomerEntity customerEntity = new CustomerEntity();
        BeanUtils.copyProperties(customerAddDTO, customerEntity);
        boolean isOk = this.updateById(customerEntity);
        if (isOk) {
            return Result.ok();
        }
        return Result.error("操作失败！");
    }

    @Override
    public void replaceCollaborator(CustomerTransferDTO customerTransferDTO) {
        customerTransferDTO.setOldOwnerBy(customerTransferDTO.getOldOwnerByIdls().get(0));
        baseMapper.replaceCollaborator(customerTransferDTO);
    }

}
