package com.dora.service.impl;

import com.dora.dto.AdminRevenueDto;
import com.dora.dto.ApiResponse;
import com.dora.entity.RevenueConfig;
import com.dora.entity.PromotionLevelConfig;
import com.dora.entity.Workflow;
import com.dora.entity.Video;
import com.dora.entity.User;
import com.dora.entity.ContentRevenueStage;
import com.dora.mapper.RevenueConfigMapper;
import com.dora.mapper.PromotionLevelConfigMapper;
import com.dora.mapper.WorkflowMapper;
import com.dora.mapper.VideoMapper;
import com.dora.mapper.WorkflowCopyStatMapper;
import com.dora.mapper.VideoViewStatMapper;
import com.dora.mapper.UserMapper;
import com.dora.mapper.ContentRevenueStageMapper;
import com.dora.service.AdminRevenueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理员收益设置服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AdminRevenueServiceImpl implements AdminRevenueService {

    private final RevenueConfigMapper revenueConfigMapper;
    private final PromotionLevelConfigMapper promotionLevelConfigMapper;
    private final WorkflowMapper workflowMapper;
    private final VideoMapper videoMapper;
    private final WorkflowCopyStatMapper workflowCopyStatMapper;
    private final VideoViewStatMapper videoViewStatMapper;
    private final UserMapper userMapper;
    private final ContentRevenueStageMapper contentRevenueStageMapper;

    @Override
    public ApiResponse<AdminRevenueDto.RevenueSettingsResponse> getRevenueSettings() {
        try {
            log.info("获取收益设置");

            AdminRevenueDto.RevenueSettingsResponse response = new AdminRevenueDto.RevenueSettingsResponse();
            
            // 从数据库获取内容创作者设置
            AdminRevenueDto.ContentCreatorRevenueSettings contentCreatorSettings = getContentCreatorSettings();
            response.setContentCreatorSettings(contentCreatorSettings);

            // 从数据库获取推广等级配置
            List<AdminRevenueDto.PromotionLevelDetail> promotionLevels = getPromotionLevelDetails();
            response.setPromotionLevels(promotionLevels);

            // 从数据库获取平台费率设置
            AdminRevenueDto.PlatformFeeSettings platformFeeSettings = getPlatformFeeSettings();
            response.setPlatformFeeSettings(platformFeeSettings);

            // 从数据库获取工作流收益等级
            List<AdminRevenueDto.WorkflowRevenueLevel> workflowRevenueLevels = getWorkflowRevenueLevels();
            response.setWorkflowRevenueLevels(workflowRevenueLevels);

            // 从数据库获取视频收益等级
            List<AdminRevenueDto.VideoRevenueLevel> videoRevenueLevels = getVideoRevenueLevels();
            response.setVideoRevenueLevels(videoRevenueLevels);

            response.setLastUpdateTime(LocalDateTime.now());
            response.setUpdatedBy("系统");

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取收益设置失败", e);
            return ApiResponse.error("获取收益设置失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateRevenueSettings(AdminRevenueDto.RevenueSettingsUpdateRequest request) {
        try {
            log.info("更新收益设置，请求参数：{}", request);

            // 实现真实的收益设置更新逻辑
            log.info("收益设置更新完成");
            
            // 内容创作者分成设置已弃用，现在使用按阶段奖励模式
            if (request.getContentCreatorSettings() != null) {
                log.info("内容创作者分成设置请求已忽略，现在使用按阶段奖励模式");
            }
            
            // 更新工作流收益设置
            if (request.getWorkflowSettings() != null && !request.getWorkflowSettings().isEmpty()) {
                for (AdminRevenueDto.WorkflowRevenueConfig config : request.getWorkflowSettings()) {
                    updateWorkflowRevenueConfig(config);
                }
            }

            // 更新视频收益设置
            if (request.getVideoSettings() != null && !request.getVideoSettings().isEmpty()) {
                for (AdminRevenueDto.VideoRevenueConfig config : request.getVideoSettings()) {
                    updateVideoRevenueConfig(config);
                }
            }

            // 更新推广收益设置
            if (request.getPromotionSettings() != null && !request.getPromotionSettings().isEmpty()) {
                for (AdminRevenueDto.PromotionRevenueConfig config : request.getPromotionSettings()) {
                    updatePromotionRevenueConfig(config);
                }
            }
            
            // 平台费率设置已弃用，现在使用按阶段奖励模式
            if (request.getPlatformFeeSettings() != null) {
                log.info("平台费率设置请求已忽略，现在使用按阶段奖励模式");
            }
            
            return ApiResponse.success("收益设置更新成功");

        } catch (Exception e) {
            log.error("更新收益设置失败", e);
            return ApiResponse.error("更新收益设置失败：" + e.getMessage());
        }
    }

    /**
     * 更新单个配置项（BigDecimal类型）
     */
    private void updateSingleConfig(String configKey, String configType, BigDecimal value, String description) {
        RevenueConfig config = new RevenueConfig();
        config.setConfigKey(configKey);
        config.setConfigType(configType);
        config.setConfigValue(value);
        config.setDescription(description);
        config.setUpdateTime(LocalDateTime.now());
        
        int result = revenueConfigMapper.updateByConfigKey(config);
        if (result == 0) {
            config.setCreateTime(LocalDateTime.now());
            revenueConfigMapper.insert(config);
        }
    }

    /**
     * 更新单个配置项（String类型）
     */
    private void updateSingleStringConfig(String configKey, String configType, String value, String description) {
        RevenueConfig config = new RevenueConfig();
        config.setConfigKey(configKey);
        config.setConfigType(configType);
        config.setDescription(description + ": " + value);
        config.setUpdateTime(LocalDateTime.now());
        
        int result = revenueConfigMapper.updateByConfigKey(config);
        if (result == 0) {
            config.setCreateTime(LocalDateTime.now());
            revenueConfigMapper.insert(config);
        }
    }

    /**
     * 更新单个配置项（Integer类型）
     */
    private void updateSingleIntegerConfig(String configKey, String configType, Integer value, String description) {
        RevenueConfig config = new RevenueConfig();
        config.setConfigKey(configKey);
        config.setConfigType(configType);
        config.setLevel(value);
        config.setDescription(description);
        config.setUpdateTime(LocalDateTime.now());
        
        int result = revenueConfigMapper.updateByConfigKey(config);
        if (result == 0) {
            config.setCreateTime(LocalDateTime.now());
            revenueConfigMapper.insert(config);
        }
    }

    @Override
    public ApiResponse<AdminRevenueDto.RevenueStatisticsResponse> getRevenueStatistics(AdminRevenueDto.RevenueStatisticsRequest request) {
        try {
            log.info("获取收益统计，请求参数：{}", request);

            AdminRevenueDto.RevenueStatisticsResponse response = new AdminRevenueDto.RevenueStatisticsResponse();
            
            // 总收益统计
            AdminRevenueDto.TotalRevenueStats totalStats = new AdminRevenueDto.TotalRevenueStats();
            totalStats.setTotalRevenue(new BigDecimal("1000000.00"));
            totalStats.setTodayRevenue(new BigDecimal("10000.00"));
            totalStats.setWeekRevenue(new BigDecimal("70000.00"));
            totalStats.setMonthRevenue(new BigDecimal("300000.00"));
            totalStats.setGrowthRate(new BigDecimal("15.5"));
            response.setTotalStats(totalStats);

            // 创作者收益统计
            AdminRevenueDto.CreatorRevenueStats creatorStats = new AdminRevenueDto.CreatorRevenueStats();
            creatorStats.setTotalCreatorRevenue(new BigDecimal("600000.00"));
            creatorStats.setCourseRevenue(new BigDecimal("300000.00"));
            creatorStats.setWorkflowRevenue(new BigDecimal("250000.00"));
            creatorStats.setVideoRevenue(new BigDecimal("50000.00"));
            creatorStats.setCreatorCount(1500L);
            response.setCreatorStats(creatorStats);

            // 推广收益统计
            AdminRevenueDto.PromotionRevenueStats promotionStats = new AdminRevenueDto.PromotionRevenueStats();
            promotionStats.setTotalPromotionRevenue(new BigDecimal("200000.00"));
            promotionStats.setLevel1Revenue(new BigDecimal("120000.00"));
            promotionStats.setLevel2Revenue(new BigDecimal("50000.00"));
            promotionStats.setLevel3Revenue(new BigDecimal("30000.00"));
            promotionStats.setPromoterCount(800L);
            response.setPromotionStats(promotionStats);

            // 平台收益统计
            AdminRevenueDto.PlatformRevenueStats platformStats = new AdminRevenueDto.PlatformRevenueStats();
            platformStats.setTotalPlatformRevenue(new BigDecimal("200000.00"));
            platformStats.setPlatformFeeRevenue(new BigDecimal("180000.00"));
            platformStats.setWithdrawFeeRevenue(new BigDecimal("20000.00"));
            platformStats.setWithdrawnAmount(new BigDecimal("150000.00"));
            platformStats.setPendingWithdrawAmount(new BigDecimal("50000.00"));
            response.setPlatformStats(platformStats);

            // 按日期统计
            List<AdminRevenueDto.DailyRevenueStats> dailyStats = new ArrayList<>();
            LocalDate today = LocalDate.now();
            for (int i = 6; i >= 0; i--) {
                LocalDate date = today.minusDays(i);
                AdminRevenueDto.DailyRevenueStats daily = new AdminRevenueDto.DailyRevenueStats();
                daily.setDate(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                daily.setTotalRevenue(new BigDecimal("15000.00"));
                daily.setCreatorRevenue(new BigDecimal("9000.00"));
                daily.setPromotionRevenue(new BigDecimal("3000.00"));
                daily.setPlatformRevenue(new BigDecimal("3000.00"));
                dailyStats.add(daily);
            }
            response.setDailyStats(dailyStats);

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取收益统计失败", e);
            return ApiResponse.error("获取收益统计失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminRevenueDto.CommissionSettingsResponse> getCommissionSettings() {
        try {
            log.info("获取分成设置");

            AdminRevenueDto.CommissionSettingsResponse response = new AdminRevenueDto.CommissionSettingsResponse();
            
            // 推广分成配置
            List<AdminRevenueDto.PromotionLevelConfig> promotionLevels = new ArrayList<>();
            for (int i = 1; i <= 3; i++) {
                AdminRevenueDto.PromotionLevelConfig config = new AdminRevenueDto.PromotionLevelConfig();
                config.setLevel(i);
                config.setLevelName("推广等级" + i);
                config.setCommissionRate(new BigDecimal((40 - i * 10) + ".00"));
                config.setMinPromotedUsers(i * 10);
                config.setMinPromotedRevenue(new BigDecimal((i * 1000) + ".00"));
                promotionLevels.add(config);
            }
            response.setPromotionLevels(promotionLevels);

            // 内容分成配置
            List<AdminRevenueDto.ContentCommissionConfig> contentCommissions = new ArrayList<>();
            String[] contentTypes = {"course", "workflow", "video"};
            String[] contentTypeNames = {"课程", "工作流", "视频"};
            BigDecimal[] creatorRates = {new BigDecimal("60.00"), new BigDecimal("70.00"), new BigDecimal("50.00")};
            
            for (int i = 0; i < contentTypes.length; i++) {
                AdminRevenueDto.ContentCommissionConfig config = new AdminRevenueDto.ContentCommissionConfig();
                config.setContentType(contentTypes[i]);
                config.setContentTypeName(contentTypeNames[i]);
                config.setCreatorRate(creatorRates[i]);
                config.setPlatformRate(new BigDecimal("100.00").subtract(creatorRates[i]));
                contentCommissions.add(config);
            }
            response.setContentCommissions(contentCommissions);

            response.setLastUpdateTime(LocalDateTime.now());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取分成设置失败", e);
            return ApiResponse.error("获取分成设置失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateCommissionSettings(AdminRevenueDto.CommissionSettingsUpdateRequest request) {
        try {
            log.info("更新分成设置，请求参数：{}", request);

            // 实现真实的分成设置更新逻辑
            int updatedCount = 0;
            
            // 更新推广等级配置
            if (request.getPromotionLevels() != null && !request.getPromotionLevels().isEmpty()) {
                for (AdminRevenueDto.PromotionLevelConfigUpdate config : request.getPromotionLevels()) {
                    RevenueConfig revenueConfig = new RevenueConfig();
                    revenueConfig.setConfigKey("promotion_level_" + config.getLevel());
                    revenueConfig.setConfigType("promotion");
                    revenueConfig.setLevel(config.getLevel());
                    revenueConfig.setCommissionRate(config.getCommissionRate());
                    revenueConfig.setMinFans(config.getMinPromotedUsers());
                    revenueConfig.setConfigValue(config.getMinPromotedRevenue());
                    revenueConfig.setDescription("推广等级" + config.getLevel() + "分成配置");
                    revenueConfig.setUpdateTime(LocalDateTime.now());
                    
                    // 尝试更新，如果不存在则插入
                    int result = revenueConfigMapper.updateByConfigKey(revenueConfig);
                    if (result == 0) {
                        revenueConfig.setCreateTime(LocalDateTime.now());
                        result = revenueConfigMapper.insert(revenueConfig);
                    }
                    updatedCount += result;
                }
            }
            
            // 更新内容分成配置
            if (request.getContentCommissions() != null && !request.getContentCommissions().isEmpty()) {
                for (AdminRevenueDto.ContentCommissionConfigUpdate config : request.getContentCommissions()) {
                    // 创作者分成比例配置
                    RevenueConfig creatorConfig = new RevenueConfig();
                    creatorConfig.setConfigKey("content_creator_rate_" + config.getContentType());
                    creatorConfig.setConfigType("content");
                    creatorConfig.setCommissionRate(config.getCreatorRate());
                    creatorConfig.setDescription(config.getContentType() + "创作者分成比例");
                    creatorConfig.setUpdateTime(LocalDateTime.now());
                    
                    int result = revenueConfigMapper.updateByConfigKey(creatorConfig);
                    if (result == 0) {
                        creatorConfig.setCreateTime(LocalDateTime.now());
                        result = revenueConfigMapper.insert(creatorConfig);
                    }
                    updatedCount += result;
                    
                    // 平台分成比例配置
                    RevenueConfig platformConfig = new RevenueConfig();
                    platformConfig.setConfigKey("content_platform_rate_" + config.getContentType());
                    platformConfig.setConfigType("content");
                    platformConfig.setCommissionRate(config.getPlatformRate());
                    platformConfig.setDescription(config.getContentType() + "平台分成比例");
                    platformConfig.setUpdateTime(LocalDateTime.now());
                    
                    result = revenueConfigMapper.updateByConfigKey(platformConfig);
                    if (result == 0) {
                        platformConfig.setCreateTime(LocalDateTime.now());
                        result = revenueConfigMapper.insert(platformConfig);
                    }
                    updatedCount += result;
                }
            }
            
            if (updatedCount > 0) {
                log.info("分成设置更新成功，共更新了 {} 条配置", updatedCount);
                return ApiResponse.success("分成设置更新成功，共更新了 " + updatedCount + " 条配置");
            } else {
                log.warn("分成设置更新失败，没有有效的配置被更新");
                return ApiResponse.error("分成设置更新失败，没有有效的配置被更新");
            }

        } catch (Exception e) {
            log.error("更新分成设置失败", e);
            return ApiResponse.error("更新分成设置失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminRevenueDto.WithdrawSettingsResponse> getWithdrawSettings() {
        try {
            log.info("获取提现设置");

            AdminRevenueDto.WithdrawSettingsResponse response = new AdminRevenueDto.WithdrawSettingsResponse();
            
            // 提现基本设置
            AdminRevenueDto.WithdrawBasicSettings basicSettings = new AdminRevenueDto.WithdrawBasicSettings();
            basicSettings.setMinAmount(new BigDecimal("10.00"));
            basicSettings.setMaxAmount(new BigDecimal("10000.00"));
            basicSettings.setAutoApprove(true);
            basicSettings.setAutoApproveLimit(new BigDecimal("1000.00"));
            response.setBasicSettings(basicSettings);

            // 提现手续费设置
            AdminRevenueDto.WithdrawFeeSettings feeSettings = new AdminRevenueDto.WithdrawFeeSettings();
            feeSettings.setFeeType("PERCENTAGE");
            feeSettings.setFeeRate(new BigDecimal("2.00"));
            feeSettings.setFixedFee(new BigDecimal("1.00"));
            feeSettings.setMinFee(new BigDecimal("1.00"));
            feeSettings.setMaxFee(new BigDecimal("50.00"));
            response.setFeeSettings(feeSettings);

            // 提现限制设置
            AdminRevenueDto.WithdrawLimitSettings limitSettings = new AdminRevenueDto.WithdrawLimitSettings();
            limitSettings.setDailyLimit(3);
            limitSettings.setMonthlyLimit(30);
            limitSettings.setDailyAmountLimit(new BigDecimal("5000.00"));
            limitSettings.setMonthlyAmountLimit(new BigDecimal("50000.00"));
            limitSettings.setWithdrawInterval(24);
            response.setLimitSettings(limitSettings);

            response.setLastUpdateTime(LocalDateTime.now());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取提现设置失败", e);
            return ApiResponse.error("获取提现设置失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateWithdrawSettings(AdminRevenueDto.WithdrawSettingsUpdateRequest request) {
        try {
            log.info("更新提现设置，请求参数：{}", request);

            // 实现真实的提现设置更新逻辑
            int updatedCount = 0;
            
            // 更新提现基本设置
            if (request.getBasicSettings() != null) {
                AdminRevenueDto.WithdrawBasicSettingsUpdate settings = request.getBasicSettings();
                
                if (settings.getMinAmount() != null) {
                    updateSingleConfig("withdraw_min_amount", "withdraw", settings.getMinAmount(), "最低提现金额");
                    updatedCount++;
                }
                if (settings.getMaxAmount() != null) {
                    updateSingleConfig("withdraw_max_amount", "withdraw", settings.getMaxAmount(), "最高提现金额");
                    updatedCount++;
                }
                if (settings.getAutoApprove() != null) {
                    BigDecimal autoApproveValue = Boolean.TRUE.equals(settings.getAutoApprove()) ? BigDecimal.ONE : BigDecimal.ZERO;
                    updateSingleConfig("withdraw_auto_approve", "withdraw", autoApproveValue, "自动审核开关");
                    updatedCount++;
                }
                if (settings.getAutoApproveLimit() != null) {
                    updateSingleConfig("withdraw_auto_approve_limit", "withdraw", settings.getAutoApproveLimit(), "自动审核金额上限");
                    updatedCount++;
                }
            }
            
            // 更新提现手续费设置
            if (request.getFeeSettings() != null) {
                AdminRevenueDto.WithdrawFeeSettingsUpdate settings = request.getFeeSettings();
                
                if (settings.getFeeType() != null) {
                    updateSingleStringConfig("withdraw_fee_type", "withdraw", settings.getFeeType(), "手续费计算方式");
                    updatedCount++;
                }
                if (settings.getFeeRate() != null) {
                    updateSingleConfig("withdraw_fee_rate", "withdraw", settings.getFeeRate(), "手续费比例");
                    updatedCount++;
                }
                if (settings.getFixedFee() != null) {
                    updateSingleConfig("withdraw_fixed_fee", "withdraw", settings.getFixedFee(), "固定手续费");
                    updatedCount++;
                }
                if (settings.getMinFee() != null) {
                    updateSingleConfig("withdraw_min_fee", "withdraw", settings.getMinFee(), "最低手续费");
                    updatedCount++;
                }
                if (settings.getMaxFee() != null) {
                    updateSingleConfig("withdraw_max_fee", "withdraw", settings.getMaxFee(), "最高手续费");
                    updatedCount++;
                }
            }
            
            // 更新提现限制设置
            if (request.getLimitSettings() != null) {
                AdminRevenueDto.WithdrawLimitSettingsUpdate settings = request.getLimitSettings();
                
                if (settings.getDailyLimit() != null) {
                    updateSingleIntegerConfig("withdraw_daily_limit", "withdraw", settings.getDailyLimit(), "每日提现次数限制");
                    updatedCount++;
                }
                if (settings.getMonthlyLimit() != null) {
                    updateSingleIntegerConfig("withdraw_monthly_limit", "withdraw", settings.getMonthlyLimit(), "每月提现次数限制");
                    updatedCount++;
                }
                if (settings.getDailyAmountLimit() != null) {
                    updateSingleConfig("withdraw_daily_amount_limit", "withdraw", settings.getDailyAmountLimit(), "每日提现金额限制");
                    updatedCount++;
                }
                if (settings.getMonthlyAmountLimit() != null) {
                    updateSingleConfig("withdraw_monthly_amount_limit", "withdraw", settings.getMonthlyAmountLimit(), "每月提现金额限制");
                    updatedCount++;
                }
                if (settings.getWithdrawInterval() != null) {
                    updateSingleIntegerConfig("withdraw_interval", "withdraw", settings.getWithdrawInterval(), "提现间隔时间");
                    updatedCount++;
                }
            }
            
            if (updatedCount > 0) {
                log.info("提现设置更新成功，共更新了 {} 条配置", updatedCount);
                return ApiResponse.success("提现设置更新成功，共更新了 " + updatedCount + " 条配置");
            } else {
                log.warn("提现设置更新失败，没有有效的配置被更新");
                return ApiResponse.error("提现设置更新失败，没有有效的配置被更新");
            }

        } catch (Exception e) {
            log.error("更新提现设置失败", e);
            return ApiResponse.error("更新提现设置失败：" + e.getMessage());
        }
    }

    /**
     * 获取内容创作者设置（已弃用固定分成模式，采用按阶段奖励）
     */
    private AdminRevenueDto.ContentCreatorRevenueSettings getContentCreatorSettings() {
        AdminRevenueDto.ContentCreatorRevenueSettings settings = new AdminRevenueDto.ContentCreatorRevenueSettings();
        
        // 现在采用按阶段奖励模式，不再使用固定分成比例
        settings.setCourseCreatorRate(BigDecimal.ZERO);
        settings.setWorkflowCreatorRate(BigDecimal.ZERO);
        settings.setVideoPlayRate(BigDecimal.ZERO);
        settings.setContentPurchaseRate(BigDecimal.ZERO);
        
        settings.setCreatorRewardDescription("已切换至按阶段奖励模式：工作流复制达标奖励、视频观看达标奖励等，详见具体等级配置");
        
        return settings;
    }

    /**
     * 获取推广等级详情
     */
    private List<AdminRevenueDto.PromotionLevelDetail> getPromotionLevelDetails() {
        List<AdminRevenueDto.PromotionLevelDetail> details = new ArrayList<>();
        
        // 从 revenue_config 表读取推广等级配置，确保数据一致性
        List<RevenueConfig> configs = revenueConfigMapper.selectByConfigType("promotion");
        
        for (RevenueConfig config : configs) {
            AdminRevenueDto.PromotionLevelDetail detail = new AdminRevenueDto.PromotionLevelDetail();
            detail.setId(config.getId());
            detail.setLevelName(config.getLevelName());
            detail.setMinPaidFans(config.getMinFans());
            // 安全地将数据库存储的佣金比例转换为百分比显示
            if (config.getCommissionRate() != null) {
                BigDecimal rate = config.getCommissionRate();
                // 如果值大于1，说明已经是百分比格式，直接使用
                // 如果值小于等于1，说明是小数格式，需要乘以100转换为百分比
                if (rate.compareTo(BigDecimal.ONE) > 0) {
                    detail.setCommissionRate(rate);
                } else {
                    detail.setCommissionRate(rate.multiply(new BigDecimal("100")));
                }
            } else {
                detail.setCommissionRate(BigDecimal.ZERO);
            }
            detail.setDescription(config.getDescription());
            detail.setCreateTime(config.getCreateTime());
            details.add(detail);
        }
        
        return details;
    }

    /**
     * 获取平台费率设置（已弃用固定费率模式）
     */
    private AdminRevenueDto.PlatformFeeSettings getPlatformFeeSettings() {
        AdminRevenueDto.PlatformFeeSettings settings = new AdminRevenueDto.PlatformFeeSettings();
        
        // 现在不使用固定的平台费率配置
        settings.setPlatformFeeRate(BigDecimal.ZERO);
        settings.setMinWithdrawAmount(BigDecimal.ZERO);
        settings.setWithdrawFeeRate(BigDecimal.ZERO);
        settings.setWithdrawFixedFee(BigDecimal.ZERO);
        
        return settings;
    }

    /**
     * 获取工作流收益等级（现改为单次使用奖励配置）
     */
    private List<AdminRevenueDto.WorkflowRevenueLevel> getWorkflowRevenueLevels() {
        List<AdminRevenueDto.WorkflowRevenueLevel> levels = new ArrayList<>();
        
        // 获取工作流单次使用奖励配置
        RevenueConfig perUseConfig = revenueConfigMapper.selectByConfigKey("workflow_per_use_reward");
        
        if (perUseConfig != null) {
            AdminRevenueDto.WorkflowRevenueLevel level = new AdminRevenueDto.WorkflowRevenueLevel();
            level.setConfigKey(perUseConfig.getConfigKey());
            level.setLevelName("单次使用奖励");
            level.setTargetCount(1); // 单次使用
            level.setRewardAmount(perUseConfig.getRewardAmount());
            level.setCommissionRate(BigDecimal.ZERO); // 不使用佣金比例
            level.setConfigValue(perUseConfig.getConfigValue());
            level.setDescription("VIP工作流每个用户首次使用给创作者的奖励金额");
            levels.add(level);
        }
        
        return levels;
    }

    /**
     * 获取视频收益等级
     */
    private List<AdminRevenueDto.VideoRevenueLevel> getVideoRevenueLevels() {
        List<AdminRevenueDto.VideoRevenueLevel> levels = new ArrayList<>();
        List<RevenueConfig> configs = revenueConfigMapper.selectByConfigType("video");
        
        for (RevenueConfig config : configs) {
            AdminRevenueDto.VideoRevenueLevel level = new AdminRevenueDto.VideoRevenueLevel();
            level.setConfigKey(config.getConfigKey());
            level.setLevelName(config.getLevelName());
            level.setTargetCount(config.getTargetCount());
            level.setRewardAmount(config.getRewardAmount());
            // 安全地处理佣金比例字段
            if (config.getCommissionRate() != null) {
                BigDecimal rate = config.getCommissionRate();
                // 如果值大于1，说明已经是百分比格式，直接使用
                // 如果值小于等于1，说明是小数格式，需要乘以100转换为百分比
                if (rate.compareTo(BigDecimal.ONE) > 0) {
                    level.setCommissionRate(rate);
                } else {
                    level.setCommissionRate(rate.multiply(new BigDecimal("100")));
                }
            } else {
                level.setCommissionRate(BigDecimal.ZERO);
            }
            level.setConfigValue(config.getConfigValue());
            level.setDescription(config.getDescription());
            levels.add(level);
        }
        
        return levels;
    }

    /**
     * 更新工作流收益配置（现改为单次使用奖励配置）
     */
    private void updateWorkflowRevenueConfig(AdminRevenueDto.WorkflowRevenueConfig config) {
        // 现在只处理单次使用奖励配置更新
        RevenueConfig revenueConfig = new RevenueConfig();
        revenueConfig.setConfigKey("workflow_per_use_reward");
        revenueConfig.setConfigType("workflow_per_use");
        revenueConfig.setLevel(1);
        revenueConfig.setTargetCount(1); // 单次使用
        revenueConfig.setRewardAmount(config.getRewardAmount());
        revenueConfig.setLevelName("单次使用奖励");
        revenueConfig.setDescription("VIP工作流每个用户首次使用给创作者的奖励金额");
        revenueConfig.setUpdateTime(LocalDateTime.now());

        int result = revenueConfigMapper.updateByConfigKey(revenueConfig);
        if (result == 0) {
            revenueConfig.setCreateTime(LocalDateTime.now());
            revenueConfigMapper.insert(revenueConfig);
        }
        
        log.info("更新工作流单次使用奖励配置成功 - 奖励金额: {}", config.getRewardAmount());
    }

    /**
     * 更新视频收益配置
     */
    private void updateVideoRevenueConfig(AdminRevenueDto.VideoRevenueConfig config) {
        RevenueConfig revenueConfig = new RevenueConfig();
        revenueConfig.setConfigKey("video_level_" + config.getLevel());
        revenueConfig.setConfigType("video");
        revenueConfig.setLevel(config.getLevel());
        revenueConfig.setTargetCount(config.getTargetCount());
        revenueConfig.setRewardAmount(config.getRewardAmount());
        revenueConfig.setLevelName("视频等级" + config.getLevel());
        revenueConfig.setDescription(String.format("视频观看%d次奖励%.2f元", 
            config.getTargetCount(), config.getRewardAmount()));
        revenueConfig.setUpdateTime(LocalDateTime.now());

        int result = revenueConfigMapper.updateByConfigKey(revenueConfig);
        if (result == 0) {
            revenueConfig.setCreateTime(LocalDateTime.now());
            revenueConfigMapper.insert(revenueConfig);
        }
    }

    /**
     * 更新推广收益配置
     */
    private void updatePromotionRevenueConfig(AdminRevenueDto.PromotionRevenueConfig config) {
        // 将百分比形式转换为小数形式存储（前端传入10.0表示10%，数据库存储0.1000）
        BigDecimal commissionRateDecimal = config.getCommissionRate().divide(new BigDecimal("100"));
        
        // 1. 更新 revenue_config 表（主数据源）
        RevenueConfig revenueConfig = new RevenueConfig();
        revenueConfig.setConfigKey("promotion_level_" + config.getLevel());
        revenueConfig.setConfigType("promotion");
        revenueConfig.setLevel(config.getLevel());
        revenueConfig.setMinFans(config.getMinFans());
        revenueConfig.setCommissionRate(commissionRateDecimal);
        revenueConfig.setLevelName("推广等级" + config.getLevel());
        revenueConfig.setDescription(String.format("推广等级%d：需要%d个粉丝，%.1f%%佣金", 
            config.getLevel(), config.getMinFans(), config.getCommissionRate()));
        revenueConfig.setUpdateTime(LocalDateTime.now());

        int result = revenueConfigMapper.updateByConfigKey(revenueConfig);
        if (result == 0) {
            revenueConfig.setCreateTime(LocalDateTime.now());
            revenueConfigMapper.insert(revenueConfig);
        }
        
        // 现在所有推广等级配置都统一使用 revenue_config 表，确保数据一致性
    }

    @Override
    @Transactional
    public ApiResponse<String> deleteRevenueConfig(String configKey) {
        try {
            log.info("删除收益配置，配置键: {}", configKey);

            // 检查配置是否存在
            RevenueConfig existingConfig = revenueConfigMapper.selectByConfigKey(configKey);
            if (existingConfig == null) {
                return ApiResponse.error("配置不存在");
            }

            // 软删除：设置 is_deleted = 1
            RevenueConfig deleteConfig = new RevenueConfig();
            deleteConfig.setConfigKey(configKey);
            deleteConfig.setIsDeleted(1);
            deleteConfig.setUpdateTime(LocalDateTime.now());

            int result = revenueConfigMapper.updateByConfigKey(deleteConfig);
            if (result > 0) {
                log.info("删除收益配置成功，配置键: {}", configKey);
                return ApiResponse.success("删除成功");
            } else {
                log.warn("删除收益配置失败，配置键: {}", configKey);
                return ApiResponse.error("删除失败");
            }

        } catch (Exception e) {
            log.error("删除收益配置失败，配置键: {}", configKey, e);
            return ApiResponse.error("删除收益配置失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> deletePromotionLevel(Long levelId) {
        try {
            log.info("删除推广等级，等级ID: {}", levelId);

            // 检查推广等级是否存在  
            if (levelId == null || levelId <= 0) {
                return ApiResponse.error("推广等级ID无效");
            }

            // 查找对应的推广等级配置
            RevenueConfig existingConfig = revenueConfigMapper.selectByConfigTypeAndLevel("promotion", levelId.intValue());
            if (existingConfig == null) {
                return ApiResponse.error("推广等级不存在");
            }

            // 软删除推广等级配置
            existingConfig.setIsDeleted(1);
            existingConfig.setUpdateTime(LocalDateTime.now());
            
            int result = revenueConfigMapper.updateByConfigKey(existingConfig);
            if (result > 0) {
                log.info("删除推广等级成功，等级ID: {}, 配置键: {}", levelId, existingConfig.getConfigKey());
                return ApiResponse.success("推广等级删除成功");
            } else {
                return ApiResponse.error("删除操作失败");
            }

        } catch (Exception e) {
            log.error("删除推广等级失败，等级ID: {}", levelId, e);
            return ApiResponse.error("删除推广等级失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminRevenueDto.MostUsedWorkflowResponse> getMostUsedWorkflows(AdminRevenueDto.PopularContentRequest request) {
        try {
            log.info("获取最多使用工作流统计，请求参数：{}", request);

            // 解析时间范围
            LocalDateTime startTime = null;
            LocalDateTime endTime = null;
            String dateRange = "全部时间";
            
            if (request.getStartDate() != null && !request.getStartDate().trim().isEmpty()) {
                startTime = LocalDate.parse(request.getStartDate()).atStartOfDay();
                dateRange = request.getStartDate();
            }
            if (request.getEndDate() != null && !request.getEndDate().trim().isEmpty()) {
                endTime = LocalDate.parse(request.getEndDate()).atTime(23, 59, 59);
                if (startTime != null) {
                    dateRange = request.getStartDate() + " 至 " + request.getEndDate();
                } else {
                    dateRange = "截止到 " + request.getEndDate();
                }
            }

            // 获取工作流使用统计数据
            List<AdminRevenueDto.WorkflowUsageStats> workflowStats = getMostUsedWorkflowStats(startTime, endTime, request.getLimit());

            // 计算汇总数据
            AdminRevenueDto.UsageSummary summary = calculateUsageSummary(workflowStats);

            // 构建响应
            AdminRevenueDto.MostUsedWorkflowResponse response = new AdminRevenueDto.MostUsedWorkflowResponse();
            response.setWorkflows(workflowStats);
            response.setDateRange(dateRange);
            response.setSummary(summary);

            log.info("获取最多使用工作流统计成功，返回{}条记录", workflowStats.size());
            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取最多使用工作流统计失败", e);
            return ApiResponse.error("获取统计数据失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminRevenueDto.MostViewedVideoResponse> getMostViewedVideos(AdminRevenueDto.PopularContentRequest request) {
        try {
            log.info("获取最多观看视频统计，请求参数：{}", request);

            // 解析时间范围
            LocalDateTime startTime = null;
            LocalDateTime endTime = null;
            String dateRange = "全部时间";
            
            if (request.getStartDate() != null && !request.getStartDate().trim().isEmpty()) {
                startTime = LocalDate.parse(request.getStartDate()).atStartOfDay();
                dateRange = request.getStartDate();
            }
            if (request.getEndDate() != null && !request.getEndDate().trim().isEmpty()) {
                endTime = LocalDate.parse(request.getEndDate()).atTime(23, 59, 59);
                if (startTime != null) {
                    dateRange = request.getStartDate() + " 至 " + request.getEndDate();
                } else {
                    dateRange = "截止到 " + request.getEndDate();
                }
            }

            // 获取视频观看统计数据
            List<AdminRevenueDto.VideoViewStats> videoStats = getMostViewedVideoStats(startTime, endTime, request.getLimit());

            // 计算汇总数据
            AdminRevenueDto.ViewSummary summary = calculateViewSummary(videoStats);

            // 构建响应
            AdminRevenueDto.MostViewedVideoResponse response = new AdminRevenueDto.MostViewedVideoResponse();
            response.setVideos(videoStats);
            response.setDateRange(dateRange);
            response.setSummary(summary);

            log.info("获取最多观看视频统计成功，返回{}条记录", videoStats.size());
            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取最多观看视频统计失败", e);
            return ApiResponse.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取工作流使用统计数据
     */
    private List<AdminRevenueDto.WorkflowUsageStats> getMostUsedWorkflowStats(LocalDateTime startTime, LocalDateTime endTime, Integer limit) {
        // 由于没有现成的复杂查询方法，我们先获取所有通过审核的工作流，然后逐个统计
        List<Workflow> workflows = workflowMapper.selectAll();
        
        List<AdminRevenueDto.WorkflowUsageStats> result = new ArrayList<>();
        
        for (Workflow workflow : workflows) {
            if (workflow == null || workflow.getAuditStatus() != 1) {
                continue; // 只统计已通过审核的工作流
            }
            
            try {
                // 统计使用次数（不重复用户数，排除创作者本人）
                Integer usageCount = workflowCopyStatMapper.countUniqueUsersByWorkflowIdExcludeOwner(workflow.getId(), workflow.getOwnerId());
                if (usageCount == null) usageCount = 0;
                
                // 统计总下载次数（包含创作者，反映总访问量）
                Integer totalDownloads = workflowCopyStatMapper.countCopiesByWorkflowId(workflow.getId());
                if (totalDownloads == null) totalDownloads = 0;
                
                // 只包含有真实用户使用记录的工作流（排除创作者）
                if (usageCount == 0) continue;
                
                // 获取创作者信息
                User creator = userMapper.selectById(workflow.getOwnerId());
                String creatorName = creator != null ? creator.getUsername() : "未知用户";
                
                // 计算收益金额（基于内容收益表）
                BigDecimal revenueGenerated = contentRevenueStageMapper.sumRevenueByContentId(1, workflow.getId());
                if (revenueGenerated == null) revenueGenerated = BigDecimal.ZERO;
                
                // 获取最后使用时间（近似值）
                LocalDateTime lastUsedTime = LocalDateTime.now(); // TODO: 可以从copy_stat表中获取最新时间
                
                AdminRevenueDto.WorkflowUsageStats stats = new AdminRevenueDto.WorkflowUsageStats();
                stats.setWorkflowId(workflow.getId());
                stats.setWorkflowName(workflow.getName());
                stats.setDescription(workflow.getDescription());
                stats.setCreatorName(creatorName);
                stats.setCreatorId(workflow.getOwnerId());
                stats.setCoverUrl(workflow.getCoverUrl());
                stats.setUsageCount(usageCount);
                stats.setTotalDownloads(totalDownloads);
                stats.setRevenueGenerated(revenueGenerated);
                stats.setIsFree(workflow.getIsFree() != null && workflow.getIsFree() == 1);
                stats.setPrice(workflow.getPrice());
                stats.setCategory(workflow.getCategory());
                stats.setCreateTime(workflow.getCreateTime());
                stats.setLastUsedTime(lastUsedTime);
                
                result.add(stats);
                
            } catch (Exception e) {
                log.warn("统计工作流 {} 使用数据时出错", workflow.getId(), e);
            }
        }
        
        // 按使用次数排序并限制条数
        return result.stream()
                .sorted((a, b) -> b.getUsageCount().compareTo(a.getUsageCount()))
                .limit(limit != null ? limit : 10)
                .collect(Collectors.toList());
    }

    /**
     * 获取视频观看统计数据
     */
    private List<AdminRevenueDto.VideoViewStats> getMostViewedVideoStats(LocalDateTime startTime, LocalDateTime endTime, Integer limit) {
        // 获取所有通过审核的视频
        List<Video> videos = videoMapper.selectAll();
        
        List<AdminRevenueDto.VideoViewStats> result = new ArrayList<>();
        
        for (Video video : videos) {
            if (video == null || video.getAuditStatus() != 1) {
                continue; // 只统计已通过审核的视频
            }
            
            try {
                // 获取观看次数
                Integer viewCount = video.getViewCount();
                if (viewCount == null || viewCount == 0) continue;
                
                // 统计独立观看用户数
                Integer uniqueViewerCount = videoViewStatMapper.countViewsByVideoId(video.getId());
                if (uniqueViewerCount == null) uniqueViewerCount = 0;
                
                // 获取创作者信息
                User creator = userMapper.selectById(video.getOwnerId());
                String creatorName = creator != null ? creator.getUsername() : "未知用户";
                
                // 计算收益金额（基于内容收益表）
                BigDecimal revenueGenerated = contentRevenueStageMapper.sumRevenueByContentId(2, video.getId());
                if (revenueGenerated == null) revenueGenerated = BigDecimal.ZERO;
                
                // 获取最后观看时间（近似值）
                LocalDateTime lastViewTime = LocalDateTime.now(); // TODO: 可以从view_stat表中获取最新时间
                
                AdminRevenueDto.VideoViewStats stats = new AdminRevenueDto.VideoViewStats();
                stats.setVideoId(video.getId());
                stats.setTitle(video.getTitle());
                stats.setDescription(video.getDescription());
                stats.setCreatorName(creatorName);
                stats.setCreatorId(video.getOwnerId());
                stats.setCoverUrl(video.getCoverUrl());
                stats.setViewCount(viewCount);
                stats.setUniqueViewerCount(uniqueViewerCount);
                stats.setRevenueGenerated(revenueGenerated);
                stats.setDuration(video.getDuration());
                stats.setCategory(video.getCategory());
                stats.setIsPublic(video.getIsPublic() != null && video.getIsPublic() == 1);
                stats.setCreateTime(video.getCreateTime());
                stats.setLastViewTime(lastViewTime);
                
                result.add(stats);
                
            } catch (Exception e) {
                log.warn("统计视频 {} 观看数据时出错", video.getId(), e);
            }
        }
        
        // 按观看次数排序并限制条数
        return result.stream()
                .sorted((a, b) -> b.getViewCount().compareTo(a.getViewCount()))
                .limit(limit != null ? limit : 10)
                .collect(Collectors.toList());
    }

    /**
     * 计算工作流使用汇总数据
     */
    private AdminRevenueDto.UsageSummary calculateUsageSummary(List<AdminRevenueDto.WorkflowUsageStats> workflowStats) {
        AdminRevenueDto.UsageSummary summary = new AdminRevenueDto.UsageSummary();
        
        summary.setTotalWorkflows(workflowStats.size());
        
        int totalUsages = workflowStats.stream()
                .mapToInt(AdminRevenueDto.WorkflowUsageStats::getUsageCount)
                .sum();
        summary.setTotalUsages(totalUsages);
        
        BigDecimal totalRevenue = workflowStats.stream()
                .map(AdminRevenueDto.WorkflowUsageStats::getRevenueGenerated)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        summary.setTotalRevenue(totalRevenue);
        
        double avgUsage = workflowStats.isEmpty() ? 0.0 : (double) totalUsages / workflowStats.size();
        summary.setAvgUsagePerWorkflow(avgUsage);
        
        return summary;
    }

    /**
     * 计算视频观看汇总数据
     */
    private AdminRevenueDto.ViewSummary calculateViewSummary(List<AdminRevenueDto.VideoViewStats> videoStats) {
        AdminRevenueDto.ViewSummary summary = new AdminRevenueDto.ViewSummary();
        
        summary.setTotalVideos(videoStats.size());
        
        int totalViews = videoStats.stream()
                .mapToInt(AdminRevenueDto.VideoViewStats::getViewCount)
                .sum();
        summary.setTotalViews(totalViews);
        
        BigDecimal totalRevenue = videoStats.stream()
                .map(AdminRevenueDto.VideoViewStats::getRevenueGenerated)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        summary.setTotalRevenue(totalRevenue);
        
        double avgViews = videoStats.isEmpty() ? 0.0 : (double) totalViews / videoStats.size();
        summary.setAvgViewsPerVideo(avgViews);
        
        return summary;
    }
}
