package com.storlead.sales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.ConvertUtils;
import com.storlead.framework.common.util.StringUtil;
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.entity.customer.*;
import com.storlead.sales.pojo.dto.report.CustomerStatusAnalysisDTO;
import com.storlead.sales.pojo.dto.report.DataSummaryDTO;
import com.storlead.sales.pojo.vo.report.CustomerStatusTotalVO;
import com.storlead.sales.pojo.vo.report.DataSummaryTotalVO;
import com.storlead.sales.pojo.vo.report.*;
import com.storlead.sales.service.CustomerAttributeAnalysisService;
import com.storlead.sales.util.report.AnalysisUtils;
import com.storlead.sales.mapper.CustomerAttributeAnalysisMapper;
import com.storlead.sales.service.customer.*;
import com.storlead.sales.service.systemrule.OperationLogService;
import com.storlead.sales.util.CalculateGrowthUtils;
import com.storlead.system.enums.OrganizationalTypeEnum;
import com.storlead.system.pojo.entity.SysDictDetailEntity;
import com.storlead.system.service.IUserRoleService;
import com.storlead.system.service.SysDictDetailService;
import com.storlead.user.service.IUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/***
  * @Description: 客户统计
  * @Param:
  * @return:
  * @Author: YPZ
  * @Date: 2024/12/27 17:28
  */
@Log4j2
@Service
public class CustomerAttributeAnalysisServiceImpl implements CustomerAttributeAnalysisService {

    @Resource
    private SysDictDetailService sysDictDetailService;
    @Resource
    private CustomerAttributeAnalysisMapper customerAttributeAnalysisMapper;
    @Resource
    private CustomerFollowUpService followUpService;
    @Resource
    private CustomerService customerService;
    @Resource
    private BusinessService businessService;
    @Resource
    private LiaisonService liaisonService;
    @Resource
    private OrderFormService orderFormService;
    @Resource
    private OperationLogService operationLogService;
    @Resource
    private IUserService userService;
    @Resource
    private IUserRoleService userRoleService;


    @Override
    public List<CustomerStatusTotalVO> customerStatusAnalyticsTotal(CustomerStatusAnalysisDTO customerStatusAnalysisDTO) {
        //查询字典全部客户状态
        Map<String, SysDictDetailEntity> SysDictDetailMap = sysDictDetailService.getDictDetailByCode("customer_status");
        if (CollectionUtils.isEmpty(SysDictDetailMap)) {
            return new ArrayList<>();
        }
        //遍历SysDictDetailMap
        List<String> statusList = new ArrayList<>();
        for (Map.Entry<String, SysDictDetailEntity> entry : SysDictDetailMap.entrySet()) {
            statusList.add(entry.getValue().getValue());
        }
        customerStatusAnalysisDTO.setStatusList(statusList);
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getDeptIds()) && CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())){
            Set<Long> userIds = userService.getUserIdsByDeptIds(customerStatusAnalysisDTO.getDeptIds());
            customerStatusAnalysisDTO.setOwnerByIds(new ArrayList<>(userIds));
        }
        //查询各种客户状态对应的客户主键List
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                customerStatusAnalysisDTO.setOwnerByIds(ConvertUtils.retainByIds(customerStatusAnalysisDTO.getOwnerByIds(),dataScope));
            }
        } else {
            customerStatusAnalysisDTO.setOwnerByIds(List.copyOf(dataScope));
        }
        List<CustomerStatusTotalVO> customerStatusTotalVOList = customerAttributeAnalysisMapper.getListByStatus(customerStatusAnalysisDTO);
        //总客户数量
        Integer customerNum = 0;
        for (CustomerStatusTotalVO customerStatusTotalVO : customerStatusTotalVOList){
            if (!ObjectUtils.isEmpty(customerStatusTotalVO.getCustomerIds())) {
                int customerAddNum = customerStatusTotalVO.getCustomerIds().split(",").length;
                customerNum += customerAddNum;
                //查询客户总数量
                LambdaQueryWrapper<CustomerEntity> customerWrapper = new LambdaQueryWrapper<>();
                customerWrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                customerWrapper.eq(CustomerEntity::getCustomerForm,10);
                customerWrapper.eq(CustomerEntity::getHasPublicCustomer,false);
                customerWrapper.eq(CustomerEntity::getHasGarbageCustomer,false);
                customerWrapper.eq(CustomerEntity::getCustomerStatusDictValue, customerStatusTotalVO.getCustomerStatusDictValue());
                int customerTotalNum = customerService.count(customerWrapper);
                customerStatusTotalVO.setAddCustomerPercent(AnalysisUtils.calculatePercentage(customerAddNum,customerTotalNum));
            }
        }
        if (customerNum == 0){
            return new ArrayList<>();
        }
        for (CustomerStatusTotalVO customerStatusTotalVO : customerStatusTotalVOList){
            List<Long> customerIdList = StringUtil.stringToLongList(customerStatusTotalVO.getCustomerIds());
            customerStatusTotalVO.setAddCustomerNum(customerIdList.size());
            customerStatusTotalVO.setCustomerStatusPercent(AnalysisUtils.calculatePercentage(customerStatusTotalVO.getAddCustomerNum(),customerNum));

            LambdaQueryWrapper<CustomerFollowUpEntity> followWrapper = new LambdaQueryWrapper<>();
            followWrapper.in(CustomerFollowUpEntity::getCustomerId,customerIdList);
            followWrapper.eq(CustomerFollowUpEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            followWrapper.ge(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getBeginTime()),CustomerFollowUpEntity::getFollowUpTime,customerStatusAnalysisDTO.getBeginTime());
            followWrapper.le(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getEndTime()),CustomerFollowUpEntity::getFollowUpTime,customerStatusAnalysisDTO.getEndTime());
            Integer followUpNum = followUpService.count(followWrapper);
            customerStatusTotalVO.setFollowUpNum(followUpNum);

            //成交次数
            LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
            orderFormWrapper.in(OrderFormEntity::getCustomerId,customerIdList);
            orderFormWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            orderFormWrapper.ge(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getBeginTime()),OrderFormEntity::getCreateTime,customerStatusAnalysisDTO.getBeginTime());
            orderFormWrapper.le(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getEndTime()),OrderFormEntity::getCreateTime,customerStatusAnalysisDTO.getEndTime());
            List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);
            customerStatusTotalVO.setDealNum(orderFormList.size());
            //成交总额
            BigDecimal totalOrderAmt = orderFormList.stream().map(OrderFormEntity::getTotalOrderAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
            customerStatusTotalVO.setDealTotal(totalOrderAmt);
        }
        SysBaseField.dictFileds(customerStatusTotalVOList);
        SysBaseField.orgFileds(customerStatusTotalVOList);

        return customerStatusTotalVOList;
    }

    @Override
    public List<CustomerStatusTotalVO> customerSourceAnalyticsTotal(CustomerStatusAnalysisDTO customerStatusAnalysisDTO) {
        //查询字典全部客户状态
        Map<String, SysDictDetailEntity> SysDictDetailMap = sysDictDetailService.getDictDetailByCode("customer_source");
        if (CollectionUtils.isEmpty(SysDictDetailMap)) {
            return new ArrayList<>();
        }
        //遍历SysDictDetailMap
        List<String> statusList = new ArrayList<>();
        for (Map.Entry<String, SysDictDetailEntity> entry : SysDictDetailMap.entrySet()) {
            statusList.add(entry.getValue().getValue());
        }
        customerStatusAnalysisDTO.setSourceList(statusList);
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                customerStatusAnalysisDTO.setOwnerByIds(ConvertUtils.retainByIds(customerStatusAnalysisDTO.getOwnerByIds(),dataScope));
            }
        } else {
            customerStatusAnalysisDTO.setOwnerByIds(List.copyOf(dataScope));
        }
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getDeptIds()) && CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())){
            Set<Long> userIds = userService.getUserIdsByDeptIds(customerStatusAnalysisDTO.getDeptIds());
            customerStatusAnalysisDTO.setOwnerByIds(new ArrayList<>(userIds));
        }
        //查询各种客户状态对应的客户主键List
        List<CustomerStatusTotalVO> customerStatusTotalVOList = customerAttributeAnalysisMapper.getListBySource(customerStatusAnalysisDTO);
        //总客户数量
        Integer customerNum = 0;
        for (CustomerStatusTotalVO customerStatusTotalVO : customerStatusTotalVOList){
            if (!ObjectUtils.isEmpty(customerStatusTotalVO.getCustomerIds())) {
//                customerNum += customerStatusTotalVO.getCustomerIds().split(",").length;
                int customerAddNum = customerStatusTotalVO.getCustomerIds().split(",").length;
                customerNum += customerAddNum;
                //查询客户总数量
                LambdaQueryWrapper<CustomerEntity> customerWrapper = new LambdaQueryWrapper<>();
                customerWrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                customerWrapper.eq(CustomerEntity::getCustomerForm,10);
                customerWrapper.eq(CustomerEntity::getHasPublicCustomer,false);
                customerWrapper.eq(CustomerEntity::getHasGarbageCustomer,false);
                customerWrapper.eq(CustomerEntity::getCustomerSourceDictValue, customerStatusTotalVO.getCustomerSourceDictValue());
                int customerTotalNum = customerService.count(customerWrapper);
                customerStatusTotalVO.setAddCustomerPercent(AnalysisUtils.calculatePercentage(customerAddNum,customerTotalNum));
            }
        }
        if (customerNum == 0){
            return new ArrayList<>();
        }
        for (CustomerStatusTotalVO customerStatusTotalVO : customerStatusTotalVOList){
            List<Long> customerIdList = StringUtil.stringToLongList(customerStatusTotalVO.getCustomerIds());
            customerStatusTotalVO.setAddCustomerNum(customerIdList.size());
            customerStatusTotalVO.setCustomerStatusPercent(AnalysisUtils.calculatePercentage(customerStatusTotalVO.getAddCustomerNum(),customerNum));

            LambdaQueryWrapper<CustomerFollowUpEntity> followWrapper = new LambdaQueryWrapper<>();
            followWrapper.in(CustomerFollowUpEntity::getCustomerId,customerIdList);
            followWrapper.eq(CustomerFollowUpEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            followWrapper.ge(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getBeginTime()),CustomerFollowUpEntity::getFollowUpTime,customerStatusAnalysisDTO.getBeginTime());
            followWrapper.le(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getEndTime()),CustomerFollowUpEntity::getFollowUpTime,customerStatusAnalysisDTO.getEndTime());
            Integer followUpNum = followUpService.count(followWrapper);
            customerStatusTotalVO.setFollowUpNum(followUpNum);

            //成交次数
            LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
            orderFormWrapper.in(OrderFormEntity::getCustomerId,customerIdList);
            orderFormWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            orderFormWrapper.ge(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getBeginTime()),OrderFormEntity::getCreateTime,customerStatusAnalysisDTO.getBeginTime());
            orderFormWrapper.le(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getEndTime()),OrderFormEntity::getCreateTime,customerStatusAnalysisDTO.getEndTime());
            List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);
            customerStatusTotalVO.setDealNum(orderFormList.size());
            //成交总额
            BigDecimal totalOrderAmt = orderFormList.stream().map(OrderFormEntity::getTotalOrderAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
            customerStatusTotalVO.setDealTotal(totalOrderAmt);
        }
        SysBaseField.dictFileds(customerStatusTotalVOList);
        SysBaseField.orgFileds(customerStatusTotalVOList);

        return customerStatusTotalVOList;
    }

    @Override
    public List<CustomerStatusTotalVO> customerLevelAnalyticsTotal(CustomerStatusAnalysisDTO customerStatusAnalysisDTO) {
        //查询字典全部客户状态
        Map<String, SysDictDetailEntity> SysDictDetailMap = sysDictDetailService.getDictDetailByCode("customer_level");
        if (CollectionUtils.isEmpty(SysDictDetailMap)) {
            return new ArrayList<>();
        }
        //遍历SysDictDetailMap
        List<String> levelList = new ArrayList<>();
        for (Map.Entry<String, SysDictDetailEntity> entry : SysDictDetailMap.entrySet()) {
            levelList.add(entry.getValue().getValue());
        }
        customerStatusAnalysisDTO.setLevelList(levelList);
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                customerStatusAnalysisDTO.setOwnerByIds(ConvertUtils.retainByIds(customerStatusAnalysisDTO.getOwnerByIds(),dataScope));
            }
        } else {
            customerStatusAnalysisDTO.setOwnerByIds(List.copyOf(dataScope));
        }
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getDeptIds()) && CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())){
            Set<Long> userIds = userService.getUserIdsByDeptIds(customerStatusAnalysisDTO.getDeptIds());
            customerStatusAnalysisDTO.setOwnerByIds(new ArrayList<>(userIds));
        }
        //查询各种客户状态对应的客户主键List
        List<CustomerStatusTotalVO> customerStatusTotalVOList = customerAttributeAnalysisMapper.getListByLevel(customerStatusAnalysisDTO);
        //总客户数量
        Integer customerNum = 0;
        for (CustomerStatusTotalVO customerStatusTotalVO : customerStatusTotalVOList){
            if (!ObjectUtils.isEmpty(customerStatusTotalVO.getCustomerIds())) {
//                customerNum += customerStatusTotalVO.getCustomerIds().split(",").length;
                int customerAddNum = customerStatusTotalVO.getCustomerIds().split(",").length;
                customerNum += customerAddNum;
                //查询客户总数量
                LambdaQueryWrapper<CustomerEntity> customerWrapper = new LambdaQueryWrapper<>();
                customerWrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                customerWrapper.eq(CustomerEntity::getCustomerForm,10);
                customerWrapper.eq(CustomerEntity::getHasPublicCustomer,false);
                customerWrapper.eq(CustomerEntity::getHasGarbageCustomer,false);
                customerWrapper.eq(CustomerEntity::getCustomerLevelDictValue, customerStatusTotalVO.getCustomerLevelDictValue());
                int customerTotalNum = customerService.count(customerWrapper);
                customerStatusTotalVO.setAddCustomerPercent(AnalysisUtils.calculatePercentage(customerAddNum,customerTotalNum));

            }
        }
        if (customerNum == 0){
            return new ArrayList<>();
        }
        for (CustomerStatusTotalVO customerStatusTotalVO : customerStatusTotalVOList){
            List<Long> customerIdList = StringUtil.stringToLongList(customerStatusTotalVO.getCustomerIds());
            customerStatusTotalVO.setAddCustomerNum(customerIdList.size());
            customerStatusTotalVO.setCustomerStatusPercent(AnalysisUtils.calculatePercentage(customerStatusTotalVO.getAddCustomerNum(),customerNum));

            LambdaQueryWrapper<CustomerFollowUpEntity> followWrapper = new LambdaQueryWrapper<>();
            followWrapper.in(CustomerFollowUpEntity::getCustomerId,customerIdList);
            followWrapper.eq(CustomerFollowUpEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            followWrapper.ge(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getBeginTime()),CustomerFollowUpEntity::getFollowUpTime,customerStatusAnalysisDTO.getBeginTime());
            followWrapper.le(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getEndTime()),CustomerFollowUpEntity::getFollowUpTime,customerStatusAnalysisDTO.getEndTime());
            Integer followUpNum = followUpService.count(followWrapper);
            customerStatusTotalVO.setFollowUpNum(followUpNum);

            //成交次数
            LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
            orderFormWrapper.in(OrderFormEntity::getCustomerId,customerIdList);
            orderFormWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            orderFormWrapper.ge(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getBeginTime()),OrderFormEntity::getCreateTime,customerStatusAnalysisDTO.getBeginTime());
            orderFormWrapper.le(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getEndTime()),OrderFormEntity::getCreateTime,customerStatusAnalysisDTO.getEndTime());
            List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);
            customerStatusTotalVO.setDealNum(orderFormList.size());
            //成交总额
            BigDecimal totalOrderAmt = orderFormList.stream().map(OrderFormEntity::getTotalOrderAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
            customerStatusTotalVO.setDealTotal(totalOrderAmt);
        }
        SysBaseField.dictFileds(customerStatusTotalVOList);
        SysBaseField.orgFileds(customerStatusTotalVOList);

        return customerStatusTotalVOList;
    }

    @Override
    public List<CustomerStatusTotalVO> customerCountryAnalyticsTotal(CustomerStatusAnalysisDTO customerStatusAnalysisDTO) {
        // 1. 根据部门ID获取用户ID（如果传了部门ID但没传用户ID）
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getDeptIds()) && CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())) {
            Set<Long> userIds = userService.getUserIdsByDeptIds(customerStatusAnalysisDTO.getDeptIds());
            customerStatusAnalysisDTO.setOwnerByIds(new ArrayList<>(userIds));
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                customerStatusAnalysisDTO.setOwnerByIds(ConvertUtils.retainByIds(customerStatusAnalysisDTO.getOwnerByIds(),dataScope));
            }
        } else {
            customerStatusAnalysisDTO.setOwnerByIds(List.copyOf(dataScope));
        }

        // 2. 查询按国家分组的客户ID列表
        List<CustomerStatusTotalVO> customerStatusTotalVOList = customerAttributeAnalysisMapper.getListByCountry(customerStatusAnalysisDTO);
        if (CollectionUtils.isEmpty(customerStatusTotalVOList)) {
            return new ArrayList<>();
        }

        // 3. 准备数据容器
        Map<String, List<Long>> countryCustomerIdsMap = new HashMap<>(); // 国家->客户ID列表
        List<Long> allCustomerIds = new ArrayList<>(); // 所有客户ID
        Set<String> countries = new HashSet<>(); // 所有国家集合

        // 4. 第一次遍历：准备基础数据
        for (CustomerStatusTotalVO vo : customerStatusTotalVOList) {
            if (!StringUtils.isEmpty(vo.getCustomerIds())) {
                List<Long> customerIds = StringUtil.stringToLongList(vo.getCustomerIds());
                vo.setAddCustomerNum(customerIds.size()); // 设置新增客户数
                countryCustomerIdsMap.put(vo.getCountry(), customerIds);
                allCustomerIds.addAll(customerIds);
                countries.add(vo.getCountry());
            }
        }

        // 5. 计算总客户数
        int customerNum = allCustomerIds.size();
        if (customerNum == 0) {
            return new ArrayList<>();
        }

        // 6. 批量查询各国客户总数（优化点：将循环内查询改为批量查询）
        Map<String, Long> countryTotalCustomerMap = getCountryTotalCustomerMap(countries);

        // 7. 批量查询客户跟进次数（优化点：将循环内查询改为批量查询）
        Map<Long, Long> followUpCountMap = getFollowUpCountMap(allCustomerIds, customerStatusAnalysisDTO);

        // 8. 批量查询订单数据（优化点：将循环内查询改为批量查询）
        Map<Long, List<OrderFormEntity>> orderFormMap = getOrderFormMap(allCustomerIds, customerStatusAnalysisDTO);

        // 9. 第二次遍历：设置计算结果
        for (CustomerStatusTotalVO vo : customerStatusTotalVOList) {
            List<Long> customerIds = countryCustomerIdsMap.get(vo.getCountry());
            if (customerIds == null || customerIds.isEmpty()) {
                continue;
            }

            // 10. 设置百分比
            int addNum = customerIds.size();
            long totalNum = countryTotalCustomerMap.getOrDefault(vo.getCountry(), 1L);
            vo.setAddCustomerPercent(AnalysisUtils.calculatePercentage(addNum, (int) totalNum)); // 新增客户占比
            vo.setCustomerStatusPercent(AnalysisUtils.calculatePercentage(addNum, customerNum)); // 客户状态占比

            // 11. 计算跟进次数总和
            long followUpNum = customerIds.stream()
                    .mapToLong(id -> followUpCountMap.getOrDefault(id, 0L))
                    .sum();
            vo.setFollowUpNum((int) followUpNum);

            // 12. 计算订单数据
            List<OrderFormEntity> orderForms = customerIds.stream()
                    .flatMap(id -> orderFormMap.getOrDefault(id, Collections.emptyList()).stream())
                    .collect(Collectors.toList());

            vo.setDealNum(orderForms.size()); // 成交次数
            vo.setDealTotal(orderForms.stream() // 成交总额
                    .map(OrderFormEntity::getTotalOrderAmt)
                    .reduce(BigDecimal.ZERO, BigDecimal::add));
        }

        // 13. 设置字典和部门字段
        SysBaseField.dictFileds(customerStatusTotalVOList);
        SysBaseField.orgFileds(customerStatusTotalVOList);

        return customerStatusTotalVOList;
    }

    /**
     * 批量查询各国客户总数
     */
    private Map<String, Long> getCountryTotalCustomerMap(Set<String> countries) {
        if (CollectionUtils.isEmpty(countries)) {
            return Collections.emptyMap();
        }

        // 使用原生SQL查询提高效率
        QueryWrapper<CustomerEntity> wrapper = new QueryWrapper<>();
        wrapper.select("country", "COUNT(id) as customer_count");
        wrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
        wrapper.eq("customer_form", 10);
        wrapper.eq("has_public_customer", 0);
        wrapper.eq("has_garbage_customer", 0);
        wrapper.in("country", countries);
        wrapper.groupBy("country");

        // 将查询结果转为Map<国家,客户数>
        return customerService.listMaps(wrapper).stream()
                .collect(Collectors.toMap(
                        map -> (String) map.get("country"),
                        map -> (Long) map.get("customer_count"),
                        (a, b) -> a
                ));
    }

    /**
     * 批量查询客户跟进次数
     */
    private Map<Long, Long> getFollowUpCountMap(List<Long> customerIds, CustomerStatusAnalysisDTO dto) {
        if (CollectionUtils.isEmpty(customerIds)) {
            return Collections.emptyMap();
        }

        // 分批查询防止SQL语句过长（每批1000个）
        int batchSize = 1000;
        Map<Long, Long> result = new HashMap<>();

        for (int i = 0; i < customerIds.size(); i += batchSize) {
            List<Long> batchIds = customerIds.subList(i, Math.min(i + batchSize, customerIds.size()));

            QueryWrapper<CustomerFollowUpEntity> wrapper = new QueryWrapper<>();
            wrapper.select("customer_id", "COUNT(id) as follow_count");
            wrapper.in("customer_id", batchIds);
            wrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
            if (!ObjectUtils.isEmpty(dto.getBeginTime())) {
                wrapper.ge("follow_up_time", dto.getBeginTime());
            }
            if (!ObjectUtils.isEmpty(dto.getEndTime())) {
                wrapper.le("follow_up_time", dto.getEndTime());
            }
            wrapper.groupBy("customer_id");

            // 将每批结果加入总结果集
            followUpService.listMaps(wrapper).forEach(map -> {
                result.put(
                        ((Number) map.get("customer_id")).longValue(),
                        ((Number) map.get("follow_count")).longValue()
                );
            });
        }

        return result;
    }

    /**
     * 批量查询订单数据
     */
    private Map<Long, List<OrderFormEntity>> getOrderFormMap(List<Long> customerIds, CustomerStatusAnalysisDTO dto) {
        if (CollectionUtils.isEmpty(customerIds)) {
            return Collections.emptyMap();
        }

        // 分批查询防止SQL语句过长（每批1000个）
        int batchSize = 1000;
        Map<Long, List<OrderFormEntity>> result = new HashMap<>();

        for (int i = 0; i < customerIds.size(); i += batchSize) {
            List<Long> batchIds = customerIds.subList(i, Math.min(i + batchSize, customerIds.size()));

            LambdaQueryWrapper<OrderFormEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(OrderFormEntity::getCustomerId, batchIds);
            wrapper.eq(OrderFormEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            if (!ObjectUtils.isEmpty(dto.getBeginTime())) {
                wrapper.ge(OrderFormEntity::getCreateTime, dto.getBeginTime());
            }
            if (!ObjectUtils.isEmpty(dto.getEndTime())) {
                wrapper.le(OrderFormEntity::getCreateTime, dto.getEndTime());
            }

            // 将每批结果按客户ID分组
            orderFormService.list(wrapper).forEach(order -> {
                result.computeIfAbsent(order.getCustomerId(), k -> new ArrayList<>()).add(order);
            });
        }

        return result;
    }
    public List<CustomerStatusTotalVO> customerCountryAnalyticsTotalOld(CustomerStatusAnalysisDTO customerStatusAnalysisDTO) {
        //查询字典全部客户状态
        if (!CollectionUtils.isEmpty(customerStatusAnalysisDTO.getDeptIds()) && CollectionUtils.isEmpty(customerStatusAnalysisDTO.getOwnerByIds())){
            Set<Long> userIds = userService.getUserIdsByDeptIds(customerStatusAnalysisDTO.getDeptIds());
            customerStatusAnalysisDTO.setOwnerByIds(new ArrayList<>(userIds));
        }
        //查询各种客户状态对应的客户主键List
        List<CustomerStatusTotalVO> customerStatusTotalVOList = customerAttributeAnalysisMapper.getListByCountry(customerStatusAnalysisDTO);
        //总客户数量
        Integer customerNum = 0;
        for (CustomerStatusTotalVO customerStatusTotalVO : customerStatusTotalVOList){
            if (!ObjectUtils.isEmpty(customerStatusTotalVO.getCustomerIds())) {
//                customerNum += customerStatusTotalVO.getCustomerIds().split(",").length;
                int customerAddNum = customerStatusTotalVO.getCustomerIds().split(",").length;
                customerNum += customerAddNum;
                //查询客户总数量
                LambdaQueryWrapper<CustomerEntity> customerWrapper = new LambdaQueryWrapper<>();
                customerWrapper.eq(CustomerEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
                customerWrapper.eq(CustomerEntity::getCustomerForm,10);
                customerWrapper.eq(CustomerEntity::getCountry, customerStatusTotalVO.getCountry());
                int customerTotalNum = customerService.count(customerWrapper);
                customerStatusTotalVO.setAddCustomerPercent(AnalysisUtils.calculatePercentage(customerAddNum,customerTotalNum));

            }
        }
        if (customerNum == 0){
            return new ArrayList<>();
        }
        for (CustomerStatusTotalVO customerStatusTotalVO : customerStatusTotalVOList){
            List<Long> customerIdList = StringUtil.stringToLongList(customerStatusTotalVO.getCustomerIds());
            customerStatusTotalVO.setAddCustomerNum(customerIdList.size());
            customerStatusTotalVO.setCustomerStatusPercent(AnalysisUtils.calculatePercentage(customerStatusTotalVO.getAddCustomerNum(),customerNum));

            LambdaQueryWrapper<CustomerFollowUpEntity> followWrapper = new LambdaQueryWrapper<>();
            followWrapper.in(CustomerFollowUpEntity::getCustomerId,customerIdList);
            followWrapper.eq(CustomerFollowUpEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            followWrapper.ge(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getBeginTime()),CustomerFollowUpEntity::getFollowUpTime,customerStatusAnalysisDTO.getBeginTime());
            followWrapper.le(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getEndTime()),CustomerFollowUpEntity::getFollowUpTime,customerStatusAnalysisDTO.getEndTime());
            Integer followUpNum = followUpService.count(followWrapper);
            customerStatusTotalVO.setFollowUpNum(followUpNum);

            //成交次数
            LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
            orderFormWrapper.in(OrderFormEntity::getCustomerId,customerIdList);
            orderFormWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            orderFormWrapper.ge(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getBeginTime()),OrderFormEntity::getCreateTime,customerStatusAnalysisDTO.getBeginTime());
            orderFormWrapper.le(!ObjectUtils.isEmpty(customerStatusAnalysisDTO.getEndTime()),OrderFormEntity::getCreateTime,customerStatusAnalysisDTO.getEndTime());
            List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);
            customerStatusTotalVO.setDealNum(orderFormList.size());
            //成交总额
            BigDecimal totalOrderAmt = orderFormList.stream().map(OrderFormEntity::getTotalOrderAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
            customerStatusTotalVO.setDealTotal(totalOrderAmt);
        }
        SysBaseField.dictFileds(customerStatusTotalVOList);
        SysBaseField.orgFileds(customerStatusTotalVOList);

        return customerStatusTotalVOList;
    }

    @Override
    public Result<?> selectDataSummary(DataSummaryDTO dataSummaryDTO) {
        DataSummaryTotalVO dataSummaryTotalVO = new DataSummaryTotalVO();
        List<Long> userIdList = dataSummaryDTO.getUserIdList();
        LocalDateTime startDateTime = LocalDateTime.now();
        LocalDateTime endDateTime = LocalDateTime.now();
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        //查询要统计的开始及结束时间
        if (dataSummaryDTO.getDateType() == 2){
            // 获取本月的第一天，时间为00:00:00
            startDateTime = now.withDayOfMonth(1)
                    .withHour(0)
                    .withMinute(0)
                    .withSecond(0)
                    .withNano(0);

            // 获取本月的最后一天，时间为23:59:59
            LocalDateTime endOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
            endDateTime = endOfMonth.withHour(23)
                    .withMinute(59)
                    .withSecond(59)
                    .withNano(0);
        }
        if (dataSummaryDTO.getDateType() == 3){
            // 获取本周的周一日期（ISO 8601标准，周一为一周的第一天）
            startDateTime = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                    .withHour(0)
                    .withMinute(0)
                    .withSecond(0)
                    .withNano(0);

            // 获取本周的周日日期（基于周一日期加6天得到）
            endDateTime = startDateTime.plusDays(6)
                    .withHour(23)
                    .withMinute(59)
                    .withSecond(59)
                    .withNano(0);
        }
        //统计新增客户数
        LambdaQueryWrapper<CustomerEntity> customerWrapper = new LambdaQueryWrapper<>();
        customerWrapper.eq(CustomerEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        customerWrapper.eq(CustomerEntity::getCustomerForm,10);
        customerWrapper.eq(CustomerEntity::getPublicDate,false);
        customerWrapper.eq(CustomerEntity::getHasGarbageCustomer,false);
        customerWrapper.ge(CustomerEntity::getCreateTime,startDateTime);
        customerWrapper.le(CustomerEntity::getCreateTime,endDateTime);
        customerWrapper.in(CustomerEntity::getOwnerBy,userIdList);
        dataSummaryTotalVO.setAddCustomerNum(customerService.count(customerWrapper));

        //统计新增线索数
        LambdaQueryWrapper<CustomerEntity> clusWrapper = new LambdaQueryWrapper<>();
        clusWrapper.eq(CustomerEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        clusWrapper.eq(CustomerEntity::getCustomerForm,11);
        customerWrapper.eq(CustomerEntity::getPublicDate,false);
        customerWrapper.eq(CustomerEntity::getHasGarbageCustomer,false);
        clusWrapper.ge(CustomerEntity::getCreateTime,startDateTime);
        clusWrapper.le(CustomerEntity::getCreateTime,endDateTime);
        clusWrapper.in(CustomerEntity::getOwnerBy,userIdList);
        dataSummaryTotalVO.setAddClusNum(customerService.count(clusWrapper));
        //统计新增商机数
        LambdaQueryWrapper<BusinessEntity> businessWrapper = new LambdaQueryWrapper<>();
        businessWrapper.eq(BusinessEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        businessWrapper.ge(BusinessEntity::getGetedDate,startDateTime);
        businessWrapper.le(BusinessEntity::getGetedDate,endDateTime);
        businessWrapper.in(BusinessEntity::getOwnerBy,userIdList);
        dataSummaryTotalVO.setAddBusinessNum(businessService.count(businessWrapper));
        //统计成交商机数
//        LambdaQueryWrapper<OperationLogEntity> operationLogWrapper = new LambdaQueryWrapper<>();
//        operationLogWrapper.eq(OperationLogEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
//        operationLogWrapper.eq(OperationLogEntity::getResourceType,30);
//        operationLogWrapper.eq(OperationLogEntity::getFieldName,20);
        LambdaQueryWrapper<BusinessEntity> businessNumWrapper = new LambdaQueryWrapper<>();
        businessNumWrapper.eq(BusinessEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        businessNumWrapper.eq(BusinessEntity::getStage,4);
//        businessNumWrapper.ge(BusinessEntity::getGetedDate,startDateTime);
//        businessNumWrapper.le(BusinessEntity::getGetedDate,endDateTime);
        businessNumWrapper.ge(BusinessEntity::getSigningDate,startDateTime);
        businessNumWrapper.le(BusinessEntity::getSigningDate,endDateTime);
        businessNumWrapper.in(BusinessEntity::getOwnerBy,userIdList);
        dataSummaryTotalVO.setTransactionsBusiness(businessService.count(businessNumWrapper));

        //统计新增订单数
        LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
        orderFormWrapper.eq(OrderFormEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        orderFormWrapper.ge(OrderFormEntity::getCreateTime,startDateTime);
        orderFormWrapper.le(OrderFormEntity::getCreateTime,endDateTime);
        orderFormWrapper.in(OrderFormEntity::getOwnerBy,userIdList);
        List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);
        int orderFormNum = orderFormList.size();
        dataSummaryTotalVO.setAddOrderFormNum(orderFormNum);

        //统计新增联系人数
        LambdaQueryWrapper<LiaisonEntity> liaisonWrapper = new LambdaQueryWrapper<>();
        liaisonWrapper.eq(LiaisonEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        liaisonWrapper.ge(LiaisonEntity::getCreateTime,startDateTime);
        liaisonWrapper.le(LiaisonEntity::getCreateTime,endDateTime);
        liaisonWrapper.in(LiaisonEntity::getOwnerBy,userIdList);
        dataSummaryTotalVO.setAddLiaisonNum(liaisonService.count(liaisonWrapper));

        //统计跟进次数
        LambdaQueryWrapper<CustomerFollowUpEntity> followUpWrapper = new LambdaQueryWrapper<>();
        followUpWrapper.eq(CustomerFollowUpEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        followUpWrapper.ge(CustomerFollowUpEntity::getCreateTime,startDateTime);
        followUpWrapper.le(CustomerFollowUpEntity::getCreateTime,endDateTime);
        followUpWrapper.in(CustomerFollowUpEntity::getOwnerBy,userIdList);
        dataSummaryTotalVO.setFollowUpNum(followUpService.count(followUpWrapper));

        //统计成交次数
        //获取商机不为空的订单
        if (orderFormNum>0) {
            List<OrderFormEntity> orderFormListNotNull = orderFormList.stream().filter(orderFormEntity -> !ObjectUtils.isEmpty(orderFormEntity.getBusinessId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(orderFormListNotNull)){
                dataSummaryTotalVO.setTransactionsNum(orderFormListNotNull.size());
            }

        }

        //统计成交总额
        if (orderFormNum > 0){
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (OrderFormEntity orderFormEntity : orderFormList){
                totalAmount = totalAmount.add(orderFormEntity.getTotalOrderAmt());
            }
            dataSummaryTotalVO.setTransactionsAmount(totalAmount);
        }

        return Result.result(dataSummaryTotalVO);
    }

    @Override
    public Result<?> selectHomeDataSummary(DataSummaryDTO dataSummaryDTO) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();

        // 添加当前月份的日期范围
        LocalDate currentDate = LocalDate.now();
        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
        LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth());

        // 添加上个月的日期范围
        LocalDate firstDayOfLastMonth = currentDate.minusMonths(1).withDayOfMonth(1);
        LocalDate lastDayOfLastMonth = currentDate.minusMonths(1).withDayOfMonth(currentDate.minusMonths(1).lengthOfMonth());

        // 查询当月总订单金额
        LambdaQueryWrapper<OrderFormEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderFormEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(!ObjectUtils.isEmpty(loginUser.getId()), OrderFormEntity::getOwnerBy, loginUser.getId());
        wrapper.between(OrderFormEntity::getSigningDate, firstDayOfMonth, lastDayOfMonth);
        List<OrderFormEntity> orderFormEntityList = orderFormService.list(wrapper);
        // 查询上个月总订单金额
        LambdaQueryWrapper<OrderFormEntity> lastwrapper = new LambdaQueryWrapper<>();
        lastwrapper.eq(OrderFormEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        lastwrapper.eq(!ObjectUtils.isEmpty(loginUser.getId()), OrderFormEntity::getOwnerBy, loginUser.getId());
        lastwrapper.between(OrderFormEntity::getSigningDate, firstDayOfLastMonth, lastDayOfLastMonth);
        List<OrderFormEntity> lastOrderList = orderFormService.list(lastwrapper);

        // 返回当月总订单金额,保留两位小数
        BigDecimal totalOrderAmt = orderFormEntityList.stream()
                .map(OrderFormEntity::getTotalOrderAmt)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .setScale(2, RoundingMode.HALF_UP);

        // 返回上个月总订单金额,保留两位小数
        BigDecimal lastOrderAmt = lastOrderList.stream()
                .map(OrderFormEntity::getTotalOrderAmt)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .setScale(2, RoundingMode.HALF_UP);

        // 计算环比增长率
        BigDecimal growthRate = CalculateGrowthUtils.calculateMonthlyGrowth(totalOrderAmt, lastOrderAmt);

        // 返回总订单数量
        int orderTotalCount = orderFormEntityList.size();
        int lastOrderTotalCount = lastOrderList.size();
        // 计算环比增长率
        Integer orderGrowthRate = CalculateGrowthUtils.calculateMonthlyGrowths(orderTotalCount, lastOrderTotalCount);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("totalOrderCount", orderTotalCount);
        resultMap.put("totalOrderAmt", totalOrderAmt);
        resultMap.put("amountGrowthRate", growthRate);
        resultMap.put("orderGrowthRate", orderGrowthRate);

        // 查询当月新增商机数量
        LambdaQueryWrapper<BusinessEntity> businessWrapper = new LambdaQueryWrapper<>();
        businessWrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        businessWrapper.eq(!ObjectUtils.isEmpty(loginUser.getId()), BusinessEntity::getOwnerBy, loginUser.getId());
        businessWrapper.between(BusinessEntity::getGetedDate, firstDayOfMonth, lastDayOfMonth);
        List<BusinessEntity> businessEntity = businessService.list(businessWrapper);

        // 查询上个月的商机数量
        LambdaQueryWrapper<BusinessEntity> lastBusinessWrapper = new LambdaQueryWrapper<>();
        lastBusinessWrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        lastBusinessWrapper.eq(!ObjectUtils.isEmpty(loginUser.getId()), BusinessEntity::getOwnerBy, loginUser.getId());
        lastBusinessWrapper.between(BusinessEntity::getGetedDate, firstDayOfLastMonth, lastDayOfLastMonth);
        List<BusinessEntity> lastBusinessEntity = businessService.list(lastBusinessWrapper);

        // 统计新增商机数量
        int totalBusinessCount = businessEntity.size();
        int lastTotalBusinessCount = lastBusinessEntity.size();
        // 计算环比增长率
        Integer businessGrowthRate = CalculateGrowthUtils.calculateMonthlyGrowths(totalBusinessCount, lastTotalBusinessCount);
        resultMap.put("totalBusinessCount", totalBusinessCount);
        resultMap.put("businessGrowthRate", businessGrowthRate);

        // 查询当月跟进次数
        LambdaQueryWrapper<CustomerFollowUpEntity> followUpWrapper = new LambdaQueryWrapper<>();
        followUpWrapper.eq(!ObjectUtils.isEmpty(loginUser.getId()), CustomerFollowUpEntity::getOwnerBy, loginUser.getId());
        followUpWrapper.eq(CustomerFollowUpEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        followUpWrapper.between(CustomerFollowUpEntity::getFollowUpTime, firstDayOfMonth, lastDayOfMonth);
        List<CustomerFollowUpEntity> customerFollowUpEntities = followUpService.list(followUpWrapper);

        // 查询上个月的跟进次数
        LambdaQueryWrapper<CustomerFollowUpEntity> lastFollowUpWrapper = new LambdaQueryWrapper<>();
        lastFollowUpWrapper.eq(!ObjectUtils.isEmpty(loginUser.getId()), CustomerFollowUpEntity::getOwnerBy, loginUser.getId());
        lastFollowUpWrapper.eq(CustomerFollowUpEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        lastFollowUpWrapper.between(CustomerFollowUpEntity::getFollowUpTime, firstDayOfLastMonth, lastDayOfLastMonth);
        List<CustomerFollowUpEntity> lastCustomerFollowUpEntities = followUpService.list(lastFollowUpWrapper);
        int lastFollowUpCount = lastCustomerFollowUpEntities.size();

        // 计算环比增长率
        int followUpCount = customerFollowUpEntities.size();
        Integer followUpGrowthRate = CalculateGrowthUtils.calculateMonthlyGrowths(followUpCount, lastFollowUpCount);
        resultMap.put("followUpGrowthRate", followUpGrowthRate);
        resultMap.put("followUpCount", followUpCount);

        return Result.result(resultMap);
    }
}
