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.google.gson.Gson;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.HtmlUtils;
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.sales.enums.QueryRangeTypeEnum;
import com.storlead.sales.pojo.dto.customer.CustomerSearchSearchDTO;
import com.storlead.sales.pojo.dto.customer.LiaisonAddDTO;
import com.storlead.sales.pojo.dto.customer.LiaisonSearchDTO;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.vo.customer.BusinessListVO;
import com.storlead.sales.pojo.vo.customer.CustomerListVO;
import com.storlead.sales.pojo.vo.customer.CustomerVO;
import com.storlead.sales.pojo.vo.customer.LiaisonListVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.pojo.entity.systemrule.SystemRuleModuleConfigEntity;
import com.storlead.sales.pojo.vo.systemrule.FieldSimilarityConfigVO;
import com.storlead.sales.mapper.customer.LiaisonMapper;
import com.storlead.sales.service.customer.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.storlead.sales.service.CustomerMailBingMarkService;
import com.storlead.sales.service.systemrule.SystemRuleModuleConfigService;
import com.storlead.sales.service.task.TaskService;
import com.storlead.sales.util.SystemRuleModuleUtils;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 联系人表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-04-12
 */
@Service
public class LiaisonServiceImpl extends MyBaseServiceImpl<LiaisonMapper, LiaisonEntity> implements LiaisonService {

    @Resource
    private CustomerService customerService;
    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Resource
    private TaskService taskService;
    @Resource
    private SystemRuleModuleConfigService systemRuleModuleConfigService;
    @Resource
    private LiaisonResourceService liaisonResourceService;
    @Resource
    private CustomerMailBingMarkService customerMailBingMarkService;
    @Resource
    private WorkDynamicsService workDynamicsService;
    @Override
    public Result<?> addOrEdit(LiaisonAddDTO locationAddDTO) {
        if (ObjectUtils.isEmpty(locationAddDTO)){
            return Result.error("参数不能为空");
        }
        if (Objects.nonNull(locationAddDTO.getCustomerId())) {
            CustomerEntity customer = customerService.getById(locationAddDTO.getCustomerId());
            if (ObjectUtils.isEmpty(customer)){
                return Result.error("客户不存在");
            }
        }
        boolean isAdd = false;
        if (ObjectUtils.isEmpty(locationAddDTO.getId())){
            isAdd = true;
        }

        Long ownerBy = LoginUserUtil.getCurrentUserId();
        if (ObjectUtils.isEmpty(locationAddDTO.getOwnerBy())){
            ownerBy = locationAddDTO.getOwnerBy();
        }


        LambdaQueryWrapper<SystemRuleModuleConfigEntity> sysWrapper = new LambdaQueryWrapper<>();
            //联系人规则
            sysWrapper.eq(SystemRuleModuleConfigEntity::getResourceType, ResourceTypeEnum.LIAISON.code);
            sysWrapper.last("limit 1");
            SystemRuleModuleConfigEntity systemRuleModuleConfig = systemRuleModuleConfigService.getOne(sysWrapper);

            //验证规则
            if (!ObjectUtils.isEmpty(systemRuleModuleConfig)){
                if (systemRuleModuleConfig.getHasPlagiarismRules()){
                    LambdaQueryWrapper<LiaisonEntity> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(LiaisonEntity::getOwnerBy, ownerBy);
                    wrapper.eq(LiaisonEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
                    List<LiaisonEntity> customerEntities = list(wrapper);
                    if (!CollectionUtils.isEmpty(customerEntities)) {
                        List<FieldSimilarityConfigVO> rules = JSON.parseArray(systemRuleModuleConfig.getPlagiarismRules(), FieldSimilarityConfigVO.class);
                        Result canAddResult = SystemRuleModuleUtils.checkFieldSimilarity(locationAddDTO, customerEntities, rules,ResourceTypeEnum.LIAISON.code);
                        if (!canAddResult.isSuccess()){
                            return canAddResult;
                        }
                    }
                }
            }


        LiaisonEntity oldLiaison = Objects.nonNull(locationAddDTO.getId()) ? getById(locationAddDTO.getId()) : null;
        LiaisonEntity latest = new LiaisonEntity();
        BeanUtils.copyProperties(locationAddDTO, latest);

        //如果是首要联系人，需要判断是否已经存在其他首要联系人
        if (!ObjectUtils.isEmpty(latest.getHasPrimaryLialison()) && latest.getHasPrimaryLialison()){
            if (!ObjectUtils.isEmpty(latest.getCustomerId())){
                LambdaQueryWrapper<LiaisonEntity> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(LiaisonEntity::getCustomerId, latest.getCustomerId());
                wrapper.eq(LiaisonEntity::getHasPrimaryLialison, true);
                wrapper.ne(LiaisonEntity::getId, latest.getId());
                wrapper.eq(LiaisonEntity::getIsDelete, false);
                wrapper.last("limit 1");
                LiaisonEntity liaisonOther = this.getOne(wrapper);
                if (!ObjectUtils.isEmpty(liaisonOther)){
                    return Result.error("该客户已有首要联系人，请先修改/删除其他首要联系人");
                }
            }
        }
        if (isAdd){
            latest.setLastFollowUpTime(LocalDateTime.now());
        }
        boolean isOk = this.saveOrUpdate(latest);
        if (isOk){
            if (isAdd){
                List<LiaisonResourceEntity> liaisonResourceList = new ArrayList<>();
                LiaisonResourceEntity liaisonResource = new LiaisonResourceEntity();
                liaisonResource.setResourceType(ResourceTypeEnum.CUSTOMER.code);
                liaisonResource.setResourceTypeId(latest.getCustomerId());
                liaisonResource.setLiaisonId(latest.getId());
                liaisonResourceList.add(liaisonResource);

                if (!ObjectUtils.isEmpty(locationAddDTO.getResourceType()) && !locationAddDTO.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code) && !locationAddDTO.getResourceType().equals(ResourceTypeEnum.CLUS.code)){
                    LiaisonResourceEntity liaisonResourceB = new LiaisonResourceEntity();
                    liaisonResourceB.setResourceType(locationAddDTO.getResourceType());
                    liaisonResourceB.setResourceTypeId(locationAddDTO.getResourceTypeId());
                    liaisonResourceB.setLiaisonId(latest.getId());
                    liaisonResourceList.add(liaisonResourceB);
                }
                liaisonResourceService.saveBatch(liaisonResourceList);

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

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

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

            if (!ObjectUtils.isEmpty(locationAddDTO.getTask())){

                locationAddDTO.getTask().setResourceType(ResourceTypeEnum.LIAISON.code);
                locationAddDTO.getTask().setResourceTypeId(latest.getId());
                taskService.addTask(locationAddDTO.getTask().setCustomerId(latest.getCustomerId()));
            }
            List<String> lmails = customerService.assembleLiaisonMails(latest);
            if (isAdd && Objects.nonNull(latest.getCustomerId())) {
                customerMailBingMarkService.updateCustomerLiaisonMailBingMark(latest.getCustomerId(),latest.getId(),lmails);
            } else if (!isAdd && Objects.nonNull(oldLiaison) && !CollectionUtils.isEmpty(lmails) && !oldLiaison.getEmail().equals(latest.getEmail())){
                customerMailBingMarkService.updateCustomerLiaisonMailBingMark(latest.getCustomerId(),latest.getId(),lmails);
            }
            return Result.result("操作成功");
        }
        return Result.error("处理失败!");
    }



    @Override
    public Result<?> selectListVO(LiaisonSearchDTO liaisonSearchDTO) {
        if (!ObjectUtils.isEmpty(liaisonSearchDTO.getResourceType()) && !ObjectUtils.isEmpty(liaisonSearchDTO.getResourceTypeId())){
            return listByResource(liaisonSearchDTO);
        }
        Long loginUserId = LoginUserUtil.getCurrentUserId();

        IPage<LiaisonListVO> pageVO = new Page<>(liaisonSearchDTO.getPageIndex(), liaisonSearchDTO.getPageSize());
        if (liaisonSearchDTO.getCorrelation() == 1 && ObjectUtils.isEmpty(liaisonSearchDTO.getCustomerId())){
            return Result.result(pageVO);
        }
        IPage<LiaisonEntity> page = new Page<>(liaisonSearchDTO.getPageIndex(), liaisonSearchDTO.getPageSize());
        LambdaQueryWrapper<LiaisonEntity> wrapper = new LambdaQueryWrapper<>();

        wrapper.and(!ObjectUtils.isEmpty(liaisonSearchDTO.getLiaisonName()),w -> w.like(LiaisonEntity::getName,liaisonSearchDTO.getLiaisonName()).or().like(LiaisonEntity::getEmail,liaisonSearchDTO.getLiaisonName()));

        if (StrUtil.isNotBlank(liaisonSearchDTO.getCustomerName())) {
            LambdaQueryWrapper<CustomerEntity> customerEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customerEntityLambdaQueryWrapper.eq(CustomerEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            customerEntityLambdaQueryWrapper.and(w -> w.like(CustomerEntity::getCustomerName,liaisonSearchDTO.getCustomerName()));

            List<CustomerEntity> customerEntityList = customerService.list(customerEntityLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(customerEntityList)){
                List<Long> customerIds = customerEntityList.stream().map(CustomerEntity::getId).collect(Collectors.toList());
                wrapper.in(LiaisonEntity::getCustomerId,customerIds);
            }else {
                return Result.result(pageVO);
            }
        }

        wrapper.eq(!ObjectUtils.isEmpty(liaisonSearchDTO.getCustomerId()), LiaisonEntity::getCustomerId, liaisonSearchDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(liaisonSearchDTO.getId()), LiaisonEntity::getId, liaisonSearchDTO.getId());
        wrapper.ne(!ObjectUtils.isEmpty(liaisonSearchDTO.getNonId()), LiaisonEntity::getId, liaisonSearchDTO.getNonId());
        wrapper.eq(LiaisonEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(liaisonSearchDTO.getBlurry())) {
            wrapper.and(w ->w.like(LiaisonEntity::getName,liaisonSearchDTO.getBlurry()).or().like(LiaisonEntity::getEmail,liaisonSearchDTO.getBlurry()));
        }
        wrapper.eq(!ObjectUtils.isEmpty(liaisonSearchDTO.getBirthday()), LiaisonEntity::getBirthday, liaisonSearchDTO.getBirthday());
        wrapper.like(!ObjectUtils.isEmpty(liaisonSearchDTO.getLiaisonName()), LiaisonEntity::getName, liaisonSearchDTO.getLiaisonName());
        wrapper.eq(!ObjectUtils.isEmpty(liaisonSearchDTO.getLiaisonRoleDictValue()), LiaisonEntity::getLiaisonRoleDictValue, liaisonSearchDTO.getLiaisonRoleDictValue());
        wrapper.ge(!ObjectUtils.isEmpty(liaisonSearchDTO.getLastFollowUpBeginTime()), LiaisonEntity::getLastFollowUpTime, liaisonSearchDTO.getLastFollowUpBeginTime());
        wrapper.le(!ObjectUtils.isEmpty(liaisonSearchDTO.getLastFollowUpEndTime()), LiaisonEntity::getLastFollowUpTime, liaisonSearchDTO.getLastFollowUpEndTime());
        wrapper.in(!CollectionUtils.isEmpty(liaisonSearchDTO.getOwnerByIds()),LiaisonEntity::getOwnerBy, liaisonSearchDTO.getOwnerByIds());
//        wrapper.orderByDesc(LiaisonEntity::getHasPrimaryLialison,LiaisonEntity::getId);
        if (Objects.nonNull(liaisonSearchDTO.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(liaisonSearchDTO.getQueryRangeType(),LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                wrapper.apply(queryRangeSql);
            }
        }

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

        StringBuilder mergeSql = new StringBuilder();

        String v1 = StrUtil.isBlank(customerIdString) ? "" : " customer_id in ( "+customerIdString +") or ";
        mergeSql.append(v1);

        String v2 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+loginUserId+",managers))";
        mergeSql.append(v2);

        IPage<LiaisonEntity> pageList = this.pageWithScope(page, wrapper,liaisonSearchDTO,mergeSql.toString());
        if (CollectionUtils.isEmpty(pageList.getRecords())){
            return Result.result(pageList);
        }
        for (LiaisonEntity l : pageList.getRecords()){
            if (l.getHasPrimaryLialison()){
                l.setName("(首)"+l.getName());
            }
            if (Objects.isNull(l.getLastFollowUpTime()) && Objects.nonNull(l.getCreateTime())) {
                LocalDateTime localDateTime = l.getCreateTime().toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                l.setLastFollowUpTime(localDateTime);
            }
        }
//        List<LiaisonListVO> list = new ArrayList<>();
        //复制list给VO类

        pageVO = SysBaseField.page(page, LiaisonListVO.class);
        Set<Long> customerIdList = pageList.getRecords().stream().filter(e->e.getCustomerId()!=null).map(LiaisonEntity::getCustomerId).collect(Collectors.toSet());
        Map<Long, CustomerEntity>  customerMap = customerService.getCustomerMap(customerIdList);
        if (Objects.nonNull(customerMap)) {
            for (LiaisonListVO liaisonvo : pageVO.getRecords()) {
                if (Objects.nonNull(liaisonvo.getCustomerId())) {
                    CustomerEntity customer = customerMap.get(liaisonvo.getCustomerId());
                    if (Objects.nonNull(customer)){
                        liaisonvo.setCustomerName(customer.getCustomerName());
                        liaisonvo.setCustomerForm(customer.getCustomerForm());
                    }
                }
            }
        }
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        return Result.result(pageVO);
    }

    @Override
    public IPage<?> selectSimpleListVO(CustomerSearchSearchDTO customerSearchSearchDTO) {

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

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

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


        wrapper.eq(LiaisonEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(customerSearchSearchDTO.getBlurry())) {
            wrapper.and(w ->w.like(LiaisonEntity::getName,customerSearchSearchDTO.getBlurry()).or().like(LiaisonEntity::getEmail,customerSearchSearchDTO.getBlurry()));
        }
        if (StrUtil.isNotBlank(customerSearchSearchDTO.getCustomerName())) {
            LambdaQueryWrapper<CustomerEntity> customerEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customerEntityLambdaQueryWrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            customerEntityLambdaQueryWrapper.like(CustomerEntity::getCustomerName, customerSearchSearchDTO.getCustomerName());
            List<CustomerEntity> customerEntityList = customerService.list(customerEntityLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(customerEntityList)){
                List<Long> customerIds = customerEntityList.stream().map(CustomerEntity::getId).collect(Collectors.toList());
                wrapper.in(LiaisonEntity::getCustomerId,customerIds);
            }else {
                return pageVO;
            }
        }

        StringBuilder mergeSql = new StringBuilder();

        String v1 = StrUtil.isBlank(customerSearchSearchDTO.getCustomerIdString()) ? "" : " customer_id in ( "+customerSearchSearchDTO.getCustomerIdString() +") ";
        mergeSql.append(v1);

//        String v2 = "owner_by in ("+customerSearchSearchDTO.getUserIdString()+")";
//        mergeSql.append(v2);

        IPage<LiaisonEntity> pageList = this.pageWithScope(page, wrapper,customerSearchSearchDTO,mergeSql.toString());
        if (CollectionUtils.isEmpty(pageList.getRecords())){
            return pageList;
        }
        for (LiaisonEntity l : pageList.getRecords()){
            if (l.getHasPrimaryLialison()){
                l.setName("(首)"+l.getName());
            }
        }
//        List<LiaisonListVO> list = new ArrayList<>();
        //复制list给VO类

        pageVO = SysBaseField.page(page, LiaisonListVO.class);
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        return pageVO;
    }

    @Override
    public Result<?> listByResource(LiaisonSearchDTO liaisonSearchDTO) {
        IPage<LiaisonListVO> pageVO = new Page<>(liaisonSearchDTO.getPageIndex(), liaisonSearchDTO.getPageSize());
        IPage<LiaisonEntity> page = new Page<>(liaisonSearchDTO.getPageIndex(), liaisonSearchDTO.getPageSize());
        //查询资源对应联系人id
        LambdaQueryWrapper<LiaisonResourceEntity> liaisonResourceWrapper = new LambdaQueryWrapper<>();
        liaisonResourceWrapper.eq(LiaisonResourceEntity::getResourceTypeId, liaisonSearchDTO.getResourceTypeId());
        liaisonResourceWrapper.eq(LiaisonResourceEntity::getResourceType, liaisonSearchDTO.getResourceType());
        liaisonResourceWrapper.eq(LiaisonResourceEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        List<LiaisonResourceEntity> resourceList = liaisonResourceService.list(liaisonResourceWrapper);
        if (CollectionUtils.isEmpty(resourceList)){
            return Result.result(pageVO);
        }
        List<Long> liaisonIdList = resourceList.stream().map(LiaisonResourceEntity::getLiaisonId).collect(Collectors.toList());


        LambdaQueryWrapper<LiaisonEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(liaisonSearchDTO.getCustomerId()), LiaisonEntity::getCustomerId, liaisonSearchDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(liaisonSearchDTO.getId()), LiaisonEntity::getId, liaisonSearchDTO.getId());
        wrapper.in(!ObjectUtils.isEmpty(liaisonIdList), LiaisonEntity::getId, liaisonIdList);
        wrapper.eq(LiaisonEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(liaisonSearchDTO.getBlurry())) {
            wrapper.and(w ->w.like(LiaisonEntity::getName,liaisonSearchDTO.getBlurry()).or().like(LiaisonEntity::getEmail,liaisonSearchDTO.getBlurry()));
        }
        wrapper.eq(!ObjectUtils.isEmpty(liaisonSearchDTO.getBirthday()), LiaisonEntity::getBirthday, liaisonSearchDTO.getBirthday());
        wrapper.eq(!ObjectUtils.isEmpty(liaisonSearchDTO.getLiaisonRoleDictValue()), LiaisonEntity::getLiaisonRoleDictValue, liaisonSearchDTO.getLiaisonRoleDictValue());
        wrapper.ge(!ObjectUtils.isEmpty(liaisonSearchDTO.getLastFollowUpBeginTime()), LiaisonEntity::getLastFollowUpTime, liaisonSearchDTO.getLastFollowUpBeginTime());
        wrapper.le(!ObjectUtils.isEmpty(liaisonSearchDTO.getLastFollowUpEndTime()), LiaisonEntity::getLastFollowUpTime, liaisonSearchDTO.getLastFollowUpEndTime());

        wrapper.orderByDesc(LiaisonEntity::getId);
        IPage<LiaisonEntity> pageList = this.page(page, wrapper);
        if (CollectionUtils.isEmpty(pageList.getRecords())){
            return Result.result(pageList);
        }
//        List<LiaisonListVO> list = new ArrayList<>();
        //复制list给VO类

        pageVO = SysBaseField.page(page, LiaisonListVO.class);
        Set<Long> customerIdList = pageList.getRecords().stream().filter(e->e.getCustomerId()!=null).map(LiaisonEntity::getCustomerId).collect(Collectors.toSet());
        Map<Long, CustomerEntity>  customerMap = customerService.getCustomerMap(customerIdList);
        for (LiaisonListVO liaisonvo : pageVO.getRecords()){
            if (!ObjectUtils.isEmpty(customerMap.get(liaisonvo.getCustomerId()))){
                liaisonvo.setCustomerName(customerMap.get(liaisonvo.getCustomerId()).getCustomerName());
            }
        }
//        customerService.setCustomerNames(pageList.getRecords());
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        return Result.result(pageVO);
    }

    @Override
    public Result<?> changePrimaryLialison(LiaisonSearchDTO liaisonSearchDTO) {
        if (ObjectUtils.isEmpty(liaisonSearchDTO.getId()) || ObjectUtils.isEmpty(liaisonSearchDTO.getCustomerId())){
            return Result.error("参数异常");
        }
        //取消客户首要联系人
        LambdaUpdateWrapper<LiaisonEntity> liaisonUpdateWrapper = new LambdaUpdateWrapper<>();
        liaisonUpdateWrapper.eq(LiaisonEntity::getCustomerId,liaisonSearchDTO.getCustomerId())
                .eq(LiaisonEntity::getHasPrimaryLialison,true)
                .set(LiaisonEntity::getHasPrimaryLialison,false);
        update(liaisonUpdateWrapper);
        //设置新的首要联系人
        LambdaUpdateWrapper<LiaisonEntity> liaisonChangeWrapper = new LambdaUpdateWrapper<>();
        liaisonChangeWrapper.eq(LiaisonEntity::getId,liaisonSearchDTO.getId())
                .set(LiaisonEntity::getHasPrimaryLialison,true);
        boolean update = update(liaisonChangeWrapper);
        if (update){
            return Result.result("更新首要联系人成功");
        }
        return Result.error("更新首要联系人失败");
    }


    @Override
    public Map<Long, LiaisonEntity> idListToLiaisonMap(List<Long> liaisonList) {

        if (!CollectionUtils.isEmpty(liaisonList)){
            List<LiaisonEntity> liaisonEntities = baseMapper.selectBatchIds(liaisonList);
            if (!CollectionUtils.isEmpty(liaisonEntities)){
                return liaisonEntities.stream().collect(Collectors.toMap(LiaisonEntity::getId, Function.identity()));
            }
        }
        return null;
    }

    @Override
    public Map<Long, LiaisonEntity> customerIdListToLiaisonMap(List<Long> customerIdList) {
        List<LiaisonEntity> liaisonEntities = baseMapper.selectList(new LambdaQueryWrapper<LiaisonEntity>().in(LiaisonEntity::getCustomerId, customerIdList).eq(LiaisonEntity::getHasPrimaryLialison,true));
//        List<Long> liaisonIds = liaisonEntities.stream().map(LiaisonEntity::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(liaisonEntities)){
            SysBaseField.dictFileds(liaisonEntities);
            return liaisonEntities.stream().collect(Collectors.toMap(LiaisonEntity::getCustomerId, Function.identity(),(existing, replacement) -> existing));
        }
        return null;

    }

    @Override
    public LiaisonEntity getByCustomerId(Long customerId) {
        if (!ObjectUtils.isEmpty(customerId)){
            LiaisonEntity liaison = baseMapper.selectOne(new LambdaQueryWrapper<LiaisonEntity>().eq(LiaisonEntity::getCustomerId, customerId).eq(LiaisonEntity::getHasPrimaryLialison,true).last("limit 1"));
//            liaison.dictFiled();
            return liaison;
        }
        return null;
    }

    @Override
    public List<LiaisonEntity> getLiaisonByCustomerId(Long customerId) {
        if (Objects.nonNull(customerId)){
            List<LiaisonEntity> liaisons = baseMapper.selectList(new LambdaQueryWrapper<LiaisonEntity>().eq(LiaisonEntity::getCustomerId, customerId));
//            liaison.dictFiled();
            return liaisons;
        }
        return null;
    }

    @Override
    public LiaisonListVO getLiaisonById(Long id) {
        LiaisonListVO liaisonListVO = new LiaisonListVO();
        LiaisonEntity liaison = baseMapper.selectById(id);
        BeanUtils.copyProperties(liaison,liaisonListVO);
        SysBaseField.orgFileds(liaisonListVO);
        liaisonListVO.dictFiled();
        //添加客户信息
        CustomerEntity customerEntity = customerService.getById(liaison.getCustomerId());
        if (!ObjectUtils.isEmpty(customerEntity)) {
            liaisonListVO.setCustomerName(customerEntity.getCustomerName());
            liaisonListVO.setCustomerForm(customerEntity.getCustomerForm());
            liaisonListVO.setCustomerStatusDictValue(customerEntity.getCustomerStatusDictValue());
            liaisonListVO.setClueStatusDictValue(customerEntity.getClueStatusDictValue());
        }

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

        //添加最后跟进时间
        LocalDateTime lastFollowUpTime = customerFollowUpService.getLastFollowUpTime(liaisonListVO.getId(), ResourceTypeEnum.LIAISON.code);
        if (Objects.isNull(lastFollowUpTime)) {
            if (Objects.nonNull(liaison.getCreateTime())) {
                LocalDateTime localDateTime = liaison.getCreateTime().toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                liaisonListVO.setLastFollowUpTime(localDateTime);
            }
        }else {
            liaisonListVO.setLastFollowUpTime(lastFollowUpTime);
        }
        //添加下次跟进时间
        LocalDateTime nextFollowUpTime = taskService.getNextFollowUpTime(liaisonListVO.getId(), ResourceTypeEnum.LIAISON.code);
        liaisonListVO.setNextFollowUpTime(nextFollowUpTime);

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

            liaisonListVO.setResourceName(resourceName);
        }
        if (Objects.nonNull(liaisonListVO)) {
            liaisonListVO.dictFiled();
        }
        return liaisonListVO;
    }

    @Override
    public Result<?> getPrimaryLialison(LiaisonSearchDTO liaisonSearchDTO) {
        LambdaQueryWrapper<LiaisonEntity> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtils.isEmpty(liaisonSearchDTO.getCustomerId())){
            return Result.error("客户id不能为空");
        }
        wrapper.eq( LiaisonEntity::getCustomerId, liaisonSearchDTO.getCustomerId());
        wrapper.eq(LiaisonEntity::getHasPrimaryLialison,true);
        wrapper.eq(LiaisonEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        wrapper.last("limit 1");
        LiaisonEntity liaison = baseMapper.selectOne(wrapper);
        LiaisonListVO liaisonListVO = new LiaisonListVO();
        BeanUtils.copyProperties(liaison,liaisonListVO);
        SysBaseField.orgFileds(liaisonListVO);
        return Result.result(liaisonListVO);
    }


}
