package com.dora.service.impl;

import com.dora.dto.WithdrawDto;
import com.dora.entity.ContentRevenueStage;
import com.dora.entity.Workflow;
import com.dora.entity.Video;
import com.dora.mapper.ContentRevenueStageMapper;
import com.dora.mapper.FanPromotionCommissionMapper;
import com.dora.mapper.RevenueConfigMapper;
import com.dora.mapper.UserMapper;
import com.dora.mapper.WorkflowMapper;
import com.dora.mapper.VideoMapper;
import com.dora.mapper.WithdrawRequestMapper;
import com.dora.mapper.WorkflowCopyStatMapper;
import com.dora.mapper.VideoViewStatMapper;
import com.dora.service.WithdrawService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 提现服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WithdrawServiceImpl implements WithdrawService {

    private final WithdrawRequestMapper withdrawRequestMapper;
    private final ContentRevenueStageMapper contentRevenueStageMapper;
    private final FanPromotionCommissionMapper fanPromotionCommissionMapper;
    private final RevenueConfigMapper revenueConfigMapper;
    private final UserMapper userMapper;
    private final WorkflowMapper workflowMapper;
    private final VideoMapper videoMapper;
    private final WorkflowCopyStatMapper workflowCopyStatMapper;
    private final VideoViewStatMapper videoViewStatMapper;

    @Override
    public WithdrawDto.WithdrawResponse submitWithdrawRequest(Long userId, WithdrawDto.WithdrawRequest request) {
        // 1. 验证提现类型和作品ID
        validateWithdrawTypeAndContentId(request);
        
        // 2. 根据提现类型验证提现条件
        if (!validateWithdrawConditionByType(userId, request)) {
            throw new RuntimeException("不满足提现条件");
        }

        // 3. 验证银行卡信息
        if ("bank".equals(request.getAccountType()) && !StringUtils.hasText(request.getBankName())) {
            throw new RuntimeException("银行卡提现必须提供开户行名称");
        }

        // 4. 创建提现申请
        com.dora.entity.WithdrawRequest withdrawRequest = new com.dora.entity.WithdrawRequest();
        withdrawRequest.setUserId(userId);
        withdrawRequest.setAmount(request.getAmount());
        withdrawRequest.setWithdrawType("balance"); // 统一使用balance类型
        withdrawRequest.setContentId(null); // 余额提现不需要作品ID
        withdrawRequest.setAccountType(request.getAccountType());
        withdrawRequest.setAccount(request.getAccount());
        withdrawRequest.setAccountName(request.getAccountName());
        withdrawRequest.setBankName(request.getBankName());
        withdrawRequest.setBankBranch(request.getBankBranch());
        withdrawRequest.setStatus(0); // 待审核
        withdrawRequest.setCreateTime(LocalDateTime.now());
        withdrawRequest.setUpdateTime(LocalDateTime.now());
        withdrawRequest.setIsDeleted(0);

        // 5. 保存到数据库
        withdrawRequestMapper.insert(withdrawRequest);

        // 6. 返回响应
        return convertToResponse(withdrawRequest);
    }

    @Override
    public WithdrawDto.WithdrawListResponse getWithdrawList(Long userId, int page, int size) {
        int offset = (page - 1) * size;
        
        // 查询提现记录
        List<com.dora.entity.WithdrawRequest> records = withdrawRequestMapper.selectByUserId(userId, offset, size);
        Long total = withdrawRequestMapper.countByUserId(userId);

        // 转换为响应对象
        List<WithdrawDto.WithdrawResponse> responses = records.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        WithdrawDto.WithdrawListResponse response = new WithdrawDto.WithdrawListResponse();
        response.setRecords(responses);
        response.setTotal(total);
        response.setPage(page);
        response.setSize(size);

        return response;
    }

    @Override
    public WithdrawDto.UserRevenueResponse getUserRevenueInfo(Long userId) {
        // 1. 获取推广收益
        BigDecimal promotionRevenue = fanPromotionCommissionMapper.sumSettledCommissionByPromoterId(userId);
        
        // 2. 获取待审核金额
        BigDecimal pendingAmount = withdrawRequestMapper.sumPendingAmountByUserId(userId);
        
        // 3. 获取已提现金额
        BigDecimal withdrawnAmount = contentRevenueStageMapper.sumWithdrawnAmount(userId);
        
        // 4. 获取未提现金额
        BigDecimal unwithdrawnAmount = contentRevenueStageMapper.sumUnwithdrawnAmount(userId);
        
        // 5. 计算总收益和可提现金额
        BigDecimal totalRevenue = promotionRevenue.add(unwithdrawnAmount).add(withdrawnAmount);
        BigDecimal availableAmount = unwithdrawnAmount;
        
        // 6. 获取用户推广等级信息
        Integer promotionLevel = userMapper.selectById(userId).getPromotionLevel();
        
        // 7. 获取推广等级配置
        var promotionConfig = revenueConfigMapper.selectByConfigTypeAndLevel("promotion", promotionLevel);
        String promotionLevelName = promotionConfig != null ? promotionConfig.getLevelName() : "普通用户";
        BigDecimal promotionRate = promotionConfig != null ? promotionConfig.getCommissionRate() : BigDecimal.ZERO;
        
        // 8. 计算距离下一等级需要的粉丝数
        var nextLevelConfig = revenueConfigMapper.selectNextLevelConfig("promotion", promotionLevel);
        Integer fansToNextLevel = nextLevelConfig != null ? 
            nextLevelConfig.getMinFans() - userMapper.countPaidFansByInviterId(userId) : 0;
        
        // 9. 获取工作流收益详情列表
        List<WithdrawDto.WorkflowRevenueDetail> workflowDetails = getWorkflowRevenueDetails(userId);
        
        // 10. 获取视频收益详情列表
        List<WithdrawDto.VideoRevenueDetail> videoDetails = getVideoRevenueDetails(userId);
        
        // 11. 构建响应
        WithdrawDto.UserRevenueResponse response = new WithdrawDto.UserRevenueResponse();
        response.setTotalRevenue(totalRevenue);
        response.setAvailableAmount(availableAmount);
        response.setWithdrawnAmount(withdrawnAmount);
        response.setPendingAmount(pendingAmount);
        response.setPromotionRevenue(promotionRevenue);
        response.setPromotionLevel(promotionLevel);
        response.setPromotionLevelName(promotionLevelName);
        response.setPromotionRate(promotionRate);
        response.setFansToNextLevel(fansToNextLevel);
        response.setWorkflowDetails(workflowDetails);
        response.setVideoDetails(videoDetails);
        
        return response;
    }

    @Override
    public boolean validateWithdrawCondition(Long userId, BigDecimal amount) {
        // 1. 检查推广收益是否达到100元
        BigDecimal promotionRevenue = fanPromotionCommissionMapper.sumSettledCommissionByPromoterId(userId);
        if (promotionRevenue.compareTo(new BigDecimal("100")) < 0) {
            return false;
        }
        
        // 2. 检查可提现金额是否足够
        BigDecimal availableAmount = contentRevenueStageMapper.sumUnwithdrawnAmount(userId);
        if (availableAmount.compareTo(amount) < 0) {
            return false;
        }
        
        return true;
    }

    /**
     * 验证提现类型和作品ID
     */
    private void validateWithdrawTypeAndContentId(WithdrawDto.WithdrawRequest request) {
        // 现在统一使用余额提现，不需要验证提现类型和作品ID
        // 保留方法以兼容现有代码结构
    }

    /**
     * 根据提现类型验证提现条件
     */
    private boolean validateWithdrawConditionByType(Long userId, WithdrawDto.WithdrawRequest request) {
        // 现在统一使用余额提现，只需要验证余额是否足够
        return validateWithdrawCondition(userId, request.getAmount());
    }

    /**
     * 验证推广提现条件
     */
    private boolean validatePromotionWithdrawCondition(Long userId, BigDecimal amount) {
        // 1. 检查推广收益是否达到100元
        BigDecimal promotionRevenue = fanPromotionCommissionMapper.sumSettledCommissionByPromoterId(userId);
        if (promotionRevenue.compareTo(new BigDecimal("100")) < 0) {
            return false;
        }
        
        // 2. 检查可提现金额是否足够
        if (promotionRevenue.compareTo(amount) < 0) {
            return false;
        }
        
        return true;
    }

    /**
     * 验证工作流提现条件
     */
    private boolean validateWorkflowWithdrawCondition(Long userId, Long workflowId, BigDecimal amount) {
        // 1. 检查工作流是否存在且属于该用户
        Workflow workflow = workflowMapper.selectById(workflowId);
        if (workflow == null || !workflow.getOwnerId().equals(userId)) {
            return false;
        }
        
        // 2. 检查工作流未提现收益是否足够
        BigDecimal unwithdrawnAmount = contentRevenueStageMapper.sumUnwithdrawnAmountByContentId(userId, 1, workflowId);
        if (unwithdrawnAmount.compareTo(amount) < 0) {
            return false;
        }
        
        return true;
    }

    /**
     * 验证视频提现条件
     */
    private boolean validateVideoWithdrawCondition(Long userId, Long videoId, BigDecimal amount) {
        // 1. 检查视频是否存在且属于该用户
        Video video = videoMapper.selectById(videoId);
        if (video == null || !video.getOwnerId().equals(userId)) {
            return false;
        }
        
        // 2. 检查视频未提现收益是否足够
        BigDecimal unwithdrawnAmount = contentRevenueStageMapper.sumUnwithdrawnAmountByContentId(userId, 2, videoId);
        if (unwithdrawnAmount.compareTo(amount) < 0) {
            return false;
        }
        
        return true;
    }

    /**
     * 获取工作流收益详情列表
     */
    private List<WithdrawDto.WorkflowRevenueDetail> getWorkflowRevenueDetails(Long userId) {
        // 获取用户的工作流收益阶段
        List<ContentRevenueStage> workflowStages = contentRevenueStageMapper.selectByUserIdAndType(userId, 1);
        
        if (workflowStages.isEmpty()) {
            return List.of();
        }
        
        // 按工作流ID分组
        Map<Long, List<ContentRevenueStage>> stagesByWorkflow = workflowStages.stream()
                .collect(Collectors.groupingBy(ContentRevenueStage::getContentId));
        
        // 获取工作流信息
        List<Long> workflowIds = stagesByWorkflow.keySet().stream().collect(Collectors.toList());
        List<Workflow> workflows = workflowMapper.selectByIds(workflowIds);
        Map<Long, Workflow> workflowMap = workflows.stream()
                .collect(Collectors.toMap(Workflow::getId, w -> w));
        
        // 获取每个工作流的复制次数
        Map<Long, Integer> copyCounts = workflowIds.stream()
                .collect(Collectors.toMap(
                    id -> id,
                    id -> workflowCopyStatMapper.countCopiesByWorkflowId(id),
                    (existing, replacement) -> existing
                ));
        
        return stagesByWorkflow.entrySet().stream()
                .map(entry -> {
                    Long workflowId = entry.getKey();
                    List<ContentRevenueStage> stages = entry.getValue();
                    
                    Workflow workflow = workflowMap.get(workflowId);
                    if (workflow == null) {
                        return null;
                    }
                    
                    Integer currentCopies = copyCounts.get(workflowId);
                    BigDecimal totalRevenue = stages.stream()
                            .filter(stage -> stage.getIsAchieved() == 1)
                            .map(ContentRevenueStage::getRewardAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    // 转换为收益阶段DTO
                    List<WithdrawDto.RevenueStage> revenueStages = stages.stream()
                            .map(this::convertToRevenueStage)
                            .collect(Collectors.toList());
                    
                    WithdrawDto.WorkflowRevenueDetail detail = new WithdrawDto.WorkflowRevenueDetail();
                    detail.setWorkflowId(workflowId);
                    detail.setWorkflowName(workflow.getName());
                    detail.setWorkflowDescription(workflow.getDescription());
                    detail.setWorkflowCoverUrl(workflow.getCoverUrl());
                    detail.setTotalRevenue(totalRevenue);
                    detail.setCurrentCopies(currentCopies);
                    detail.setStages(revenueStages);
                    
                    return detail;
                })
                .filter(detail -> detail != null)
                .collect(Collectors.toList());
    }

    /**
     * 获取视频收益详情列表
     */
    private List<WithdrawDto.VideoRevenueDetail> getVideoRevenueDetails(Long userId) {
        // 获取用户的视频收益阶段
        List<ContentRevenueStage> videoStages = contentRevenueStageMapper.selectByUserIdAndType(userId, 2);
        
        if (videoStages.isEmpty()) {
            return List.of();
        }
        
        // 按视频ID分组
        Map<Long, List<ContentRevenueStage>> stagesByVideo = videoStages.stream()
                .collect(Collectors.groupingBy(ContentRevenueStage::getContentId));
        
        // 获取视频信息
        List<Long> videoIds = stagesByVideo.keySet().stream().collect(Collectors.toList());
        List<Video> videos = videoMapper.selectByIds(videoIds);
        Map<Long, Video> videoMap = videos.stream()
                .collect(Collectors.toMap(Video::getId, v -> v));
        
        // 获取每个视频的观看次数
        Map<Long, Integer> viewCounts = videoIds.stream()
                .collect(Collectors.toMap(
                    id -> id,
                    id -> videoViewStatMapper.countViewsByVideoId(id),
                    (existing, replacement) -> existing
                ));
        
        return stagesByVideo.entrySet().stream()
                .map(entry -> {
                    Long videoId = entry.getKey();
                    List<ContentRevenueStage> stages = entry.getValue();
                    
                    Video video = videoMap.get(videoId);
                    if (video == null) {
                        return null;
                    }
                    
                    Integer currentViews = viewCounts.get(videoId);
                    BigDecimal totalRevenue = stages.stream()
                            .filter(stage -> stage.getIsAchieved() == 1)
                            .map(ContentRevenueStage::getRewardAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    // 转换为收益阶段DTO
                    List<WithdrawDto.RevenueStage> revenueStages = stages.stream()
                            .map(this::convertToRevenueStage)
                            .collect(Collectors.toList());
                    
                    WithdrawDto.VideoRevenueDetail detail = new WithdrawDto.VideoRevenueDetail();
                    detail.setVideoId(videoId);
                    detail.setVideoTitle(video.getTitle());
                    detail.setVideoDescription(video.getDescription());
                    detail.setVideoCoverUrl(video.getCoverUrl());
                    detail.setTotalRevenue(totalRevenue);
                    detail.setCurrentViews(currentViews);
                    detail.setStages(revenueStages);
                    
                    return detail;
                })
                .filter(detail -> detail != null)
                .collect(Collectors.toList());
    }

    /**
     * 转换为收益阶段DTO
     */
    private WithdrawDto.RevenueStage convertToRevenueStage(ContentRevenueStage stage) {
        WithdrawDto.RevenueStage revenueStage = new WithdrawDto.RevenueStage();
        revenueStage.setStageId(stage.getId());
        revenueStage.setStageLevel(stage.getStageLevel());
        revenueStage.setStageName(stage.getStageName());
        revenueStage.setTargetCount(stage.getTargetCount());
        revenueStage.setRewardAmount(stage.getRewardAmount());
        revenueStage.setCurrentCount(stage.getCurrentCount());
        revenueStage.setIsAchieved(stage.getIsAchieved() == 1);
        revenueStage.setAchievedAt(stage.getAchievedAt());
        revenueStage.setIsWithdrawn(stage.getIsWithdrawn() == 1);
        revenueStage.setWithdrawnAt(stage.getWithdrawnAt());
        revenueStage.setRemainingCount(Math.max(0, stage.getTargetCount() - stage.getCurrentCount()));
        
        return revenueStage;
    }

    /**
     * 转换为响应对象
     */
    private WithdrawDto.WithdrawResponse convertToResponse(com.dora.entity.WithdrawRequest withdrawRequest) {
        WithdrawDto.WithdrawResponse response = new WithdrawDto.WithdrawResponse();
        response.setId(withdrawRequest.getId());
        response.setAmount(withdrawRequest.getAmount());
        response.setAccountType(withdrawRequest.getAccountType());
        response.setAccount(withdrawRequest.getAccount());
        response.setAccountName(withdrawRequest.getAccountName());
        response.setBankName(withdrawRequest.getBankName());
        response.setBankBranch(withdrawRequest.getBankBranch());
        response.setStatus(withdrawRequest.getStatus());
        response.setReason(withdrawRequest.getReason());
        response.setTransactionNo(withdrawRequest.getTransactionNo());
        response.setFeeAmount(withdrawRequest.getFeeAmount());
        response.setActualAmount(withdrawRequest.getActualAmount());
        response.setProcessedAt(withdrawRequest.getProcessedAt());
        response.setCreateTime(withdrawRequest.getCreateTime());
        response.setReviewedAt(withdrawRequest.getReviewedAt());
        return response;
    }

    @Override
    public WithdrawDto.BasicRevenueResponse getBasicRevenueInfo(Long userId) {
        // 1. 获取推广收益
        BigDecimal promotionRevenue = fanPromotionCommissionMapper.sumSettledCommissionByPromoterId(userId);
        
        // 2. 获取待审核金额
        BigDecimal pendingAmount = withdrawRequestMapper.sumPendingAmountByUserId(userId);
        
        // 3. 获取已提现金额
        BigDecimal withdrawnAmount = contentRevenueStageMapper.sumWithdrawnAmount(userId);
        
        // 4. 获取未提现金额
        BigDecimal unwithdrawnAmount = contentRevenueStageMapper.sumUnwithdrawnAmount(userId);
        
        // 5. 计算总收益和可提现金额
        BigDecimal totalRevenue = promotionRevenue.add(unwithdrawnAmount).add(withdrawnAmount);
        BigDecimal availableAmount = unwithdrawnAmount;
        
        // 6. 获取用户推广等级信息
        Integer promotionLevel = userMapper.selectById(userId).getPromotionLevel();
        
        // 7. 获取推广等级配置
        var promotionConfig = revenueConfigMapper.selectByConfigTypeAndLevel("promotion", promotionLevel);
        String promotionLevelName = promotionConfig != null ? promotionConfig.getLevelName() : "普通用户";
        BigDecimal promotionRate = promotionConfig != null ? promotionConfig.getCommissionRate() : BigDecimal.ZERO;
        
        // 8. 计算距离下一等级需要的粉丝数
        var nextLevelConfig = revenueConfigMapper.selectNextLevelConfig("promotion", promotionLevel);
        Integer fansToNextLevel = nextLevelConfig != null ? 
            nextLevelConfig.getMinFans() - userMapper.countPaidFansByInviterId(userId) : 0;
        
        // 9. 构建响应
        WithdrawDto.BasicRevenueResponse response = new WithdrawDto.BasicRevenueResponse();
        response.setTotalRevenue(totalRevenue);
        response.setAvailableAmount(availableAmount);
        response.setWithdrawnAmount(withdrawnAmount);
        response.setPendingAmount(pendingAmount);
        response.setPromotionRevenue(promotionRevenue);
        response.setPromotionLevel(promotionLevel);
        response.setPromotionLevelName(promotionLevelName);
        response.setPromotionRate(promotionRate);
        response.setFansToNextLevel(fansToNextLevel);
        
        return response;
    }

    @Override
    public WithdrawDto.WorkflowRevenueListResponse getWorkflowRevenueDetails(Long userId, int page, int size) {
        int offset = (page - 1) * size;
        
        // 获取用户的工作流收益阶段（分页）
        List<ContentRevenueStage> workflowStages = contentRevenueStageMapper.selectByUserIdAndTypeWithPagination(userId, 1, offset, size);
        Long total = contentRevenueStageMapper.countByUserIdAndType(userId, 1);
        
        if (workflowStages.isEmpty()) {
            WithdrawDto.WorkflowRevenueListResponse response = new WithdrawDto.WorkflowRevenueListResponse();
            response.setRecords(List.of());
            response.setTotal(0L);
            response.setPage(page);
            response.setSize(size);
            return response;
        }
        
        // 按工作流ID分组
        Map<Long, List<ContentRevenueStage>> stagesByWorkflow = workflowStages.stream()
                .collect(Collectors.groupingBy(ContentRevenueStage::getContentId));
        
        // 获取工作流信息
        List<Long> workflowIds = stagesByWorkflow.keySet().stream().collect(Collectors.toList());
        List<Workflow> workflows = workflowMapper.selectByIds(workflowIds);
        Map<Long, Workflow> workflowMap = workflows.stream()
                .collect(Collectors.toMap(Workflow::getId, w -> w));
        
        // 获取每个工作流的复制次数
        Map<Long, Integer> copyCounts = workflowIds.stream()
                .collect(Collectors.toMap(
                    id -> id,
                    id -> workflowCopyStatMapper.countCopiesByWorkflowId(id),
                    (existing, replacement) -> existing
                ));
        
        List<WithdrawDto.WorkflowRevenueDetail> details = stagesByWorkflow.entrySet().stream()
                .map(entry -> {
                    Long workflowId = entry.getKey();
                    List<ContentRevenueStage> stages = entry.getValue();
                    
                    Workflow workflow = workflowMap.get(workflowId);
                    if (workflow == null) {
                        return null;
                    }
                    
                    Integer currentCopies = copyCounts.get(workflowId);
                    BigDecimal totalRevenue = stages.stream()
                            .filter(stage -> stage.getIsAchieved() == 1)
                            .map(ContentRevenueStage::getRewardAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    // 转换为收益阶段DTO
                    List<WithdrawDto.RevenueStage> revenueStages = stages.stream()
                            .map(this::convertToRevenueStage)
                            .collect(Collectors.toList());
                    
                    WithdrawDto.WorkflowRevenueDetail detail = new WithdrawDto.WorkflowRevenueDetail();
                    detail.setWorkflowId(workflowId);
                    detail.setWorkflowName(workflow.getName());
                    detail.setWorkflowDescription(workflow.getDescription());
                    detail.setWorkflowCoverUrl(workflow.getCoverUrl());
                    detail.setTotalRevenue(totalRevenue);
                    detail.setCurrentCopies(currentCopies);
                    detail.setStages(revenueStages);
                    
                    return detail;
                })
                .filter(detail -> detail != null)
                .collect(Collectors.toList());
        
        WithdrawDto.WorkflowRevenueListResponse response = new WithdrawDto.WorkflowRevenueListResponse();
        response.setRecords(details);
        response.setTotal(total);
        response.setPage(page);
        response.setSize(size);
        
        return response;
    }

    @Override
    public WithdrawDto.VideoRevenueListResponse getVideoRevenueDetails(Long userId, int page, int size) {
        int offset = (page - 1) * size;
        
        // 获取用户的视频收益阶段（分页）
        List<ContentRevenueStage> videoStages = contentRevenueStageMapper.selectByUserIdAndTypeWithPagination(userId, 2, offset, size);
        Long total = contentRevenueStageMapper.countByUserIdAndType(userId, 2);
        
        if (videoStages.isEmpty()) {
            WithdrawDto.VideoRevenueListResponse response = new WithdrawDto.VideoRevenueListResponse();
            response.setRecords(List.of());
            response.setTotal(0L);
            response.setPage(page);
            response.setSize(size);
            return response;
        }
        
        // 按视频ID分组
        Map<Long, List<ContentRevenueStage>> stagesByVideo = videoStages.stream()
                .collect(Collectors.groupingBy(ContentRevenueStage::getContentId));
        
        // 获取视频信息
        List<Long> videoIds = stagesByVideo.keySet().stream().collect(Collectors.toList());
        List<Video> videos = videoMapper.selectByIds(videoIds);
        Map<Long, Video> videoMap = videos.stream()
                .collect(Collectors.toMap(Video::getId, v -> v));
        
        // 获取每个视频的观看次数
        Map<Long, Integer> viewCounts = videoIds.stream()
                .collect(Collectors.toMap(
                    id -> id,
                    id -> videoViewStatMapper.countViewsByVideoId(id),
                    (existing, replacement) -> existing
                ));
        
        List<WithdrawDto.VideoRevenueDetail> details = stagesByVideo.entrySet().stream()
                .map(entry -> {
                    Long videoId = entry.getKey();
                    List<ContentRevenueStage> stages = entry.getValue();
                    
                    Video video = videoMap.get(videoId);
                    if (video == null) {
                        return null;
                    }
                    
                    Integer currentViews = viewCounts.get(videoId);
                    BigDecimal totalRevenue = stages.stream()
                            .filter(stage -> stage.getIsAchieved() == 1)
                            .map(ContentRevenueStage::getRewardAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    // 转换为收益阶段DTO
                    List<WithdrawDto.RevenueStage> revenueStages = stages.stream()
                            .map(this::convertToRevenueStage)
                            .collect(Collectors.toList());
                    
                    WithdrawDto.VideoRevenueDetail detail = new WithdrawDto.VideoRevenueDetail();
                    detail.setVideoId(videoId);
                    detail.setVideoTitle(video.getTitle());
                    detail.setVideoDescription(video.getDescription());
                    detail.setVideoCoverUrl(video.getCoverUrl());
                    detail.setTotalRevenue(totalRevenue);
                    detail.setCurrentViews(currentViews);
                    detail.setStages(revenueStages);
                    
                    return detail;
                })
                .filter(detail -> detail != null)
                .collect(Collectors.toList());
        
        WithdrawDto.VideoRevenueListResponse response = new WithdrawDto.VideoRevenueListResponse();
        response.setRecords(details);
        response.setTotal(total);
        response.setPage(page);
        response.setSize(size);
        
        return response;
    }

    @Override
    public WithdrawDto.PromotionRevenueResponse getPromotionRevenueInfo(Long userId) {
        // 1. 获取推广收益
        BigDecimal promotionRevenue = fanPromotionCommissionMapper.sumSettledCommissionByPromoterId(userId);
        
        // 2. 获取用户推广等级信息
        Integer promotionLevel = userMapper.selectById(userId).getPromotionLevel();
        
        // 3. 获取推广等级配置
        var promotionConfig = revenueConfigMapper.selectByConfigTypeAndLevel("promotion", promotionLevel);
        String promotionLevelName = promotionConfig != null ? promotionConfig.getLevelName() : "普通用户";
        BigDecimal promotionRate = promotionConfig != null ? promotionConfig.getCommissionRate() : BigDecimal.ZERO;
        
        // 4. 计算距离下一等级需要的粉丝数
        var nextLevelConfig = revenueConfigMapper.selectNextLevelConfig("promotion", promotionLevel);
        Integer fansToNextLevel = nextLevelConfig != null ? 
            nextLevelConfig.getMinFans() - userMapper.countPaidFansByInviterId(userId) : 0;
        
        // 5. 获取当前付费粉丝数
        Integer currentPaidFans = userMapper.countPaidFansByInviterId(userId);
        
        // 6. 构建响应
        WithdrawDto.PromotionRevenueResponse response = new WithdrawDto.PromotionRevenueResponse();
        response.setPromotionRevenue(promotionRevenue);
        response.setPromotionLevel(promotionLevel);
        response.setPromotionLevelName(promotionLevelName);
        response.setPromotionRate(promotionRate);
        response.setFansToNextLevel(fansToNextLevel);
        response.setCurrentPaidFans(currentPaidFans);
        
        return response;
    }
} 