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


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.storlead.framework.common.util.ConvertUtils;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.pojo.dto.customer.DataAnalysisDTO;
import com.storlead.sales.pojo.vo.customer.*;
import com.storlead.sales.mapper.customer.RankingsMapper;
import com.storlead.sales.service.customer.BusinessService;
import com.storlead.sales.service.customer.CustomerService;
import com.storlead.sales.service.customer.OrderFormService;
import com.storlead.sales.service.customer.RankingsService;
import com.storlead.sales.util.report.AnalysisUtils;
import com.storlead.system.enums.OrganizationalTypeEnum;
import com.storlead.system.service.IUserRoleService;
import com.storlead.user.mapper.UserMapper;
import com.storlead.user.pojo.entity.UserEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class RankingsServiceImpl extends MyBaseServiceImpl<UserMapper, UserEntity> implements RankingsService {

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private RankingsMapper rankingsMapper;

    @Override
    public ClosedBusinessListVO selectClosedList(DataAnalysisDTO dto) {
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
        if (!CollectionUtils.isEmpty(dto.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                dto.setOwnerByIds(ConvertUtils.retainByIds(dto.getOwnerByIds(),dataScope));
            }
        } else {
            dto.setOwnerByIds(List.copyOf(dataScope));
        }
        ClosedBusinessListVO totalvo = new ClosedBusinessListVO();
        List<ClosedBusinessMonthCountVO> monthDatas = rankingsMapper.selectClosedBusinessByMonth(dto);
        // 填充月份数据
        List<String> months = new ArrayList<>();
        Map<String,ClosedBusinessMonthCountVO> growMap =  monthDatas.stream().collect(Collectors.toMap(ClosedBusinessMonthCountVO::getGroupType, CustomerListVO -> CustomerListVO));
        months = AnalysisUtils.generateYearMonthMap(dto.getBeginCycleTime(),dto.getEndCycleTime());
        for (String month : months) {
            ClosedBusinessMonthCountVO vo = growMap.get(month);
            if (Objects.isNull(vo)) {
                vo = new ClosedBusinessMonthCountVO();
                vo.setGroupType(month);
                monthDatas.add(vo);
            }
            vo.setGroupTypeName(month);
        }
        // 按月份降序排序
        monthDatas = monthDatas.stream().sorted(Comparator.comparing(ClosedBusinessMonthCountVO::getGroupType)).collect(Collectors.toList());
        if (monthDatas != null && monthDatas.size() > 0) {
            // 处理第一个月的数据
            ClosedBusinessMonthCountVO firstMonth = monthDatas.get(0);
            BigDecimal avgBusinessAmountFirstMonth = BigDecimal.ZERO;
            if (firstMonth.getBusinessNum() != 0) {
                avgBusinessAmountFirstMonth = firstMonth.getBusinessAmount().divide(new BigDecimal(firstMonth.getBusinessNum()), 2, BigDecimal.ROUND_HALF_UP);
            }
            firstMonth.setAvgBusinessAmount(avgBusinessAmountFirstMonth);

            // 如果有多于一个月的数据，计算环比增长率
            if (monthDatas.size() > 1) {
                firstMonth.setBusinessCountRate(0.0);
                firstMonth.setBusinessAmountRate(0.0);

                for (int i = 1; i < monthDatas.size(); i++) {
                    ClosedBusinessMonthCountVO currentMonth = monthDatas.get(i);
                    ClosedBusinessMonthCountVO previousMonth = monthDatas.get(i - 1);

                    // 计算商机数量环比增长率
                    double businessCountRate = 0.0;
                    Long previousBusinessNum = previousMonth.getBusinessNum();
                    Long currentBusinessNum = currentMonth.getBusinessNum();

                    if (previousBusinessNum == 0 && currentBusinessNum != 0) {
                        businessCountRate = 100.0;
                    } else if (currentBusinessNum == 0 && previousBusinessNum != 0) {
                        businessCountRate = -100.0;
                    } else if (currentBusinessNum == 0 && previousBusinessNum == 0){
                        businessCountRate = 0.0;
                    } else {
                        businessCountRate = ((double) (currentBusinessNum - previousBusinessNum) / previousBusinessNum) * 100;
                        businessCountRate = new BigDecimal(businessCountRate).setScale(2, RoundingMode.HALF_UP).doubleValue();
                    }
                    currentMonth.setBusinessCountRate(businessCountRate);

                    // 计算商机金额环比增长率
                    double businessAmountRate = 0.0;
                    BigDecimal previousMonthAmount = previousMonth.getBusinessAmount();
                    BigDecimal currentMonthAmount = currentMonth.getBusinessAmount();

                    if (currentMonthAmount.compareTo(BigDecimal.ZERO) != 0 && previousMonthAmount.compareTo(BigDecimal.ZERO) == 0) {
                        businessAmountRate = 100.0;
                    } else if ( previousMonthAmount.compareTo(BigDecimal.ZERO) != 0 && currentMonthAmount.compareTo(BigDecimal.ZERO) == 0) {
                        businessAmountRate = -100.0;
                    } else if(currentMonthAmount.compareTo(BigDecimal.ZERO) == 0 && previousMonthAmount.compareTo(BigDecimal.ZERO) == 0){
                        businessAmountRate = 0.0;
                    }else {
                        businessAmountRate = (currentMonthAmount.subtract(previousMonthAmount)
                                           .divide(previousMonthAmount, 4, BigDecimal.ROUND_HALF_UP)
                                           .multiply(new BigDecimal("100"))
                                           .setScale(2, BigDecimal.ROUND_HALF_UP))
                                           .doubleValue();

                    }
                    currentMonth.setBusinessAmountRate(businessAmountRate);

                    // 计算平均客单价
                    BigDecimal avgBusinessAmount = BigDecimal.ZERO;
                    if (currentMonth.getBusinessNum() != 0) {
                        avgBusinessAmount = currentMonth.getBusinessAmount().divide(new BigDecimal(currentMonth.getBusinessNum()), 2, BigDecimal.ROUND_HALF_UP);
                    }
                    currentMonth.setAvgBusinessAmount(avgBusinessAmount);
                }
            }
        }

        totalvo.setBusinessMonthCountls(monthDatas);
        totalvo.setSalesAmountTotal(monthDatas.stream().map(ClosedBusinessMonthCountVO::getBusinessAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalvo.setBusinessNumTotal(monthDatas.stream().map(ClosedBusinessMonthCountVO::getBusinessNum).reduce(0L, Long::sum));
        return totalvo;
    }

    @Override
    public CloseBusinessAllListsVO selectClosedBusinessList(DataAnalysisDTO dto) {
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
        if (!CollectionUtils.isEmpty(dto.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                dto.setOwnerByIds(ConvertUtils.retainByIds(dto.getOwnerByIds(),dataScope));
            }
        } else {
            dto.setOwnerByIds(List.copyOf(dataScope));
        }
        CloseBusinessAllListsVO totalvo = new CloseBusinessAllListsVO();
        List<CloseBusinessAllListVO> growDatas = rankingsMapper.selectCloseBusinessAllList(dto);
        totalvo.setCloseBusinessAllList(growDatas);
        totalvo.setTotalCount(growDatas.size());
        SysBaseField.dictFileds(growDatas);
        return totalvo;
    }

    @Override
    public QuotationSalesTotalVO productSalesTotal(DataAnalysisDTO dto) {
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
        if (!CollectionUtils.isEmpty(dto.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                dto.setOwnerByIds(ConvertUtils.retainByIds(dto.getOwnerByIds(),dataScope));
            }
        } else {
            dto.setOwnerByIds(List.copyOf(dataScope));
        }
        QuotationSalesTotalVO totalVO = new QuotationSalesTotalVO();
        List<QuotationSalesListVO> growDatas = rankingsMapper.selectQuotationByTotalNumber(dto);
        totalVO.setDatas(growDatas);
        totalVO.setTotalAmount(growDatas.stream().map(QuotationSalesListVO::getSalesAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setTotalNum(growDatas.stream().map(QuotationSalesListVO::getSalesNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        return totalVO;
    }

    @Override
    public QuotationTimeTotalVO productSalesTotalByMonth(DataAnalysisDTO dto) {
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
        if (!CollectionUtils.isEmpty(dto.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                dto.setOwnerByIds(ConvertUtils.retainByIds(dto.getOwnerByIds(),dataScope));
            }
        } else {
            dto.setOwnerByIds(List.copyOf(dataScope));
        }
        QuotationTimeTotalVO totalVO = new QuotationTimeTotalVO();
        List<QuotationTimeListVO> growDatas = rankingsMapper.selectQuotationByTime(dto);
        // 填充月份数据
        List<String> months = new ArrayList<>();
        Map<String,QuotationTimeListVO> growMap =  growDatas.stream().collect(Collectors.toMap(QuotationTimeListVO::getMonth, CustomerListVO -> CustomerListVO));
        months = AnalysisUtils.generateYearMonthMap(dto.getBeginCycleTime(),dto.getEndCycleTime());
        for (String month : months) {
            QuotationTimeListVO vo = growMap.get(month);
            if (Objects.isNull(vo)) {
                vo = new QuotationTimeListVO();
                vo.setMonth(month);
                growDatas.add(vo);
            }
            vo.setMonth(month);
        }
        // 按月份降序排序
        growDatas = growDatas.stream().sorted(Comparator.comparing(QuotationTimeListVO::getMonth)).collect(Collectors.toList());
        for (int i = 0; i < growDatas.size(); i++) {
            QuotationTimeListVO currentMonthData = growDatas.get(i);
            BigDecimal currentMonthSalesAmount = currentMonthData.getSalesAmount();
            BigDecimal lastMonthSalesAmount = BigDecimal.ZERO;

            if (i > 0) {
                QuotationTimeListVO lastMonthData = growDatas.get(i - 1);
                lastMonthSalesAmount = lastMonthData.getSalesAmount();
            }

            double increaseRate;
            if (lastMonthSalesAmount.compareTo(BigDecimal.ZERO) == 0 && currentMonthSalesAmount.compareTo(BigDecimal.ZERO) != 0) {
                increaseRate = 100.0;
            } else if (currentMonthSalesAmount.compareTo(BigDecimal.ZERO) == 0 && lastMonthSalesAmount.compareTo(BigDecimal.ZERO) != 0) {
                increaseRate = -100.0;
            } else if(currentMonthData.getSalesAmount().compareTo(BigDecimal.ZERO) == 0 && lastMonthSalesAmount.compareTo(BigDecimal.ZERO) == 0){
                increaseRate = 0.0;
            } else {
                increaseRate = currentMonthSalesAmount.subtract(lastMonthSalesAmount)
                        .divide(lastMonthSalesAmount, 4, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal(100))
                        .doubleValue();
            }
            currentMonthData.setIncreaseRate(increaseRate);
        }
        totalVO.setDatas(growDatas);
        totalVO.setTotalAmount(growDatas.stream().map(QuotationTimeListVO::getSalesAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setTotalNum(growDatas.stream().map(QuotationTimeListVO::getSalesNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        return totalVO;
    }

    @Override
    public SalesDataAddTotalVO businessRankings(DataAnalysisDTO dto) {
//        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.USER_GROUP);
//        if (!CollectionUtils.isEmpty(dto.getOwnerByIds())) {
//            if (!CollectionUtils.isEmpty(dataScope)) {
//                dto.getOwnerByIds().retainAll(dataScope);
//            }
//        } else {
//            dto.setOwnerByIds(List.copyOf(dataScope));
//        }
        SalesDataAddTotalVO totalVO = new SalesDataAddTotalVO();
        List<SalesDataAddCountVO> growDatas =  rankingsMapper.selectBusinessOrderCustomer(dto);

        totalVO.setDatas(growDatas);
        totalVO.setCustomerNumTotal(growDatas.stream().map(SalesDataAddCountVO::getCustomerNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setClusNumTotal(growDatas.stream().map(SalesDataAddCountVO::getClusNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setBusinessNumTotal(growDatas.stream().map(SalesDataAddCountVO::getBusinessNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setOrderFormNumTotal(growDatas.stream().map(SalesDataAddCountVO::getOrderFormNum).reduce(BigDecimal.ZERO, BigDecimal::add));

        return totalVO;
    }

    @Override
    public TransactionDataAllVo rankingTransactionData(DataAnalysisDTO dto) {

        TransactionDataAllVo totalVO = new TransactionDataAllVo();
        List<TransactionDataVo> growDatas = rankingsMapper.selectOrderProduct(dto);

        totalVO.setDatas(growDatas);
        totalVO.setDealTotal(growDatas.stream().map(TransactionDataVo::getDealAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setOrderNumTotal(growDatas.stream().map(TransactionDataVo::getDealOrder).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setProductNumTotal(growDatas.stream().map(TransactionDataVo::getDealProductNum).reduce(BigDecimal.ZERO, BigDecimal::add));

        // 计算总的平均客单价
        BigDecimal dealTotal = totalVO.getDealTotal();
        BigDecimal orderNumTotal = totalVO.getOrderNumTotal();
        BigDecimal avgPrice = orderNumTotal.compareTo(BigDecimal.ZERO) != 0 ? dealTotal.divide(orderNumTotal, 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
        totalVO.setAvgPrice(avgPrice);

        return totalVO;

    }

    @Override
    public ConversionRateTotalVo rankingConversionRate(DataAnalysisDTO dto) {

        ConversionRateTotalVo totalVO = new ConversionRateTotalVo();
        // 初始化 growDatas 为一个空列表
        List<ConversionRateListVo> growDatas = Collections.emptyList();

        if (dto.getTargetType() == 11) {
            // 线索转化率
            growDatas = rankingsMapper.selectClueConversionRate(dto);
        } else if (dto.getTargetType() == 12) {
            // 客户转化率
            growDatas = rankingsMapper.selectCustomerConversionRate(dto);
        } else if (dto.getTargetType() == 30) {
            // 商机成交率
            growDatas = rankingsMapper.selectBusinessConversionRate(dto);
        } else if (dto.getTargetType() == 31) {
            // 商机流失率
            growDatas = rankingsMapper.selectBusinessLossRate(dto);
        }

        // 过滤掉 newNum 和 convertedNum 都为 0 的数据
        List<ConversionRateListVo> filteredGrowDatas = growDatas.stream()
                .filter(data -> data.getNewNum().compareTo(BigDecimal.ZERO) != 0 || data.getConvertedNum().compareTo(BigDecimal.ZERO) != 0)
                .collect(Collectors.toList());

        // 设置总数据和总计数
        totalVO.setDatas(filteredGrowDatas);
        totalVO.setTotalNewNum(filteredGrowDatas.stream().map(ConversionRateListVo::getNewNum).reduce(BigDecimal.ZERO, BigDecimal::add));
        totalVO.setTotalconvertedNum(filteredGrowDatas.stream().map(ConversionRateListVo::getConvertedNum).reduce(BigDecimal.ZERO, BigDecimal::add));

        BigDecimal totalNewNum = totalVO.getTotalNewNum();
        BigDecimal totalConvertedNum = totalVO.getTotalconvertedNum();

        if (totalNewNum.compareTo(BigDecimal.ZERO) != 0) {
            // 使用BigDecimal进行完整计算并格式化结果到2位小数
            BigDecimal rate = totalNewNum
                .divide(totalConvertedNum, 4, RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100))
                .setScale(2, RoundingMode.HALF_UP);
            totalVO.setTotalConversionRate(rate.doubleValue());
        } else {
            totalVO.setTotalConversionRate(0.00);
        }

        return totalVO;
    }

    @Override
    public UserFollowUpModeTotalVO rankingFollowUpData(DataAnalysisDTO dto) {

        UserFollowUpModeTotalVO totalVO = new UserFollowUpModeTotalVO();
        List<UserFollowUpModeCountVO> growDatas = rankingsMapper.selectFollowRecord(dto);

        totalVO.setDatas(growDatas);

        return totalVO;
    }

}
