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.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.CodeGenerateInterface;
import com.storlead.framework.common.constant.CommonConstant;
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.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.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.sku.QuotationEntity;
import com.storlead.sales.mapper.customer.BusinessMapper;
import com.storlead.sales.service.customer.*;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.service.sku.QuotationService;
import com.storlead.sales.service.sku.SsdSkuService;
import com.storlead.sales.service.task.TaskService;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
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.math.BigDecimal;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商机表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-05-10
 */
@Service
public class BusinessServiceImpl extends MyBaseServiceImpl<BusinessMapper, BusinessEntity> implements BusinessService {

    @Resource
    private TaskService taskService;
    @Resource
    private CustomerService customerService;
    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Resource
    private IUserService userService;
    @Resource
    private QuotationService quotationService;
    @Resource
    private OrderFormService orderFormService;
    @Resource
    private SsdSkuService ssdSkuService;

    @Resource
    private LiaisonService liaisonService;
    @Resource
    private MessageAssembleService assembleService;
    @Resource
    private LiaisonResourceService liaisonResourceService;
    @Resource
    private WorkDynamicsService workDynamicsService;
    @Resource
    private RedisService redisService;
    @Override
    public Result<?> addBusiness(BusinessAddDTO businessAddDTO) {
        BusinessEntity businessEntity = new BusinessEntity();
        if (ObjectUtils.isEmpty(businessAddDTO)){
            return Result.error("参数不能为空");
        }
        if (ObjectUtils.isEmpty(businessAddDTO.getEstimatedSalesAmount())){
            businessAddDTO.setEstimatedSalesAmount(BigDecimal.ZERO);
        }
        boolean isAdd = false;
        if (ObjectUtils.isEmpty(businessAddDTO.getId())){
            isAdd = true;
        }
        if (!ObjectUtils.isEmpty(businessAddDTO.getCollaboratorList())){
            String collaborator = String.join(",", businessAddDTO.getCollaboratorList().stream()
                    .map(Object::toString)
                    .toArray(String[]::new));
            businessEntity.setCollaborator(collaborator);
        }

        BeanUtils.copyProperties(businessAddDTO, businessEntity);
        Long ownerBy = LoginUserUtil.getCurrentUserId();
        if (ObjectUtils.isEmpty(businessAddDTO.getOwnerBy())){
            ownerBy = businessAddDTO.getOwnerBy();
        }
        //在添加商机时，根据币种和汇率，计算出估计的销售金额
        if (businessAddDTO.getCurrency() == 1) {
            businessEntity.setCurrency(businessAddDTO.getCurrency());
            BigDecimal defaultExchangeRate = BigDecimal.ONE;
            businessEntity.setExchangeRate(defaultExchangeRate);
            businessEntity.setEstimatedSalesAmount(businessEntity.getInitialSalesAmount());
        } else if (businessAddDTO.getCurrency() == 2) {
            // 现获取汇率方法只支持美元
            BigDecimal exchangeRate = ssdSkuService.getRate();
            businessEntity.setCurrency(businessAddDTO.getCurrency());
            businessEntity.setExchangeRate(exchangeRate);
            if (ObjectUtils.isEmpty(businessEntity.getInitialSalesAmount())){
                businessEntity.setInitialSalesAmount(BigDecimal.ZERO);
            }
            businessEntity.setEstimatedSalesAmount(
                businessEntity.getInitialSalesAmount().multiply(exchangeRate).setScale(2, RoundingMode.HALF_UP)
            );
        }
        if (ObjectUtils.isEmpty(businessAddDTO.getId())){
            businessEntity.setDataCode(CodeGenerate.generate10Code(CodeGenerateInterface.BUSINESS_CODE));
        }
        boolean success = saveOrUpdate(businessEntity);
        if (success){
            if (!ObjectUtils.isEmpty(businessAddDTO.getLiaisonId())){
                if (!isAdd){
                    LambdaUpdateWrapper<LiaisonResourceEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.eq(LiaisonResourceEntity::getResourceTypeId, businessAddDTO.getId());
                    lambdaUpdateWrapper.eq(LiaisonResourceEntity::getResourceType, ResourceTypeEnum.BUSINESS.code);
                    lambdaUpdateWrapper.eq(LiaisonResourceEntity::getLiaisonId, businessAddDTO.getLiaisonId());
                    lambdaUpdateWrapper.set(LiaisonResourceEntity::getIsDelete, CommonConstant.DEL_FLAG_1);
                    liaisonResourceService.update(lambdaUpdateWrapper);
                }
                LiaisonResourceEntity liaisonResourceEntity = new LiaisonResourceEntity();
                liaisonResourceEntity.setResourceTypeId(businessEntity.getId());
                liaisonResourceEntity.setResourceType(ResourceTypeEnum.BUSINESS.code);
                liaisonResourceEntity.setLiaisonId(businessAddDTO.getLiaisonId());
                liaisonResourceService.save(liaisonResourceEntity);
            }
            if (!ObjectUtils.isEmpty(businessAddDTO.getTask())){

                businessAddDTO.getTask().setResourceType(ResourceTypeEnum.BUSINESS.code);
                businessAddDTO.getTask().setResourceTypeId(businessEntity.getId());
                taskService.addTask(businessAddDTO.getTask().setCustomerId(businessEntity.getCustomerId()));
            }


            if (isAdd == true){
                //添加商机工作动态
                WorkDynamicsEntity workDynamicsBusiness = new WorkDynamicsEntity();
                workDynamicsBusiness.setCustomerId(businessEntity.getCustomerId());
                workDynamicsBusiness.setOperationType(1);
                workDynamicsBusiness.setResourceType(ResourceTypeEnum.BUSINESS.code);
                workDynamicsBusiness.setResourceTypeId(businessEntity.getId());
                workDynamicsBusiness.setTitle("创建商机"+ HtmlUtils.clearContent(businessEntity.getTitle()));
                workDynamicsBusiness.setOwnerBy(ownerBy);

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

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

                assembleService.sendBusinessEventMessages(businessEntity.getId(),"ADD_OPPORTUNITY");
            }else {
                Set<Long> userIds = new HashSet<>();
                if (!ObjectUtils.isEmpty(businessAddDTO.getCollaboratorList())){
                    userIds.addAll(businessAddDTO.getCollaboratorList());
                    assembleService.sendBusinessEventMessages(businessEntity.getId(),"DATA_CHANGE",userIds);
                }else {
                    assembleService.sendBusinessEventMessages(businessEntity.getId(),"DATA_CHANGE");
                }
//                userIds.add(Long.valueOf(businessAddDTO.getCollaborator()));


            }

            return Result.result(businessEntity.getId());
        }
        return Result.error("操作失败！");
    }

    @Override
    public Result<IPage<BusinessListVO>> selectListVO(BusinessSearchDTO businessSearchDTO) {
        String jsonKey = JSON.toJSONString(businessSearchDTO.getScopeMenuId()+"_"+LoginUserUtil.getCurrentUserId());
        log.error("jsonKey = "+jsonKey);
        String preNexKey = MD5Util.MD5Encode(jsonKey,"UTF-8");
        LoginUser loginUser = LoginUserUtil.getLoginUser();

        IPage<BusinessListVO> pageVO = new Page<>(businessSearchDTO.getPageIndex(), businessSearchDTO.getPageSize());
        IPage<BusinessEntity> page = new Page<>(businessSearchDTO.getPageIndex(), businessSearchDTO.getPageSize());
        LambdaQueryWrapper<BusinessEntity> wrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotBlank(businessSearchDTO.getCustomerName()) || StrUtil.isNotBlank(businessSearchDTO.getCountry())) {
            LambdaQueryWrapper<CustomerEntity> customerEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customerEntityLambdaQueryWrapper.eq(CustomerEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            if (StrUtil.isNotBlank(businessSearchDTO.getCustomerName())) {
                customerEntityLambdaQueryWrapper.and(w -> w.like(CustomerEntity::getCustomerName, businessSearchDTO.getCustomerName()));
            }
            customerEntityLambdaQueryWrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getCountry()), CustomerEntity::getCountry, businessSearchDTO.getCountry());
            List<CustomerEntity> customerEntityList = customerService.list(customerEntityLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(customerEntityList)){
                List<Long> customerIds = customerEntityList.stream().map(CustomerEntity::getId).collect(Collectors.toList());
                wrapper.in(BusinessEntity::getCustomerId,customerIds);
                wrapper.and(w ->w.like(BusinessEntity::getTitle, businessSearchDTO.getCustomerName()).or().like(BusinessEntity::getDataCode, businessSearchDTO.getCustomerName()).or().in(BusinessEntity::getCustomerId,customerIds));

            }else {
                wrapper.and(w ->w.like(BusinessEntity::getTitle, businessSearchDTO.getCustomerName()).or().like(BusinessEntity::getDataCode, businessSearchDTO.getCustomerName()));

//                return Result.result(pageVO);
            }
        }
        if (!CollectionUtils.isEmpty(businessSearchDTO.getDeptIds())){
            //查询部门的全部用户
            Set<Long> userIdSet = userService.getUserIdsByDeptIds(businessSearchDTO.getDeptIds());
            if (CollectionUtils.isEmpty(userIdSet)){
                return Result.result(pageVO);
            }
            wrapper.in(BusinessEntity::getOwnerBy,userIdSet);
        }

        wrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(businessSearchDTO.getBlurry())) {
            wrapper.and(w ->w.like(BusinessEntity::getTitle, businessSearchDTO.getBlurry()).or().like(BusinessEntity::getDataCode, businessSearchDTO.getBlurry()));
        }
//        if (StrUtil.isNotBlank(businessSearchDTO.getCustomerName())) {
//            wrapper.and(w ->w.like(BusinessEntity::getTitle, businessSearchDTO.getCustomerName()).or().like(BusinessEntity::getDataCode, businessSearchDTO.getCustomerName()));
//        }
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getStage()),BusinessEntity::getStage, businessSearchDTO.getStage());
        wrapper.like(!ObjectUtils.isEmpty(businessSearchDTO.getTitle()),BusinessEntity::getTitle, businessSearchDTO.getTitle());
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getCustomerId()),BusinessEntity::getCustomerId, businessSearchDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getLiaisonId()),BusinessEntity::getCustomerId, businessSearchDTO.getLiaisonId());
        wrapper.in(!CollectionUtils.isEmpty(businessSearchDTO.getOwnerByIds()),BusinessEntity::getOwnerBy, businessSearchDTO.getOwnerByIds());

        //是否有已成交订单(1有，2没有)
        if (!ObjectUtils.isEmpty(businessSearchDTO.getHasOrderForm()) && !ObjectUtils.isEmpty(businessSearchDTO.getCustomerId())){
            LambdaQueryWrapper<OrderFormEntity> orderFormEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderFormEntityLambdaQueryWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            orderFormEntityLambdaQueryWrapper.eq(OrderFormEntity::getCustomerId, businessSearchDTO.getCustomerId());
            List<OrderFormEntity> orderFormEntityList = orderFormService.list(orderFormEntityLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(orderFormEntityList)){
                List<Long> businessIdList = orderFormEntityList.stream().filter(o -> !ObjectUtils.isEmpty(o.getBusinessId())).map(OrderFormEntity::getBusinessId).collect(Collectors.toList());
                if (businessSearchDTO.getHasOrderForm()==1){
                    if (!ObjectUtils.isEmpty(businessSearchDTO.getId())) {
                        businessIdList.add(businessSearchDTO.getId());
                    }
                    wrapper.in(BusinessEntity::getId, businessIdList);
                }else if (businessSearchDTO.getHasOrderForm()==2){
                    if (!ObjectUtils.isEmpty(businessSearchDTO.getId())){
                        businessIdList = businessIdList.stream().filter(o -> !o.equals(businessSearchDTO.getId())).collect(Collectors.toList());
                    }
                    if(!CollectionUtils.isEmpty(businessIdList)) {
                        wrapper.notIn(BusinessEntity::getId, businessIdList);
                    }
                }
            }

        }
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getOwnerBy()),BusinessEntity::getOwnerBy, businessSearchDTO.getOwnerBy());
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getSourcesOfBusinessDictValue()),BusinessEntity::getSourcesOfBusinessDictValue, businessSearchDTO.getSourcesOfBusinessDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getSalesPhaseDictValue()),BusinessEntity::getSalesPhaseDictValue, businessSearchDTO.getSalesPhaseDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getTransactionProbabilityDictValue()),BusinessEntity::getTransactionProbabilityDictValue, businessSearchDTO.getTransactionProbabilityDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getBusinessTypeDictValue()),BusinessEntity::getBusinessTypeDictValue, businessSearchDTO.getBusinessTypeDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getExpectedSigningDate()),BusinessEntity::getExpectedSigningDate, businessSearchDTO.getExpectedSigningDate());
        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getHasLoss()),BusinessEntity::getHasLoss, businessSearchDTO.getHasLoss());
//        wrapper.eq(!ObjectUtils.isEmpty(businessSearchDTO.getStage()),BusinessEntity::getStage, businessSearchDTO.getStage());
        if (Objects.nonNull(businessSearchDTO.getResourceTypeId()) && StrUtil.isNotBlank(businessSearchDTO.getResourceType())) {
            if (ResourceTypeEnum.LIAISON.code.equals(businessSearchDTO.getResourceType())) {
                wrapper.eq(BusinessEntity::getLiaisonId, businessSearchDTO.getResourceTypeId());
            }
            if (ResourceTypeEnum.CLUS.code.equals(businessSearchDTO.getResourceType())) {
                wrapper.eq(BusinessEntity::getCustomerId, businessSearchDTO.getResourceTypeId());
            }
            if (ResourceTypeEnum.CUSTOMER.code.equals(businessSearchDTO.getResourceType())) {
                wrapper.eq(BusinessEntity::getCustomerId, businessSearchDTO.getResourceTypeId());
            }
        }
        wrapper.ne(businessSearchDTO.getIsNeedNotDeal(), BusinessEntity::getStage, 4);
        if (Objects.nonNull(businessSearchDTO.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(businessSearchDTO.getQueryRangeType(),LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                wrapper.apply(queryRangeSql);
            }else if(QueryRangeTypeEnum.QUERY_MY_COOPERA_SQL.getCode().equals(businessSearchDTO.getQueryRangeType())){
                //我协作的
                wrapper.apply("FIND_IN_SET("+loginUser.getId()+", collaborator) ");
            }else if(QueryRangeTypeEnum.QUERY_MY_DEAL_SQL.getCode().equals(businessSearchDTO.getQueryRangeType())){
                //我成交的
                wrapper.eq(BusinessEntity::getStage,4);
                wrapper.eq(BusinessEntity::getOwnerBy,loginUser.getId());
            }
        }
        //权限范围内能看到的所有数据
        StringBuilder mergeSql = new StringBuilder();
//        if(QueryRangeTypeEnum.ALL_USER_SQL.getCode().equals(businessSearchDTO.getQueryRangeType())
//                || Integer.valueOf(1).equals(businessSearchDTO.getCommonScope())){
            String v1 = "owner_by = "+loginUser.getId();
            mergeSql.append(v1);
            String v2 = "FIND_IN_SET("+loginUser.getId()+", collaborator)";
            mergeSql.append(" or ");
            mergeSql.append(v2);

            List<Long> customerIds = customerService.getCustomerIdList(loginUser.getId());
            String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            if (!StrUtil.isBlank(customerIdString)){
                String v3 = " or customer_id in ( "+customerIdString +")";
                mergeSql.append(v3);
            }



            page = pageWithScope(page, wrapper,businessSearchDTO,mergeSql.toString());

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

        if (CollectionUtils.isEmpty(page.getRecords())){
            return Result.result(pageVO);
        }
//        List<CustomerListVO> customerListVO = new ArrayList<>();
        //复制list给VO类
        pageVO = SysBaseField.page(page, BusinessListVO.class);
        Set<Long> customerIdList = page.getRecords().stream().filter(e->e.getCustomerId()!=null).map(BusinessEntity::getCustomerId).collect(Collectors.toSet());
        Map<Long, CustomerEntity>  customerMap = customerService.getCustomerMap(customerIdList);
        List<Long> businessIdList = page.getRecords().stream().map(BusinessEntity::getId).collect(Collectors.toList());
        Map<Long, CustomerFollowUpLastVO> followUpLastVOMap = customerFollowUpService.getBussFollowUpLastVOMap(businessIdList,ResourceTypeEnum.BUSINESS.code);

        List<Long> quotationIdList = page.getRecords().stream().filter(e->e.getQuotationId()!=null).map(BusinessEntity::getQuotationId).collect(Collectors.toList());
        Map<Long, QuotationEntity> quotationMap = quotationService.getQuotationMap(quotationIdList);


        for (BusinessListVO businessListVO : pageVO.getRecords()){
            if (!ObjectUtils.isEmpty(customerMap.get(businessListVO.getCustomerId()))){
                businessListVO.setCustomerName(customerMap.get(businessListVO.getCustomerId()).getCustomerName());
            }
            if (Objects.nonNull(quotationMap) && !ObjectUtils.isEmpty(quotationMap.get(businessListVO.getQuotationId()))){
                businessListVO.setOfferAmount(quotationMap.get(businessListVO.getQuotationId()).getTotalOrderAmt());
            }
            //补充最后跟进时间及未跟进时长
            CustomerFollowUpLastVO customerFollowUpLastVO = followUpLastVOMap.get(businessListVO.getId());
            if (!ObjectUtils.isEmpty(customerFollowUpLastVO)){
                businessListVO.setLastFollowUpTime(customerFollowUpLastVO.getFollowUpTime());
                businessListVO.setNotFollowedDays(customerFollowUpLastVO.getNotFollowUpDate());
            }
        }

        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());
        return Result.result(pageVO);
    }

    @Override
    public IPage<?> selectSimpleListVO(CustomerSearchSearchDTO customerSearchSearchDTO) {
        LoginUser loginUser = customerSearchSearchDTO.getLoginUser();

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


        wrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(customerSearchSearchDTO.getBlurry())) {
//            wrapper.and(w ->w.like(BusinessEntity::getTitle, customerSearchSearchDTO.getBlurry()).or().like(BusinessEntity::getDataCode, customerSearchSearchDTO.getBlurry()));
              wrapper.like(BusinessEntity::getTitle, 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(BusinessEntity::getCustomerId,customerIds);
            }else {
                return pageVO;
            }
        }

        //是否有已成交订单(1有，2没有)
        //权限范围内能看到的所有数据
        StringBuilder mergeSql = new StringBuilder();
//        if(QueryRangeTypeEnum.ALL_USER_SQL.getCode().equals(businessSearchDTO.getQueryRangeType())
//                || Integer.valueOf(1).equals(businessSearchDTO.getCommonScope())){
        String v1 = "owner_by = "+loginUser.getId();
        mergeSql.append(v1);
        String v2 = "FIND_IN_SET("+loginUser.getId()+", collaborator)";
        mergeSql.append(" or ");
        mergeSql.append(v2);

//        List<Long> customerIds = customerService.getCustomerIdList(loginUser.getId());
//        String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        if (!StrUtil.isBlank(customerSearchSearchDTO.getCustomerIdString())){
            String v3 = " or customer_id in ( "+customerSearchSearchDTO.getCustomerIdString() +")";
            mergeSql.append(v3);
        }



        page = pageWithScope(page, wrapper,customerSearchSearchDTO,mergeSql.toString());

        if (CollectionUtils.isEmpty(page.getRecords())){
            return pageVO;
        }
//        List<CustomerListVO> customerListVO = new ArrayList<>();
        //复制list给VO类
        pageVO = SysBaseField.page(page, BusinessListVO.class);
//        Set<Long> customerIdList = page.getRecords().stream().filter(e->e.getCustomerId()!=null).map(BusinessEntity::getCustomerId).collect(Collectors.toSet());
//        Map<Long, CustomerEntity>  customerMap = customerService.getCustomerMap(customerIdList);
//        List<Long> businessIdList = page.getRecords().stream().map(BusinessEntity::getId).collect(Collectors.toList());
//
//        List<Long> quotationIdList = page.getRecords().stream().filter(e->e.getQuotationId()!=null).map(BusinessEntity::getQuotationId).collect(Collectors.toList());
//        Map<Long, QuotationEntity> quotationMap = quotationService.getQuotationMap(quotationIdList);
//
//
//        for (BusinessListVO businessListVO : pageVO.getRecords()){
//            if (!ObjectUtils.isEmpty(customerMap.get(businessListVO.getCustomerId()))){
//                businessListVO.setCustomerName(customerMap.get(businessListVO.getCustomerId()).getCustomerName());
//            }
//            if (Objects.nonNull(quotationMap) && !ObjectUtils.isEmpty(quotationMap.get(businessListVO.getQuotationId()))){
//                businessListVO.setOfferAmount(quotationMap.get(businessListVO.getQuotationId()).getTotalOrderAmt());
//            }
//        }

        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());
        return pageVO;
    }


    @Override
    public BusinessDetailVO getBusinessVOById(Long id) {
        BusinessEntity businessEntity = getById(id);
        if (!ObjectUtils.isEmpty(businessEntity)){
            BusinessDetailVO businessDetailVO = new BusinessDetailVO();
            BeanUtils.copyProperties(businessEntity, businessDetailVO);
            //添加客户名称
            businessDetailVO.setCustomerName(customerService.getById(businessEntity.getCustomerId()).getCustomerName());
            businessDetailVO.dictFiled();
            SysBaseField.orgFileds(businessDetailVO);

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

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

            return businessDetailVO;
        }
        return null;
    }

    @Override
    public BusinessAllDetailVO getBusinessAllVOById(Long id) {
        BusinessEntity businessEntity = getById(id);
        if (!ObjectUtils.isEmpty(businessEntity)){
            BusinessAllDetailVO businessAllDetailVO = new BusinessAllDetailVO();
            BeanUtils.copyProperties(businessEntity, businessAllDetailVO);
            //添加客户名称
            if (!ObjectUtils.isEmpty(businessEntity.getCustomerId())){
                CustomerEntity customerEntity = customerService.getById(businessEntity.getCustomerId());
                if (!ObjectUtils.isEmpty(customerEntity)){
                    businessAllDetailVO.setCustomerName(customerEntity.getCustomerName());
                }
            }
            //添加订单名称
            LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<OrderFormEntity>();
            orderFormWrapper.eq(OrderFormEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            orderFormWrapper.eq(OrderFormEntity::getBusinessId, id);
            orderFormWrapper.last("limit 1");
            OrderFormEntity orderFormEntity = orderFormService.getOne(orderFormWrapper);
            if (!ObjectUtils.isEmpty(orderFormEntity)){
                businessAllDetailVO.setOrderFormTitle(orderFormEntity.getTitle());
                businessAllDetailVO.setOrderFormId(orderFormEntity.getId());
            }
            businessAllDetailVO.setCurrency(businessEntity.getCurrency());
            businessAllDetailVO.setExchangeRate(businessEntity.getExchangeRate());
            businessAllDetailVO.setInitialSalesAmount(businessEntity.getInitialSalesAmount());

            //添加主要联系人姓名
            if (!ObjectUtils.isEmpty(businessEntity.getLiaisonId())){
                LiaisonEntity liaisonEntity = liaisonService.getById(businessEntity.getLiaisonId());
                if (!ObjectUtils.isEmpty(liaisonEntity)){
                    businessAllDetailVO.setLiaisonName(liaisonEntity.getName());
                }
            }
            //添加协作人员姓名
            if (!ObjectUtils.isEmpty(businessEntity.getCollaborator())){
                List<Long> collaboratorList = Arrays.stream(businessEntity.getCollaborator().split(",")).map(Long::valueOf).collect(Collectors.toList());
                List<UserEntity> userEntityList = userService.listByIds(collaboratorList);
                if (!CollectionUtils.isEmpty(userEntityList)){
                    businessAllDetailVO.setCollaboratorName(userEntityList.stream().map(UserEntity::getRealName).collect(Collectors.joining(",")));
                }
            }
            //添加所属成员部门信息
            if (!ObjectUtils.isEmpty(businessEntity.getOwnerBy())){
                businessAllDetailVO.setDeptName(userService.getUserInfoById(businessEntity.getOwnerBy()).getDeptName());
            }

            //添加最后跟进时间
            LocalDateTime lastFollowUpTime = customerFollowUpService.getLastFollowUpTime(businessEntity.getId(), ResourceTypeEnum.BUSINESS.code);
            businessAllDetailVO.setLastFollowUpTime(lastFollowUpTime);
            //添加下次跟进时间
            LocalDateTime nextFollowUpTime = taskService.getNextFollowUpTime(businessEntity.getId(), ResourceTypeEnum.BUSINESS.code);
            businessAllDetailVO.setNextFollowUpTime(nextFollowUpTime);

            businessAllDetailVO.dictFiled();
            SysBaseField.orgFileds(businessAllDetailVO);

            //添加下一个id
//            BusinessEntity next = getNextById(id, new LambdaQueryWrapper<BusinessEntity>().ge(BusinessEntity::getId, id).eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0).orderByAsc(BusinessEntity::getId).last("limit 10"));
//            if (!ObjectUtils.isEmpty(next)){
//                businessAllDetailVO.setNextId(next.getId());
//
//            }
//            //添加上一个id
//            BusinessEntity previous = getPreviousById(id, new LambdaQueryWrapper<BusinessEntity>().le(BusinessEntity::getId, id).eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0).orderByDesc(BusinessEntity::getId).last("limit 10"));
//            if (!ObjectUtils.isEmpty(previous)){
//                businessAllDetailVO.setPreviousId(previous.getId());
//            }
            //判断是否有已存在的订单
            LambdaQueryWrapper<OrderFormEntity> orderCountWrapper = new LambdaQueryWrapper<>();
            orderCountWrapper.eq(OrderFormEntity::getBusinessId,businessAllDetailVO.getId());
            orderCountWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            if (orderFormService.count(orderCountWrapper)>0){
                businessAllDetailVO.setHasOrderForm(true);
            }
            return businessAllDetailVO;
        }
        return null;
    }

    @Override
    public Map<Long, BusinessEntity> getBusinessMap(List<Long> businessIdList) {
        if (!CollectionUtils.isEmpty(businessIdList)){
            LambdaQueryWrapper<BusinessEntity> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.in(BusinessEntity::getId, businessIdList);
            List<BusinessEntity> businessEntityList = list(wrapper);
            if (!CollectionUtils.isEmpty(businessEntityList)){
                return businessEntityList.stream().collect(
                        Collectors.toMap(BusinessEntity::getId, BusinessEntity -> BusinessEntity));
                    }
                }
        return null;
    }

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

    @Override
    public Result<?> changeStage(BusinessChangeStageDTO businessChangeStage) {
        if (!ObjectUtils.isEmpty(businessChangeStage)){
            BusinessEntity businessEntity = new BusinessEntity();
            BeanUtils.copyProperties(businessChangeStage, businessEntity);
            businessEntity.setStage(businessChangeStage.getStage());
            //如果阶段改为成交商机，写入签单日期
            if (businessChangeStage.getStage().equals("4")){
                businessEntity.setSigningDate(new Date());
            }
            if (updateById(businessEntity)){

                assembleService.sendBusinessEventMessages(businessEntity.getId(),"DATA_CHANGE");
                return Result.ok();
            }
        }
        return Result.error("操作失败！");
    }

    @Override
    public Result<?> businessLoss(BusinessLossDTO businessLossDTO) {
        if (ObjectUtils.isEmpty(businessLossDTO)){
            return Result.error("参数异常！");

        }
        BusinessEntity businessOld = getById(businessLossDTO.getId());
        if (businessOld.getHasLoss().equals(0)){
            businessLossDTO.setHasLoss(1);
        }else {
            businessLossDTO.setHasLoss(0);
        }
        BusinessEntity businessEntity = new BusinessEntity();
        BeanUtils.copyProperties(businessLossDTO, businessEntity);
        if (updateById(businessEntity)){
            return Result.ok();
        }
        return Result.error("操作失败！");
    }

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


}
