package com.storlead.sales.service.impl;

import cn.hutool.core.util.StrUtil;
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.common.constant.CommonConstant;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.sales.pojo.entity.customer.BusinessEntity;
import com.storlead.sales.pojo.entity.customer.CustomerEntity;
import com.storlead.sales.pojo.vo.customer.BusinessListVO;
import com.storlead.sales.pojo.dto.report.DataAnalysisDTO;
import com.storlead.sales.pojo.vo.report.*;
import com.storlead.sales.service.SalesProcessAnalysisService;
import com.storlead.sales.util.report.AnalysisUtils;
import com.storlead.sales.mapper.SalesAnalysisReportMapper;
import com.storlead.sales.service.customer.BusinessService;
import com.storlead.sales.service.customer.CustomerService;
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 javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-10-22 15:14
 */
@Log4j2
@Service
public class SalesProcessAnalysisServiceImpl implements SalesProcessAnalysisService {

    @Resource
    private BusinessService businessService;

    @Resource
    private CustomerService customerService;

    @Resource
    private SysDictDetailService dictDetailService;

    @Resource
    private IUserService userService;

    @Resource
    private SalesAnalysisReportMapper analysisReportMapper;

    @Resource
    private IUserRoleService userRoleService;
    /**
     * 执行销售预测分析
     */
    @Override
    public BusinessMonthTotalVO performSalesForecastAnalysis(DataAnalysisDTO dto) {

        LambdaQueryWrapper<BusinessEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);

        wrapper.in(!ObjectUtils.isEmpty(dto.getOwnerByIds()),BusinessEntity::getOwnerBy, dto.getOwnerByIds());
        try {
            if (!ObjectUtils.isEmpty(dto.getBeginCycleTime()) && !ObjectUtils.isEmpty(dto.getEndCycleTime())) {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getBeginCycleTime() + " 00:00:00");
                Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getEndCycleTime() + " 23:59:00");
                wrapper.ge(BusinessEntity::getExpectedSigningDate, startDate)
                        .le(BusinessEntity::getExpectedSigningDate, endDate);
            }
        } catch (Exception e) {
            log.error("e",e);
        }
        wrapper.isNotNull(BusinessEntity::getExpectedSigningDate);

        List<BusinessEntity> businessls = businessService.listWithScope(wrapper);

        Map<String, BigDecimal> monthlySales = businessls.stream()
                .collect(Collectors.groupingBy(
                        entity -> new SimpleDateFormat("yyyy-MM").format(entity.getExpectedSigningDate()),
                        Collectors.mapping(BusinessEntity::getEstimatedSalesAmount, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))
                ));

        Map<String, Long> monthlyOpportunityCount = businessls.stream()
                .collect(Collectors.groupingBy(
                        entity -> new SimpleDateFormat("yyyy-MM").format(entity.getExpectedSigningDate()),
                        Collectors.counting()
                ));

        Map<String, BigDecimal> monthlyProbabilitySales = businessls.stream()
                .collect(Collectors.groupingBy(
                        entity -> new SimpleDateFormat("yyyy-MM").format(entity.getExpectedSigningDate()),
                        Collectors.mapping(entity -> {
                            BigDecimal estimatedSales = entity.getEstimatedSalesAmount();
                            // 假设成交几率为字符串，格式为 "80%"，需要转换为 BigDecimal
                            BigDecimal transactionProbability = new BigDecimal(entity.getTransactionProbabilityDictValue()).divide(new BigDecimal(100));
                            return estimatedSales.multiply(transactionProbability);
                        }, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))
                ));
        List<String> months = AnalysisUtils.generateYearMonthMap();
        if (StrUtil.isNotBlank(dto.getBeginCycleTime()) && StrUtil.isNotBlank(dto.getEndCycleTime())) {
            months = AnalysisUtils.generateYearMonthMap(dto.getBeginCycleTime(),dto.getEndCycleTime());
        }
        List<BusinessMonthCountVO> monthTotalls = new ArrayList<>();
        for (String month : months) {
            BusinessMonthCountVO vo = new BusinessMonthCountVO();
            vo.setMonth(month);
            vo.setSalesAmount(monthlySales.getOrDefault(month, BigDecimal.ZERO).setScale(2,  RoundingMode.HALF_UP));
            vo.setBusinessNum(monthlyOpportunityCount.getOrDefault(month, 0L));
            vo.setExpectedSalesAmount(monthlyProbabilitySales.getOrDefault(month, BigDecimal.ZERO).setScale(2,  RoundingMode.HALF_UP));
            monthTotalls.add(vo);
        }
        if (!CollectionUtils.isEmpty(monthTotalls)) {
            monthTotalls = monthTotalls.stream().sorted(Comparator.comparing(BusinessMonthCountVO::getMonth)).collect(Collectors.toList());

        }
        BusinessMonthTotalVO totalVO = new BusinessMonthTotalVO();
        totalVO.setSalesAmountTotal(monthTotalls.stream().map(BusinessMonthCountVO::getSalesAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2,  RoundingMode.HALF_UP));
        totalVO.setBusinessNumTotal(monthTotalls.stream().map(BusinessMonthCountVO::getBusinessNum).reduce(Long::sum).orElse(0L));
        totalVO.setExpectedSalesAmountTotal(monthTotalls.stream().map(BusinessMonthCountVO::getExpectedSalesAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2,  RoundingMode.HALF_UP));
        totalVO.setBusinessMonthCountls(monthTotalls);
        return totalVO;
    }

    @Override
    public IPage<BusinessListVO> listPerformSalesForecastAnalysis(DataAnalysisDTO dto) {

        IPage<BusinessListVO> pageVO = new Page<>(dto.getPageIndex(), dto.getPageSize());
        IPage<BusinessEntity> page = new Page<>(dto.getPageIndex(), dto.getPageSize());
        LambdaQueryWrapper<BusinessEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(BusinessEntity::getExpectedSigningDate);
        wrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);

        wrapper.isNotNull(BusinessEntity::getStage);
        if (StrUtil.isNotBlank(dto.getBlurry())) {
            wrapper.and(w ->w.like(BusinessEntity::getTitle, dto.getBlurry()).or().like(BusinessEntity::getDataCode, dto.getBlurry()));
        }
        wrapper.in(!ObjectUtils.isEmpty(dto.getOwnerByIds()),BusinessEntity::getOwnerBy, dto.getOwnerByIds());
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getBeginCycleTime() +" 00:00:00");
            Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getEndCycleTime()+" 23:59:00");
            wrapper.ge(BusinessEntity::getGetedDate, startDate)
                    .le(BusinessEntity::getGetedDate, endDate);
        } catch (Exception e) {
            log.error("e",e);
        }
        page = businessService.pageWithScope(page, wrapper);
        if (CollectionUtils.isEmpty(page.getRecords())){
            return  pageVO;
        }

        pageVO = SysBaseField.page(page, BusinessListVO.class);
        Set<Long> customerIdList = page.getRecords().stream().filter(e->e.getCustomerId()!=null).map(BusinessEntity::getCustomerId).collect(Collectors.toSet());
        Map<Long, CustomerEntity>  customerMap = customerService.getCustomerMap(customerIdList);

        for (BusinessListVO businessListVO : pageVO.getRecords()){
            if (!ObjectUtils.isEmpty(customerMap.get(businessListVO.getCustomerId()))){
                businessListVO.setCustomerName(customerMap.get(businessListVO.getCustomerId()).getCustomerName());
            }
            BigDecimal estimatedSales = Objects.isNull(businessListVO.getEstimatedSalesAmount()) ? BigDecimal.ZERO : businessListVO.getEstimatedSalesAmount();
            // 假设成交几率为字符串，格式为 "80%"，需要转换为 BigDecimal
            BigDecimal transactionProbability = new BigDecimal(businessListVO.getTransactionProbabilityDictValue()).divide(new BigDecimal(100));
            businessListVO.setTransactionProbabilityAmount(estimatedSales.multiply(transactionProbability));
            businessListVO.setExpectedSalesAmount(estimatedSales.multiply(transactionProbability));
        }

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

    }

    @Override
    public BusinessMonthTotalVO listCountPerformSalesForecastAnalysis(DataAnalysisDTO dto) {

        LambdaQueryWrapper<BusinessEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(dto.getBlurry())) {
            wrapper.and(w ->w.like(BusinessEntity::getTitle, dto.getBlurry()).or().like(BusinessEntity::getDataCode, dto.getBlurry()));
        }
        wrapper.in(!ObjectUtils.isEmpty(dto.getOwnerByIds()),BusinessEntity::getOwnerBy, dto.getOwnerByIds());
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getBeginCycleTime() +" 00:00:00");
            Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getEndCycleTime()+" 23:59:00");
            wrapper.ge(BusinessEntity::getExpectedSigningDate, startDate)
                    .le(BusinessEntity::getExpectedSigningDate, endDate);
        } catch (Exception e) {
            log.error("e",e);
        }
        List<BusinessEntity> businessls = businessService.listWithScope(wrapper);

        BusinessMonthTotalVO vo = new BusinessMonthTotalVO();
        if (CollectionUtils.isEmpty(businessls)){
            return new BusinessMonthTotalVO();
        }

        BusinessMonthTotalVO totalVO = new BusinessMonthTotalVO();

        BigDecimal totalEstimatedSalesAmount = businessls.stream()
                .map(BusinessEntity::getEstimatedSalesAmount) // 提取 estimatedSalesAmount
                .filter(amount -> amount != null) // 过滤掉 null 值
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 计算总和


        BigDecimal totalExpectedClosingAmount = businessls.stream()
                .map(entity -> {
                    BigDecimal estimatedSales = entity.getEstimatedSalesAmount();
                    String transactionProbabilityStr = entity.getTransactionProbabilityDictValue();

                    // 处理成交几率
                    BigDecimal transactionProbability = BigDecimal.ZERO;
                    if (transactionProbabilityStr != null && transactionProbabilityStr.endsWith("%")) {
                        transactionProbability = new BigDecimal(transactionProbabilityStr.replace("%", "")).divide(new BigDecimal(100));
                    }

                    // 计算预计成交金额
                    return estimatedSales != null ? estimatedSales.multiply(transactionProbability) : BigDecimal.ZERO;
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 计算总和

        totalVO.setSalesAmountTotal(totalEstimatedSalesAmount);
        totalVO.setBusinessNumTotal(Long.valueOf(businessls.size()));
        totalVO.setExpectedSalesAmountTotal(totalExpectedClosingAmount);

        return totalVO;
    }

    /**
     * 销售漏斗分析： 漏斗分析
     * @param dto
     */
    @Override
    public BusinessStageTotalVO analyzeSalesFunnel(DataAnalysisDTO dto) {

        LambdaQueryWrapper<BusinessEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BusinessEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.isNotNull(BusinessEntity::getStage);
        wrapper.isNotNull(BusinessEntity::getEstimatedSalesAmount);
        wrapper.isNotNull(BusinessEntity::getExpectedSigningDate);
        wrapper.in(!ObjectUtils.isEmpty(dto.getOwnerByIds()),BusinessEntity::getOwnerBy, dto.getOwnerByIds());
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getBeginCycleTime() +" 00:00:00");
            Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getEndCycleTime()+" 23:59:00");
            wrapper.ge(BusinessEntity::getExpectedSigningDate, startDate)
                    .le(BusinessEntity::getExpectedSigningDate, endDate);
            // expected_signing_date
        }catch (Exception e) {
            log.error("--",e);
        }
        /**
         * 权限范围
         */
        List<BusinessEntity> businessls = businessService.listWithScope(wrapper);
        /**
         * 除流失商机外的其他商机
         */
        Map<String, BigDecimal> monthlySales = businessls.stream().filter(e-> Integer.valueOf(0).equals(e.getHasLoss()))
                .collect(Collectors.groupingBy(
                        entity -> entity.getStage(),
                        Collectors.mapping(
                                entity -> Optional.ofNullable(entity.getEstimatedSalesAmount()).orElse(BigDecimal.ZERO),
                                Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)
                        )
                ));

        BigDecimal lossSalesAmount = businessls.stream().filter(e-> Integer.valueOf(1).equals(e.getHasLoss()))
                .map(BusinessEntity::getEstimatedSalesAmount) // 提取 estimatedSalesAmount
                .filter(amount -> amount != null) // 过滤掉 null 值
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 计算总和

        if (Objects.isNull(monthlySales)) {
            monthlySales = new HashMap<>();
        }
        monthlySales.put("99", lossSalesAmount);
        /**
         * 阶段数量
         */
        Map<String, Long> monthlyOpportunityCount = businessls.stream().filter(e-> Integer.valueOf(0).equals(e.getHasLoss()))
                .collect(Collectors.groupingBy(
                        entity -> entity.getStage(),
                        Collectors.counting()
                ));

        Long lossSalesNum = businessls.stream().filter(e-> Integer.valueOf(1).equals(e.getHasLoss())).count();
        if (Objects.isNull(monthlyOpportunityCount)) {
            monthlyOpportunityCount = new HashMap<>();
        }
        monthlyOpportunityCount.put("99", lossSalesNum);

        Map<String,String> sortedMap = dictDetailService.getDictMapByCode("business_stage");
        sortedMap.put("99","流失商机");

        Map<String, String> stageMap = new TreeMap<>(sortedMap);

        Map<String, BigDecimal> monthlyProbabilitySales = businessls.stream().filter(e-> Integer.valueOf(0).equals(e.getHasLoss()))
                .collect(Collectors.groupingBy(
                        entity -> entity.getStage(),
                        Collectors.mapping(entity -> {
                            BigDecimal estimatedSales = Objects.isNull(entity.getEstimatedSalesAmount()) ? BigDecimal.ZERO : entity.getEstimatedSalesAmount();
                            // 假设成交几率为字符串，格式为 "80%"，需要转换为 BigDecimal
                            BigDecimal transactionProbability = new BigDecimal(entity.getTransactionProbabilityDictValue()).divide(new BigDecimal(100));
                            return estimatedSales.multiply(transactionProbability);
                        }, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))
                ));

        BigDecimal lossExSalesAmount = businessls.stream().filter(e-> Integer.valueOf(1).equals(e.getHasLoss()))
                .collect(Collectors.mapping(entity -> {
                            BigDecimal estimatedSales = Objects.isNull(entity.getEstimatedSalesAmount()) ? BigDecimal.ZERO : entity.getEstimatedSalesAmount();
                            // 假设成交几率为字符串，格式为 "80%"，需要转换为 BigDecimal
                            BigDecimal transactionProbability = new BigDecimal(entity.getTransactionProbabilityDictValue()).divide(new BigDecimal(100));
                            return estimatedSales.multiply(transactionProbability);
                        }, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))
                );

        if (Objects.isNull(monthlyProbabilitySales)) {
            monthlyProbabilitySales = new HashMap<>();
        }
        monthlyProbabilitySales.put("99", lossExSalesAmount.setScale(2, RoundingMode.HALF_UP));

        List<BusinessStageCountVO> monthTotalls = new ArrayList<>();
        Integer totalBusinessNum = businessls.size();
        String previousKey = null;
        for (String key : stageMap.keySet()) {

            BusinessStageCountVO vo = new BusinessStageCountVO();
            vo.setStageName(stageMap.get(key));
            String stageName = stageMap.get(key);
            String stageKey = key;
            if (Objects.isNull(previousKey)) {

            }
            if ("初步洽谈".equals(stageName)) {
                vo.setStageSurnoverRatio(BigDecimal.ZERO);
            } else if ("流失商机".equals(stageName)){
                vo.setStageSurnoverRatio(BigDecimal.ZERO);
            } else {
                Long var1 = businessls.stream()
                        .filter(business -> business.getStage().equals(stageKey)).count();
                Long var2 = businessls.stream()
                        .filter(business -> business.getStage().compareTo(stageKey) >= 0 && !business.getStage().equals("99")).count();
                BigDecimal previousCount = getPreviousKey(stageMap, stageKey, businessls);
                vo.setStageSurnoverRatio(AnalysisUtils.computaPercentage(BigDecimal.valueOf(var1),BigDecimal.valueOf(var2).add(previousCount)));
            }
            vo.setSalesAmount(monthlySales.getOrDefault(key, BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP));
            vo.setBusinessNum(monthlyOpportunityCount.getOrDefault(key, 0L));
            vo.setBusinessNumRatio(AnalysisUtils.computaPercentage(BigDecimal.valueOf(vo.getBusinessNum()), BigDecimal.valueOf(totalBusinessNum)));
            vo.setExpectedSalesAmount(monthlyProbabilitySales.getOrDefault(key, BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP));
            monthTotalls.add(vo);
        }
        BusinessStageTotalVO totalVO = new BusinessStageTotalVO();
        totalVO.setSalesAmountTotal(monthTotalls.stream().map(BusinessStageCountVO::getSalesAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP));
        totalVO.setBusinessNumTotal(totalBusinessNum);
        totalVO.setExpectedSalesAmountTotal(monthTotalls.stream().map(BusinessStageCountVO::getExpectedSalesAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP));
        totalVO.setBusinessStageCountls(monthTotalls);
        return totalVO;
    }

    public static BigDecimal getPreviousKey(Map<String, String> sortedMap, String key,List<BusinessEntity> businessls) {
        String previousKey = "";
        Iterator<Map.Entry<String, String>> iterator = sortedMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            String currentKey = entry.getKey();
            if (currentKey.equals(key) && previousKey != "") {
                String finalPreviousKey = previousKey;
                Long var1 = businessls.stream()
                        .filter(business -> business.getStage().equals(finalPreviousKey)).count();

                return BigDecimal.valueOf(var1);
            }
            previousKey = currentKey;
        }
        return BigDecimal.valueOf(0);
    }


    /**
     *
     * @param dto
     */
    @Override
    public SalesDataGrowTotalVO summarizeNewBusiness(DataAnalysisDTO dto) {
        // 新增的线索
        SalesDataGrowTotalVO totalVO = new SalesDataGrowTotalVO();

        List<SalesDataGrowCountVO> growDatas =  analysisReportMapper.selectBusinessOrderCustomerWhere(dto);
        List<String> months = new ArrayList<>();
        if (Integer.valueOf(30).equals(dto.getSummaryType())) {
            Map<String,SalesDataGrowCountVO> growMap =  growDatas.stream().collect(Collectors.toMap(SalesDataGrowCountVO::getGroupType, CustomerListVO -> CustomerListVO));
            months = AnalysisUtils.generateYearMonthMap(dto.getBeginCycleTime(),dto.getEndCycleTime());
            for (String month : months) {
                SalesDataGrowCountVO vo = growMap.get(month);
                if (Objects.isNull(vo)) {
                    vo = new SalesDataGrowCountVO();
                    vo.setGroupType(month);
                    growDatas.add(vo);
                }
                vo.setGroupTypeName(month);
            }
            growDatas = growDatas.stream().sorted(Comparator.comparing(SalesDataGrowCountVO::getGroupTypeName)).collect(Collectors.toList());
        } else if (Integer.valueOf(50).equals(dto.getSummaryType())) {
            months = AnalysisUtils.generateYearMonthDayMap(dto.getBeginCycleTime(),dto.getEndCycleTime());
            Map<String,SalesDataGrowCountVO> growMap =  growDatas.stream().collect(Collectors.toMap(SalesDataGrowCountVO::getGroupType, CustomerListVO -> CustomerListVO));
            for (String month : months) {
                SalesDataGrowCountVO vo = growMap.get(month);
                if (Objects.isNull(vo)) {
                    vo = new SalesDataGrowCountVO();
                    vo.setGroupType(month);
                    growDatas.add(vo);
                }
                vo.setGroupTypeName(month);
            }
            growDatas = growDatas.stream().sorted(Comparator.comparing(SalesDataGrowCountVO::getGroupTypeName)).collect(Collectors.toList());
        } else {
            for (SalesDataGrowCountVO vo : growDatas) {
                vo.setGroupTypeName(vo.getGroupType());
            }
            growDatas = growDatas.stream().sorted(Comparator.comparing(SalesDataGrowCountVO::getCustomerNum).reversed()).collect(Collectors.toList());
        }
        totalVO.setDatas(growDatas);
        totalVO.setCustomerNumTotal(growDatas.stream().map(SalesDataGrowCountVO::getCustomerNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setClusNumTotal(growDatas.stream().map(SalesDataGrowCountVO::getClusNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setBusinessNumTotal(growDatas.stream().map(SalesDataGrowCountVO::getBusinessNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setOrderFormNumTotal(growDatas.stream().map(SalesDataGrowCountVO::getOrderFormNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        return totalVO;
    }

    @Override
    public void generateBusinessDetailReport(DataAnalysisDTO dto) {

    }

    /**
     * 跟进记录汇总-跟进对象
     * @param dto
     */
    @Override
    public IPage summarizeFollowUpTypeRecords(DataAnalysisDTO dto) {
        IPage<UserFollowUpCountVO> page = new Page<>(dto.getPageIndex(), dto.getPageSize());
        List<UserFollowUpCountVO> userFollowUpCountVOList = analysisReportMapper.countBusFollowUpByResourceType(page,dto);
        page.setRecords(userFollowUpCountVOList);
        return page;
    }

    /**
     * 跟进记录汇总-跟进类型
     * @param dto
     */
    @Override
    public IPage summarizeFollowUpModeRecords(DataAnalysisDTO dto) {
        IPage<UserFollowUpModeCountVO> page = new Page<>(dto.getPageIndex(), dto.getPageSize());
        List<UserFollowUpModeCountVO> userFollowUpCountVOList = analysisReportMapper.countBusFollowUpByFollowType(page,dto);
        page.setRecords(userFollowUpCountVOList);
        return page;
    }

    @Override
    public UserFollowUpCountVO summarizeFollowUpTypeVo(DataAnalysisDTO dto) {
        UserFollowUpCountVO vo = analysisReportMapper.countBusFollowUpByResourceTypeVo(dto);
        return vo;
    }

    /**
     * 跟进记录汇总-跟进类型
     * @param dto
     */
    @Override
    public UserFollowUpModeCountVO summarizeFollowUpModeVo(DataAnalysisDTO dto) {
        UserFollowUpModeCountVO vo = analysisReportMapper.countBusFollowUpByFollowTypeVo(dto);
        return vo;
    }

    @Override
    public List<SalesDataGrowCountVO> countBusinessSummaryTotal(DataAnalysisDTO dto) {
        List<SalesDataGrowCountVO> vos = analysisReportMapper.countBusinessSummaryTotal(dto);
        return vos;
    }

    @Override
    public List<SalesBusinessGrowCountVO>  countBusinessIncreaseTotal(DataAnalysisDTO dto) {
        List<SalesBusinessGrowCountVO> vos = new ArrayList<>();// analysisReportMapper.countBusinessIncreaseTotal(dto);
        return vos;
    }


    @Override
    public List<SalesDataGrowCountVO>  generateComprehensiveBusinessStatistics(DataAnalysisDTO dto) {
        List<SalesDataGrowCountVO> growDatas = analysisReportMapper.countBusinessSummaryTotal(dto);
        List<String> months = new ArrayList<>();
        if (CollectionUtils.isEmpty(growDatas)) {
            growDatas = new ArrayList<>();
        }
        if (Integer.valueOf(30).equals(dto.getSummaryType())) {
            Map<String,SalesDataGrowCountVO> growMap =  growDatas.stream().collect(Collectors.toMap(SalesDataGrowCountVO::getGroupType, CustomerListVO -> CustomerListVO));
            months = AnalysisUtils.generateYearMonthMap(dto.getBeginCycleTime(),dto.getEndCycleTime());
            for (String month : months) {
                SalesDataGrowCountVO vo = growMap.get(month);
                if (Objects.isNull(vo)) {
                    vo = new SalesDataGrowCountVO();
                    vo.setGroupType(month);
                    growDatas.add(vo);
                }
                vo.setGroupTypeName(month);

            }
        } else if (Integer.valueOf(50).equals(dto.getSummaryType())) {
            months = AnalysisUtils.generateYearMonthDayMap(dto.getBeginCycleTime(),dto.getEndCycleTime());
            Map<String,SalesDataGrowCountVO> growMap =  growDatas.stream().collect(Collectors.toMap(SalesDataGrowCountVO::getGroupType, CustomerListVO -> CustomerListVO));
            for (String month : months) {
                SalesDataGrowCountVO vo = growMap.get(month);
                if (Objects.isNull(vo)) {
                    vo = new SalesDataGrowCountVO();
                    vo.setGroupType(month);
                    growDatas.add(vo);
                }
                vo.setGroupTypeName(month);
            }
        } else {
            for (SalesDataGrowCountVO vo : growDatas) {
                vo.setGroupTypeName(vo.getGroupType());
            }
        }
        return growDatas;
    }

    @Override
    public List<SalesBusinessGrowCountVO>  calculateBusinessGrowthStatistics(DataAnalysisDTO dto) {
        List<SalesBusinessGrowCountVO> vos = analysisReportMapper.calculateBusinessGrowthStatistics(dto);
        return vos;
    }

    @Override
    public List<SalesDealRankCountlVO>  selectSalesDealRankTop(DataAnalysisDTO dto) {
        List<SalesDealRankCountlVO> vos = analysisReportMapper.selectSalesDealRankTop(dto);
        return vos;
    }


    @Override
    public List<SalesAreaSpreadCountVO>  selectSalesAreaSpreadSummary(DataAnalysisDTO dto) {
        List<SalesAreaSpreadCountVO> vos = analysisReportMapper.selectSalesAreaSpreadSummary(dto);
        return vos;
    }

    @Override
    public SalesAreaSpreadTotalVO  selectSalesAreaSpreadTotal(DataAnalysisDTO dto) {
        SalesAreaSpreadTotalVO vo = analysisReportMapper.selectSalesAreaSpreadTotal(dto);
        return vo;
    }

}
