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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.sales.pojo.dto.customer.CustomerSearchSearchDTO;
import com.storlead.sales.pojo.entity.customer.BusinessEntity;
import com.storlead.sales.pojo.entity.customer.CustomerEntity;
import com.storlead.sales.pojo.entity.customer.CustomerSearchEntity;
import com.storlead.sales.pojo.vo.customer.CustomerListVO;
import com.storlead.sales.pojo.vo.customer.CustomerSearchListVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.mapper.customer.CustomerSearchMapper;
import com.storlead.sales.service.customer.*;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.service.task.TaskService;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * <p>
 * 查询记录表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2025-06-03
 */
@Service
public class CustomerSearchServiceImpl extends MyBaseServiceImpl<CustomerSearchMapper, CustomerSearchEntity> implements CustomerSearchService {

    @Resource
    private CustomerService customerService;
    @Resource
    private LiaisonService liaisonService;
    @Resource
    private BusinessService businessService;
    @Resource
    private OrderFormService orderFormService;
    @Resource
    private TaskService taskService;
    @Resource
    private IUserService userService;
    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Override
    public Result<?> selectListVO(CustomerSearchSearchDTO customerSearchSearchDTO) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        Long loginUserId = loginUser.getId();
        IPage<Object> objectPage = null;
//        List<CustomerSearchListVO> customerSearchListVOList = new ArrayList<>();
        List<Long> customerIds = customerService.getCustomerIdList(loginUserId);
        String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));
//        select id from `user` WHERE  FIND_IN_SET("+loginUser.getId()+",managers)
        LambdaQueryWrapper<UserEntity> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.apply("FIND_IN_SET({0}, managers)", loginUser.getId());
        List<UserEntity> userList = userService.list(userWrapper);
        List<Long> userIdList = userList.stream().map(UserEntity::getId).collect(Collectors.toList());
        String userIds = userIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
        customerSearchSearchDTO.setLoginUser(loginUser);
        customerSearchSearchDTO.setCustomerIdString(customerIdString);
        customerSearchSearchDTO.setUserIdString(userIds);
        //查询全部相关数据
//        if (ObjectUtils.isEmpty(customerSearchSearchDTO.getResourceType())){
//
//            // 1. 定义任务列表（按顺序）
//            List<Supplier<CustomerSearchListVO>> tasks = Arrays.asList(
//                    // 任务1：查询客户
//                    () -> {
//                        CustomerSearchListVO vo = new CustomerSearchListVO();
//                        vo.setResourceType(ResourceTypeEnum.CUSTOMER.code);
//                        vo.setObjectPage((IPage<Object>) customerService.selectSimpleListVO(customerSearchSearchDTO, ResourceTypeEnum.CUSTOMER.code));
//                        return vo;
//                    },
//                    // 任务2：查询线索
//                    () -> {
//                        CustomerSearchListVO vo = new CustomerSearchListVO();
//                        vo.setResourceType(ResourceTypeEnum.CLUS.code);
//                        vo.setObjectPage((IPage<Object>) customerService.selectSimpleListVO(customerSearchSearchDTO, ResourceTypeEnum.CLUS.code));
//                        return vo;
//                    },
//                    // 任务3：查询商机
//                    () -> {
//                        CustomerSearchListVO vo = new CustomerSearchListVO();
//                        vo.setResourceType(ResourceTypeEnum.BUSINESS.code);
//                        vo.setObjectPage((IPage<Object>) businessService.selectSimpleListVO(customerSearchSearchDTO));
//                        return vo;
//                    },
//                    // 任务4：查询订单
//                    () -> {
//                        CustomerSearchListVO vo = new CustomerSearchListVO();
//                        vo.setResourceType(ResourceTypeEnum.ORDER_FORM.code);
//                        vo.setObjectPage((IPage<Object>) orderFormService.selectSimpleListVO(customerSearchSearchDTO));
//                        return vo;
//                    },
//                    // 任务5：查询联系人
//                    () -> {
//                        CustomerSearchListVO vo = new CustomerSearchListVO();
//                        vo.setResourceType(ResourceTypeEnum.LIAISON.code);
//                        vo.setObjectPage((IPage<Object>) liaisonService.selectSimpleListVO(customerSearchSearchDTO));
//                        return vo;
//                    },
//                    // 任务6：查询任务
//                    () -> {
//                        CustomerSearchListVO vo = new CustomerSearchListVO();
//                        vo.setResourceType(ResourceTypeEnum.TASK_CANCELED.code);
//                        vo.setObjectPage((IPage<Object>) taskService.selectSimpleListVO(customerSearchSearchDTO));
//                        return vo;
//                    }
//            );
//
//            // 2. 并行执行所有任务（使用固定线程池）
//            ExecutorService executor = Executors.newFixedThreadPool(6);
//            List<CompletableFuture<CustomerSearchListVO>> futures = tasks.stream()
//                    .map(task -> CompletableFuture.supplyAsync(task, executor))
//                    .collect(Collectors.toList());
//
//            // 3. 按原始顺序等待结果并添加到列表
//            for (CompletableFuture<CustomerSearchListVO> future : futures) {
//                try {
//                    customerSearchListVOList.add(future.get()); // 阻塞直到当前任务完成
//                } catch (Exception e) {
//                    log.error("查询失败", e);
//                    // 可选：添加空对象或默认值
//                    customerSearchListVOList.add(new CustomerSearchListVO());
//                }
//            }
//
//            // 4. 关闭线程池
//            executor.shutdown();
//        }
        //查询具体业务类型的数据
        if (!ObjectUtils.isEmpty(customerSearchSearchDTO.getResourceType())){
            //查询客户
            if (customerSearchSearchDTO.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code)){
                CustomerSearchListVO customerVO = new CustomerSearchListVO();
                customerVO.setResourceType(ResourceTypeEnum.CUSTOMER.code);
                customerVO.setObjectPage((IPage<Object>)customerService.selectSimpleListVO(customerSearchSearchDTO,ResourceTypeEnum.CUSTOMER.code));
//                customerSearchListVOList.add(customerVO);
                objectPage = customerVO.getObjectPage();
            }
            //查询线索
            if (customerSearchSearchDTO.getResourceType().equals(ResourceTypeEnum.CLUS.code)){
                CustomerSearchListVO clusVO = new CustomerSearchListVO();
                clusVO.setResourceType(ResourceTypeEnum.CLUS.code);
                clusVO.setObjectPage((IPage<Object>)customerService.selectSimpleListVO(customerSearchSearchDTO,ResourceTypeEnum.CLUS.code));
//                customerSearchListVOList.add(clusVO);
                objectPage = clusVO.getObjectPage();
            }
            //查询商机
            if (customerSearchSearchDTO.getResourceType().equals(ResourceTypeEnum.BUSINESS.code)){
                CustomerSearchListVO businessVO = new CustomerSearchListVO();
                businessVO.setResourceType(ResourceTypeEnum.BUSINESS.code);
                businessVO.setObjectPage((IPage<Object>)businessService.selectSimpleListVO(customerSearchSearchDTO));
//                customerSearchListVOList.add(businessVO);
                objectPage = businessVO.getObjectPage();
            }
            //查询订单
            if (customerSearchSearchDTO.getResourceType().equals(ResourceTypeEnum.ORDER_FORM.code)){
                CustomerSearchListVO orderFormVO = new CustomerSearchListVO();
                orderFormVO.setResourceType(ResourceTypeEnum.ORDER_FORM.code);
                orderFormVO.setObjectPage((IPage<Object>)orderFormService.selectSimpleListVO(customerSearchSearchDTO));
//                customerSearchListVOList.add(orderFormVO);
                objectPage = orderFormVO.getObjectPage();
            }
            //查询联系人
            if (customerSearchSearchDTO.getResourceType().equals(ResourceTypeEnum.LIAISON.code)){
                CustomerSearchListVO liaisonVO = new CustomerSearchListVO();
                liaisonVO.setResourceType(ResourceTypeEnum.LIAISON.code);
                liaisonVO.setObjectPage((IPage<Object>)liaisonService.selectSimpleListVO(customerSearchSearchDTO));
//                customerSearchListVOList.add(liaisonVO);
                objectPage = liaisonVO.getObjectPage();
            }
            //查询任务
            if (customerSearchSearchDTO.getResourceType().equals(ResourceTypeEnum.TASK_CANCELED.code)){
                CustomerSearchListVO taskVO = new CustomerSearchListVO();
                taskVO.setResourceType(ResourceTypeEnum.TASK_CANCELED.code);
                taskVO.setObjectPage((IPage<Object>)taskService.selectSimpleListVO(customerSearchSearchDTO));
//                customerSearchListVOList.add(taskVO);
                objectPage = taskVO.getObjectPage();
            }
            //查询跟进
            if (customerSearchSearchDTO.getResourceType().equals(ResourceTypeEnum.FOLLOW_UP.code)){
                CustomerSearchListVO followUpVO = new CustomerSearchListVO();
                followUpVO.setResourceType(ResourceTypeEnum.FOLLOW_UP.code);
                followUpVO.setObjectPage((IPage<Object>)customerFollowUpService.selectSimpleListVO(customerSearchSearchDTO));
//                customerSearchListVOList.add(followUpVO);
                objectPage = followUpVO.getObjectPage();
            }
        }
//        SysBaseField.dictFileds(customerSearchListVOList);
//        SysBaseField.orgFileds(pageVO.getRecords());
        return Result.result(objectPage);
    }
}
