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.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.CustomerCollaboratorDTO;
import com.storlead.sales.pojo.dto.customer.CustomerSearchSearchDTO;
import com.storlead.sales.pojo.dto.customer.OrderFormAddDTO;
import com.storlead.sales.pojo.dto.customer.OrderFormSearchDTO;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.vo.customer.CustomerListVO;
import com.storlead.sales.pojo.vo.customer.LiaisonListVO;
import com.storlead.sales.pojo.vo.customer.OrderFormDetailVO;
import com.storlead.sales.pojo.vo.customer.OrderFormListVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.pojo.entity.sku.QuotationEntity;
import com.storlead.sales.pojo.entity.systemrule.CurrencySettingsEntity;
import com.storlead.sales.mapper.customer.OrderFormMapper;
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.systemrule.CurrencySettingsService;
import com.storlead.sales.service.task.TaskService;
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 io.swagger.annotations.ApiModelProperty;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.apache.commons.lang.StringUtils;
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.time.LocalDate;
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 OrderFormServiceImpl extends MyBaseServiceImpl<OrderFormMapper, OrderFormEntity> implements OrderFormService {

    @Resource
    private CustomerService customerService;
    @Resource
    private BusinessService businessService;
    @Resource
    private IUserService userService;
    @Resource
    private SysResourceService sysResourceService;
    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Resource
    private TaskService taskService;
    @Resource
    private QuotationService quotationService;
    @Resource
    private MessageAssembleService assembleService;
    @Resource
    private CurrencySettingsService currencySettingsService;
    @Resource
    private IDepartService departService;
    @Resource
    private WorkDynamicsService  workDynamicsService;
    @Resource
    private RedisService redisService;
    @Override
    public Result<?> addOrderForm(OrderFormAddDTO orderFormAddDTO) {
        if (ObjectUtils.isEmpty(orderFormAddDTO)){
            return Result.error("参数错误");
        }
        if (!ObjectUtils.isEmpty(orderFormAddDTO.getBusinessId())){
            //验证商机是否已转订单
            LambdaQueryWrapper<OrderFormEntity> orderCountWrapper = new LambdaQueryWrapper<>();
            orderCountWrapper.eq(OrderFormEntity::getBusinessId,orderFormAddDTO.getBusinessId());
            orderCountWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            if (count(orderCountWrapper)>0){
                return Result.error("商机已转订单，无法再次转订单");
            }
        }
        if (!ObjectUtils.isEmpty(orderFormAddDTO.getQuotationAddDTO())){
            orderFormAddDTO.getQuotationAddDTO().setCustomerId(orderFormAddDTO.getCustomerId());
            if (!ObjectUtils.isEmpty(orderFormAddDTO.getQuotationAddDTO().getId())){
                Result queryResult = quotationService.editQuotation(orderFormAddDTO.getQuotationAddDTO());
                if (!queryResult.isSuccess()){
                    return queryResult;
                }
            }else {
//                orderFormAddDTO.getQuotationAddDTO().setOrderFormId(orderFormAddDTO.getId());
                Result queryResult = quotationService.addQuotation(orderFormAddDTO.getQuotationAddDTO());
                if (!queryResult.isSuccess()){
                    return queryResult;
                }

            }
            orderFormAddDTO.setQuotationId(orderFormAddDTO.getQuotationAddDTO().getId());
            orderFormAddDTO.setTotalOrderAmt(orderFormAddDTO.getQuotationAddDTO().getTotalOrderAmt());
        }



        OrderFormEntity orderFormEntity = new OrderFormEntity();
        BeanUtils.copyProperties(orderFormAddDTO,orderFormEntity);
        if (ObjectUtils.isEmpty(orderFormAddDTO.getId())){
            orderFormEntity.setDataCode(CodeGenerate.generate10Code(CodeGenerateInterface.ORDER_FORM_CODE));
        }

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

        boolean success = saveOrUpdate(orderFormEntity);
        if (!success) {
            return Result.error("操作失败");
        }
//            orderFormAddDTO.setId(orderFormEntity.getId());
            //添加附件
        if (!CollectionUtils.isEmpty(orderFormAddDTO.getResourceIdList())){
            sysResourceService.updateResourceById(orderFormEntity.getCustomerId(),ResourceTypeEnum.ORDER_FORM.code,orderFormEntity.getId(),orderFormAddDTO.getResourceIdList());
        }
        //关联任务
        if (!ObjectUtils.isEmpty(orderFormAddDTO.getTask())){
            orderFormAddDTO.getTask().setResourceType(ResourceTypeEnum.ORDER_FORM.code);
            orderFormAddDTO.getTask().setResourceTypeId(orderFormEntity.getId());
            taskService.addTask(orderFormAddDTO.getTask().setCustomerId(orderFormEntity.getCustomerId()));
        }
        //修改客户成交状态
        if (!ObjectUtils.isEmpty(orderFormAddDTO.getCustomerId())){
            CustomerEntity customer = new CustomerEntity();
            customer.setId(orderFormAddDTO.getCustomerId());
            customer.setHasOrderForm(1);
            customerService.updateById(customer);
            customer = customerService.getById(orderFormAddDTO.getCustomerId());

            //添加订单工作动态
            WorkDynamicsEntity workDynamicsBusiness = new WorkDynamicsEntity();
            workDynamicsBusiness.setCustomerId(orderFormEntity.getCustomerId());
            workDynamicsBusiness.setOperationType(1);
            workDynamicsBusiness.setResourceType(ResourceTypeEnum.ORDER_FORM.code);
            workDynamicsBusiness.setResourceTypeId(orderFormEntity.getId());
            workDynamicsBusiness.setTitle("成交订单："+ HtmlUtils.clearContent(orderFormEntity.getDataCode())
                    +"<br/>成交金额：￥"+HtmlUtils.clearContent(orderFormEntity.getTotalOrderAmt().toString())
                    +"<br/>客户名称："+HtmlUtils.clearContent(customer.getCustomerName()));
            workDynamicsBusiness.setOwnerBy(ownerBy);

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

                workDynamicsBusiness.setContent(workContentLiaison);
            }catch (Exception e){
                return Result.error("订单工作动态写入异常");
            }
            workDynamicsService.save(workDynamicsBusiness);
        }
        //关联报价
        if (!ObjectUtils.isEmpty(orderFormEntity.getQuotationId())){
            QuotationEntity quotationEntity = new QuotationEntity();
            quotationEntity.setId(orderFormEntity.getQuotationId());
            quotationEntity.setOrderFormId(orderFormEntity.getId());
            //关联商机
            if (!ObjectUtils.isEmpty(orderFormEntity.getBusinessId())){
                quotationEntity.setBusinessId(orderFormEntity.getBusinessId());
                //修改商机阶段为成交商机
                BusinessEntity business = new BusinessEntity();
                business.setId(orderFormEntity.getBusinessId());
                business.setQuotationId(orderFormEntity.getQuotationId());
                business.setStage("4");
                //如果阶段改为成交商机，写入签单日期
                business.setSigningDate(orderFormEntity.getSigningDate());
                businessService.updateById(business);
            }
            quotationService.updateById(quotationEntity);
        }



        //发送消息
        if (!ObjectUtils.isEmpty(orderFormAddDTO.getRemindUserIds())){
            Set<Long> toUserIds = Arrays.stream(orderFormAddDTO.getRemindUserIds().split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toSet());
            assembleService.sendOrderEventMessages(orderFormEntity.getId(),"ADD_ORDER",toUserIds);
        }else if (!ObjectUtils.isEmpty(orderFormAddDTO.getBusinessId())){
            assembleService.sendBusinessEventMessages(orderFormEntity.getBusinessId(),"CONVERT_TO_ORDER");
        }else {
            assembleService.sendOrderParentEventMessages(orderFormEntity.getId(),"ADD_ORDER");
        }

        return Result.result(orderFormEntity.getId());
    }

    @Override
    public Result<?> editOrderForm(OrderFormAddDTO orderFormAddDTO) {
        if (ObjectUtils.isEmpty(orderFormAddDTO)){
            return Result.error("参数错误");
        }
        OrderFormEntity orderFormOld = getById(orderFormAddDTO.getId());
        if (!ObjectUtils.isEmpty(orderFormAddDTO.getBusinessId())){
            //验证商机是否已转订单
            LambdaQueryWrapper<OrderFormEntity> orderCountWrapper = new LambdaQueryWrapper<>();
            orderCountWrapper.eq(OrderFormEntity::getBusinessId,orderFormAddDTO.getBusinessId());
            orderCountWrapper.ne(OrderFormEntity::getId,orderFormAddDTO.getId());
            orderCountWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            if (count(orderCountWrapper)>0){
                return Result.error("该商机已关联订单！");
            }
        }

        if (!ObjectUtils.isEmpty(orderFormAddDTO.getQuotationAddDTO())){
            orderFormAddDTO.getQuotationAddDTO().setCustomerId(orderFormAddDTO.getCustomerId());
            if (!ObjectUtils.isEmpty(orderFormAddDTO.getQuotationAddDTO().getId())){
                Result queryResult = quotationService.editQuotation(orderFormAddDTO.getQuotationAddDTO());
                if (!queryResult.isSuccess()){
                    return queryResult;
                }
            }else {
//                orderFormAddDTO.getQuotationAddDTO().setOrderFormId(orderFormAddDTO.getId());
                Result queryResult = quotationService.addQuotation(orderFormAddDTO.getQuotationAddDTO());
                if (!queryResult.isSuccess()){
                    return queryResult;
                }

            }
            orderFormAddDTO.setQuotationId(orderFormAddDTO.getQuotationAddDTO().getId());
            orderFormAddDTO.setTotalOrderAmt(orderFormAddDTO.getQuotationAddDTO().getTotalOrderAmt());
        }
        OrderFormEntity orderFormEntity = new OrderFormEntity();
        BeanUtils.copyProperties(orderFormAddDTO,orderFormEntity);
        boolean success = updateById(orderFormEntity);
        if (!success) {
            return Result.error("操作失败");
        }
        if (ObjectUtils.isEmpty(orderFormAddDTO.getBusinessId())){

            if (!ObjectUtils.isEmpty(orderFormOld.getBusinessId())) {
                LambdaUpdateWrapper<OrderFormEntity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(OrderFormEntity::getId, orderFormEntity.getId());
                updateWrapper.set(OrderFormEntity::getBusinessId, null);
                update(updateWrapper);

                LambdaUpdateWrapper<BusinessEntity> businessUpdateWrapper = new LambdaUpdateWrapper<>();
                businessUpdateWrapper.eq(BusinessEntity::getId, orderFormOld.getBusinessId());
                businessUpdateWrapper.set(BusinessEntity::getStage, "3");
                businessUpdateWrapper.set(BusinessEntity::getSigningDate, null);

                businessService.update(businessUpdateWrapper);
            }
        }else if (!ObjectUtils.isEmpty(orderFormOld.getBusinessId()) && !orderFormOld.getBusinessId().equals(orderFormAddDTO.getBusinessId())){
            LambdaUpdateWrapper<BusinessEntity> businessUpdateWrapper = new LambdaUpdateWrapper<>();
            businessUpdateWrapper.eq(BusinessEntity::getId, orderFormOld.getBusinessId());
            businessUpdateWrapper.set(BusinessEntity::getStage, "3");
            businessUpdateWrapper.set(BusinessEntity::getSigningDate, null);
            businessService.update(businessUpdateWrapper);
        }

//            orderFormAddDTO.setId(orderFormEntity.getId());
            //添加附件
//        if (!CollectionUtils.isEmpty(orderFormAddDTO.getResourceIdList())){
        sysResourceService.updateResourceById(orderFormEntity.getCustomerId(),ResourceTypeEnum.ORDER_FORM.code,orderFormEntity.getId(),orderFormAddDTO.getResourceIdList());
//        }
        //关联任务
        if (!ObjectUtils.isEmpty(orderFormAddDTO.getTask())){
            orderFormAddDTO.getTask().setResourceType(ResourceTypeEnum.ORDER_FORM.code);
            orderFormAddDTO.getTask().setResourceTypeId(orderFormEntity.getId());
            taskService.addTask(orderFormAddDTO.getTask().setCustomerId(orderFormEntity.getCustomerId()));
        }
        //修改客户成交状态
        if (!ObjectUtils.isEmpty(orderFormAddDTO.getCustomerId())){
            CustomerEntity customer = new CustomerEntity();
            customer.setId(orderFormAddDTO.getCustomerId());
            customer.setHasOrderForm(1);
            customerService.updateById(customer);
        }
        //关联报价
        if (!ObjectUtils.isEmpty(orderFormEntity.getQuotationId())){
            QuotationEntity quotationEntity = new QuotationEntity();
            quotationEntity.setId(orderFormEntity.getQuotationId());
            quotationEntity.setOrderFormId(orderFormEntity.getId());
            //关联商机
            if (!ObjectUtils.isEmpty(orderFormEntity.getBusinessId())){
                quotationEntity.setBusinessId(orderFormEntity.getBusinessId());
                //修改商机阶段为成交商机
                BusinessEntity business = new BusinessEntity();
                business.setId(orderFormEntity.getBusinessId());
                business.setQuotationId(orderFormEntity.getQuotationId());
                business.setStage("4");
                //如果阶段改为成交商机，写入签单日期
                business.setSigningDate(orderFormEntity.getSigningDate());
                businessService.updateById(business);
            }
            quotationService.updateById(quotationEntity);
            if (!orderFormOld.getQuotationId().equals(orderFormAddDTO.getQuotationId())){
                //删除原有报价单
                QuotationEntity quotationOld = new QuotationEntity();
                quotationOld.setId(orderFormOld.getQuotationId());
                quotationOld.setOrderFormId(0L);
//                quotationOld.setIsDelete(CommonConstant.DEL_FLAG_1);
                quotationService.updateById(quotationOld);
            }
        }
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        if (!orderFormOld.getId().equals(loginUser.getId())){
            //发送消息
            assembleService.sendOrderEventMessages(orderFormEntity.getId(),"DATA_CHANGE");
        }
        return Result.result(orderFormEntity.getId());
    }

    @Override
    public Result<IPage<OrderFormListVO>> selectListVO(OrderFormSearchDTO orderFormSearchDTO) {
        String jsonKey = JSON.toJSONString(orderFormSearchDTO.getScopeMenuId()+"_"+LoginUserUtil.getCurrentUserId());
        log.error("jsonKey = "+jsonKey);
        String preNexKey = MD5Util.MD5Encode(jsonKey,"UTF-8");
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        IPage<OrderFormListVO> pageVO = new Page<>(orderFormSearchDTO.getPageIndex(),orderFormSearchDTO.getPageSize());
        IPage<OrderFormEntity> page = new Page<>(orderFormSearchDTO.getPageIndex(),orderFormSearchDTO.getPageSize());
        LambdaQueryWrapper<OrderFormEntity> wrapper = new LambdaQueryWrapper<>();

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

        wrapper.eq(OrderFormEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(orderFormSearchDTO.getBlurry())) {
            wrapper.and(w ->w.like(OrderFormEntity::getTitle,orderFormSearchDTO.getBlurry()).or().like(OrderFormEntity::getDataCode,orderFormSearchDTO.getBlurry()));
        }
        wrapper.eq(!ObjectUtils.isEmpty(orderFormSearchDTO.getCustomerId()),OrderFormEntity::getCustomerId,orderFormSearchDTO.getCustomerId());
        wrapper.like(!ObjectUtils.isEmpty(orderFormSearchDTO.getTitle()),OrderFormEntity::getTitle,orderFormSearchDTO.getTitle());
        wrapper.eq(!ObjectUtils.isEmpty(orderFormSearchDTO.getOwnerBy()),OrderFormEntity::getOwnerBy,orderFormSearchDTO.getOwnerBy());
        wrapper.eq(!ObjectUtils.isEmpty(orderFormSearchDTO.getBusinessId()),OrderFormEntity::getBusinessId,orderFormSearchDTO.getBusinessId());
        wrapper.eq(!ObjectUtils.isEmpty(orderFormSearchDTO.getOrderTypeDictValue()),OrderFormEntity::getOrderTypeDictValue,orderFormSearchDTO.getOrderTypeDictValue());
        wrapper.eq(!ObjectUtils.isEmpty(orderFormSearchDTO.getSigningDate()),OrderFormEntity::getSigningDate,orderFormSearchDTO.getSigningDate());
        wrapper.in(!CollectionUtils.isEmpty(orderFormSearchDTO.getOwnerByIds()),OrderFormEntity::getOwnerBy, orderFormSearchDTO.getOwnerByIds());
        if (Objects.nonNull(orderFormSearchDTO.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(orderFormSearchDTO.getQueryRangeType(), LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                wrapper.apply(queryRangeSql);
            }else if(QueryRangeTypeEnum.QUERY_MY_COOPERA_SQL.getCode().equals(orderFormSearchDTO.getQueryRangeType())){
                //我协作的
                wrapper.apply("FIND_IN_SET("+loginUser.getId()+", collaborator) ");
            }else if(QueryRangeTypeEnum.QUERY_SUBORDINATE_COOPERA_SQL.getCode().equals(orderFormSearchDTO.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)+",'"));
            }

        }
        //权限范围内能看到的所有数据
        StringBuilder mergeSql = new StringBuilder();
//        if(QueryRangeTypeEnum.ALL_USER_SQL.getCode().equals(orderFormSearchDTO.getQueryRangeType())
//                || Integer.valueOf(1).equals(orderFormSearchDTO.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> subUserIds = userService.getAllSubordinate(loginUser.getId());
            if (!CollectionUtils.isEmpty(subUserIds)){
                String v3 = "CONCAT(',',collaborator,',') REGEXP ',"+concatRegexp(subUserIds)+",'";
                mergeSql.append(" or ");
                mergeSql.append(v3);
            }

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

            String v5 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+loginUser.getId()+",managers))";
            mergeSql.append(" or ");
            mergeSql.append(v5);

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

//        if (QueryRangeTypeEnum.ALL_USER_SQL.getCode().equals(orderFormSearchDTO.getQueryRangeType())){
//            page = pageWithScope(page, wrapper);
//        }else {
//            page = page(page, wrapper);
//        }
        wrapper.select(OrderFormEntity::getId);
        int pageIndex1 = orderFormSearchDTO.getPageIndex() > 10 ? orderFormSearchDTO.getPageIndex() - 10 : 1;
        IPage<OrderFormEntity> pagePre1 = new Page<>(pageIndex1, orderFormSearchDTO.getPageSize() * 10);
        pagePre1 = pageWithScope(pagePre1, wrapper,orderFormSearchDTO,mergeSql.toString());
        if(!CollectionUtils.isEmpty(pagePre1.getRecords())) {
            List<Long> cIds = pagePre1.getRecords().stream().map(OrderFormEntity::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);
        }
        pageVO = SysBaseField.page(page, OrderFormListVO.class);
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        Set<Long> customerIdList = pageVO.getRecords().stream().filter(e->e.getCustomerId()!=null).map(OrderFormListVO::getCustomerId).collect(Collectors.toSet());
        Map<Long, CustomerEntity> customerMap = customerService.getCustomerMap(customerIdList);
        if (!CollectionUtils.isEmpty(customerMap)){
            for (OrderFormListVO orderFormListVO : pageVO.getRecords()){
                if (!ObjectUtils.isEmpty(customerMap.get(orderFormListVO.getCustomerId()))){
                    orderFormListVO.setCustomerName(customerMap.get(orderFormListVO.getCustomerId()).getCustomerName());
                }
            }
        }

        List<Long>  businessIdList = pageVO.getRecords().stream().filter(e->e.getBusinessId()!=null).map(OrderFormListVO::getBusinessId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(businessIdList)) {
            Map<Long, BusinessEntity> businessMap = businessService.getBusinessMap(businessIdList);
            if (!CollectionUtils.isEmpty(businessMap)){
                for (OrderFormListVO orderFormListVO : pageVO.getRecords()) {
                    if (!ObjectUtils.isEmpty(businessMap.get(orderFormListVO.getBusinessId()))) {
                        orderFormListVO.setBusinessName(businessMap.get(orderFormListVO.getBusinessId()).getTitle());
                    }
                }
            }

        }
        //返回币种名称
        Set<Long> currencyIdList = pageVO.getRecords().stream().filter(e->e.getCurrencyId()!=null).map(OrderFormListVO::getCurrencyId).collect(Collectors.toSet());
        Map<Long, CurrencySettingsEntity> currencyMap = currencySettingsService.getCurrencyMap(currencyIdList);
        if (!CollectionUtils.isEmpty(currencyMap)){
            for (OrderFormListVO orderFormListVO : pageVO.getRecords()) {
                if (!ObjectUtils.isEmpty(currencyMap.get(orderFormListVO.getCurrencyId()))){
                    orderFormListVO.setCurrencyName(currencyMap.get(orderFormListVO.getCurrencyId()).getChineseName());
                }
            }
        }
        //返回报价列表
        List<Long> quotationIdList = pageVO.getRecords().stream().filter(e->e.getQuotationId()!=null).map(OrderFormListVO::getQuotationId).collect(Collectors.toList());
        Map<Long, QuotationEntity> quotationEntityMap = quotationService.getQuotationMap(quotationIdList);
        if (!CollectionUtils.isEmpty(quotationEntityMap)){
            for (OrderFormListVO orderFormListVO : pageVO.getRecords()) {
                if (!ObjectUtils.isEmpty(quotationEntityMap.get(orderFormListVO.getQuotationId()))){
                    orderFormListVO.setQuotation(quotationEntityMap.get(orderFormListVO.getQuotationId()));
                }
            }
        }

        return Result.result(pageVO);
    }

    @Override
    public IPage<?> selectSimpleListVO(CustomerSearchSearchDTO customerSearchSearchDTO) {
        LoginUser loginUser = customerSearchSearchDTO.getLoginUser();
        IPage<OrderFormListVO> pageVO = new Page<>(customerSearchSearchDTO.getPageIndex(),customerSearchSearchDTO.getPageSize());
        IPage<OrderFormEntity> page = new Page<>(customerSearchSearchDTO.getPageIndex(),customerSearchSearchDTO.getPageSize());
        LambdaQueryWrapper<OrderFormEntity> wrapper = new LambdaQueryWrapper<>();


        wrapper.eq(OrderFormEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(customerSearchSearchDTO.getBlurry())) {
//            wrapper.and(w ->w.like(OrderFormEntity::getTitle,customerSearchSearchDTO.getBlurry()).or().like(OrderFormEntity::getDataCode,customerSearchSearchDTO.getBlurry()));
            wrapper.like(OrderFormEntity::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(OrderFormEntity::getCustomerId,customerIds);
            }else {
                return pageVO;
            }
        }
        //权限范围内能看到的所有数据
        StringBuilder mergeSql = new StringBuilder();
        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> subUserIds = userService.getAllSubordinate(loginUser.getId());
        if (!CollectionUtils.isEmpty(subUserIds)){
            String v3 = "CONCAT(',',collaborator,',') REGEXP ',"+concatRegexp(subUserIds)+",'";
            mergeSql.append(" or ");
            mergeSql.append(v3);
        }

        if (!StrUtil.isBlank(customerSearchSearchDTO.getCustomerIdString())){
            String v4= " or customer_id in ( "+customerSearchSearchDTO.getCustomerIdString() +")";
            mergeSql.append(v4);
        }

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

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

        if (CollectionUtils.isEmpty(page.getRecords())){
            return pageVO;
        }
        pageVO = SysBaseField.page(page, OrderFormListVO.class);
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        //添加报价详情
//        List<Long> quotationIdList = pageVO.getRecords().stream().filter(e->e.getQuotationId()!=null).map(OrderFormListVO::getQuotationId).collect(Collectors.toList());
//        Map<Long, QuotationEntity> quotationEntityMap = quotationService.getQuotationMap(quotationIdList);
//        if (!CollectionUtils.isEmpty(quotationEntityMap)){
//            for (OrderFormListVO orderFormListVO : pageVO.getRecords()) {
//                if (!ObjectUtils.isEmpty(quotationEntityMap.get(orderFormListVO.getQuotationId()))){
//                    orderFormListVO.setQuotation(quotationEntityMap.get(orderFormListVO.getQuotationId()));
//                }
//            }
//        }

        return pageVO;
    }


    @Override
    public OrderFormDetailVO getOrderFormVOById(Long id) {
        OrderFormEntity orderFormEntity = getById(id);
        if (ObjectUtils.isEmpty(orderFormEntity)){
            return null;
        }
        OrderFormDetailVO orderFormDetailVO = new OrderFormDetailVO();
        BeanUtils.copyProperties(orderFormEntity,orderFormDetailVO);
        SysBaseField.orgFileds(orderFormDetailVO);
        orderFormDetailVO.dictFiled();

        //添加客户名称
        if (!ObjectUtils.isEmpty(orderFormDetailVO.getCustomerId())){
            CustomerEntity customerEntity = customerService.getById(orderFormDetailVO.getCustomerId());
            if (!ObjectUtils.isEmpty(customerEntity)){
                orderFormDetailVO.setCustomerName(customerEntity.getCustomerName());
            }
        }
        //添加商机名称
        if (!ObjectUtils.isEmpty(orderFormDetailVO.getBusinessId())){
            BusinessEntity businessEntity = businessService.getById(orderFormDetailVO.getBusinessId());
            if (!ObjectUtils.isEmpty(businessEntity)){
                orderFormDetailVO.setBusinessName(businessEntity.getTitle());
            }
        }

        //返回币种
        CurrencySettingsEntity currencySettings = currencySettingsService.getById(orderFormDetailVO.getCurrencyId());
        if (!ObjectUtils.isEmpty(currencySettings)){
            orderFormDetailVO.setCurrencyName(currencySettings.getChineseName());
        }

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

        //添加所属成员部门信息
        if (!ObjectUtils.isEmpty(orderFormDetailVO.getOwnerBy())){
            orderFormDetailVO.setDeptName(userService.getUserInfoById(orderFormDetailVO.getOwnerBy()).getDeptName());
        }

        if (Objects.nonNull(orderFormDetailVO.getFormerOwnerBy())) {
            UserEntity fuser = userService.getById(orderFormDetailVO.getFormerOwnerBy());
            if (Objects.nonNull(fuser)) {
                DeptEntity fDept = departService.getById(fuser.getDeptId());
                if (Objects.nonNull(fDept)) {
                    orderFormDetailVO.setFormerDeptName(fDept.getName());
                }
            }
            UserEntity user = userService.getById(orderFormDetailVO.getOwnerBy());
            if (Objects.nonNull(user)) {
                DeptEntity dept = departService.getById(fuser.getDeptId());
                if (Objects.nonNull(dept)) {
                    orderFormDetailVO.setFormerDeptName(dept.getName());
                }
            }
        }

        //获取相关附件
        LambdaQueryWrapper<SysResourceEntity> resourceWrapper = new LambdaQueryWrapper<>();
        resourceWrapper.eq(SysResourceEntity::getResourceType, ResourceTypeEnum.ORDER_FORM.code);
        resourceWrapper.eq(SysResourceEntity::getResourceTypeId,orderFormDetailVO.getId());
        resourceWrapper.eq(SysResourceEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        List<SysResourceEntity> sysResourceList = sysResourceService.list(resourceWrapper);
        orderFormDetailVO.setResourceList(sysResourceList);

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

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

        return orderFormDetailVO;
    }

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

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

    private String concatRegexp(List<Long> ids){
        if(ids.size()==0){
            return "-";
        }else {
            return ids.stream().map(String::valueOf).collect(Collectors.joining("|"));
        }
    }


}
