package com.dora.service.impl;

import com.dora.dto.PromotionRuleDto;
import com.dora.entity.RevenueConfig;
import com.dora.entity.User;
import com.dora.mapper.PromotionRuleMapper;
import com.dora.mapper.UserMapper;
import com.dora.service.PromotionRuleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 推广规则服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PromotionRuleServiceImpl implements PromotionRuleService {

    private final PromotionRuleMapper promotionRuleMapper;
    private final UserMapper userMapper;

    @Override
    public PromotionRuleDto.PromotionRuleResponse getPromotionRules() {
        PromotionRuleDto.PromotionRuleResponse response = new PromotionRuleDto.PromotionRuleResponse();
        
        try {
            // 获取推广等级规则
            List<RevenueConfig> promotionLevelConfigs = promotionRuleMapper.selectPromotionLevelRules();
            List<PromotionRuleDto.PromotionLevelRule> promotionLevels = new ArrayList<>();
            
            for (RevenueConfig config : promotionLevelConfigs) {
                PromotionRuleDto.PromotionLevelRule rule = new PromotionRuleDto.PromotionLevelRule();
                rule.setLevel(config.getLevel());
                rule.setLevelName(config.getLevelName());
                rule.setMinFans(config.getMinFans());
                // 安全地将数据库存储的佣金比例转换为百分比显示
                if (config.getCommissionRate() != null) {
                    BigDecimal rate = config.getCommissionRate();
                    // 如果值大于1，说明已经是百分比格式，直接使用
                    // 如果值小于等于1，说明是小数格式，需要乘以100转换为百分比
                    if (rate.compareTo(BigDecimal.ONE) > 0) {
                        rule.setCommissionRate(rate);
                    } else {
                        rule.setCommissionRate(rate.multiply(new BigDecimal("100")));
                    }
                } else {
                    rule.setCommissionRate(BigDecimal.ZERO);
                }
                rule.setDescription(config.getDescription());
                promotionLevels.add(rule);
            }
            
            // 获取内容收益规则
            List<RevenueConfig> contentRewardConfigs = promotionRuleMapper.selectContentRewardRules();
            List<PromotionRuleDto.ContentRewardRule> contentRewards = new ArrayList<>();
            
            for (RevenueConfig config : contentRewardConfigs) {
                PromotionRuleDto.ContentRewardRule rule = new PromotionRuleDto.ContentRewardRule();
                rule.setType(config.getConfigType());
                rule.setTypeName(getTypeName(config.getConfigType()));
                rule.setTargetCount(config.getTargetCount());
                rule.setRewardAmount(config.getRewardAmount());
                rule.setConfigValue(config.getConfigValue());
                rule.setDescription(config.getDescription());
                contentRewards.add(rule);
            }
            
            response.setSuccess(true);
            response.setMessage("获取成功");
            response.setPromotionLevels(promotionLevels);
            response.setContentRewards(contentRewards);
            response.setPromotionDescription("通过推广获得粉丝，粉丝购买会员可获得提成收益");
            response.setRewardDescription("创作优质内容，获得播放和复制收益");
            
            log.info("获取推广规则成功 - 推广等级数: {}, 内容收益规则数: {}", 
                    promotionLevels.size(), contentRewards.size());
            
        } catch (Exception e) {
            log.error("获取推广规则失败", e);
            response.setSuccess(false);
            response.setMessage("获取失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public PromotionRuleDto.UserPromotionStatus getUserPromotionStatus(Long userId) {
        PromotionRuleDto.UserPromotionStatus status = new PromotionRuleDto.UserPromotionStatus();
        
        try {
            // 1. 获取用户信息
            User user = userMapper.selectById(userId);
            if (user == null) {
                throw new IllegalArgumentException("用户不存在");
            }
            
            // 2. 获取用户粉丝数量
            int totalFansCount = userMapper.countFansByInviterId(userId);
            int paidFansCount = userMapper.countPaidFansByInviterId(userId);
            
            // 3. 获取所有推广等级规则，按等级排序
            List<RevenueConfig> allConfigs = promotionRuleMapper.selectPromotionLevelRules();
            if (allConfigs.isEmpty()) {
                throw new IllegalStateException("推广规则配置为空");
            }
            
            // 4. 直接使用用户数据库中的推广等级（不再重复计算，提高性能）
            Integer currentLevel = user.getPromotionLevel();
            if (currentLevel == null) {
                currentLevel = 1; // 默认等级
                log.warn("用户推广等级为空，使用默认等级1 - userId: {}", userId);
            }
            status.setCurrentLevel(currentLevel);
            status.setTotalFansCount(totalFansCount);
            status.setPaidFansCount(paidFansCount);
            
            log.debug("获取推广状态 - userId: {}, currentLevel: {}, totalFans: {}, paidFans: {}", 
                    userId, currentLevel, totalFansCount, paidFansCount);
            
            // 5. 查找当前等级和下一等级配置
            RevenueConfig currentLevelConfig = null;
            RevenueConfig nextLevelConfig = null;
            
            for (RevenueConfig config : allConfigs) {
                if (config.getLevel().equals(currentLevel)) {
                    currentLevelConfig = config;
                }
                if (config.getLevel().equals(currentLevel + 1)) {
                    nextLevelConfig = config;
                }
            }
            
            // 6. 设置当前等级信息
            if (currentLevelConfig != null) {
                status.setCurrentLevelName(currentLevelConfig.getLevelName());
                status.setCurrentLevelMinFans(currentLevelConfig.getMinFans());
                status.setCurrentCommissionRate(formatCommissionRate(currentLevelConfig.getCommissionRate()));
            } else {
                status.setCurrentLevelName("等级" + currentLevel);
                status.setCurrentLevelMinFans(0);
                status.setCurrentCommissionRate(BigDecimal.ZERO);
            }
            
            // 7. 设置下一等级信息
            if (nextLevelConfig != null) {
                status.setNextLevel(nextLevelConfig.getLevel());
                status.setNextLevelName(nextLevelConfig.getLevelName());
                status.setNextLevelMinFans(nextLevelConfig.getMinFans());
                status.setNextCommissionRate(formatCommissionRate(nextLevelConfig.getCommissionRate()));
                
                // 计算距离下一等级还需要的粉丝数（基于总粉丝数）
                int fansToNext = Math.max(0, nextLevelConfig.getMinFans() - totalFansCount);
                status.setFansToNextLevel(fansToNext);
                status.setIsMaxLevel(false);
            } else {
                status.setIsMaxLevel(true);
                status.setFansToNextLevel(0);
            }
            
            // 8. 生成带状态的推广等级列表
            List<PromotionRuleDto.PromotionLevelWithStatus> levelsWithStatus = new ArrayList<>();
            
            for (RevenueConfig config : allConfigs) {
                PromotionRuleDto.PromotionLevelWithStatus levelWithStatus = new PromotionRuleDto.PromotionLevelWithStatus();
                levelWithStatus.setLevel(config.getLevel());
                levelWithStatus.setLevelName(config.getLevelName());
                levelWithStatus.setMinFans(config.getMinFans());
                levelWithStatus.setCommissionRate(formatCommissionRate(config.getCommissionRate()));
                levelWithStatus.setDescription(config.getDescription());
                
                // 设置状态信息（基于总粉丝数）
                levelWithStatus.setIsCurrent(config.getLevel().equals(currentLevel));
                levelWithStatus.setIsAchieved(totalFansCount >= config.getMinFans());
                
                // 计算达成进度百分比（基于总粉丝数）
                if (config.getMinFans() > 0) {
                    BigDecimal achievementRate = BigDecimal.valueOf(totalFansCount)
                            .multiply(new BigDecimal("100"))
                            .divide(BigDecimal.valueOf(config.getMinFans()), 1, RoundingMode.HALF_UP);
                    // 最大100%
                    levelWithStatus.setAchievementRate(achievementRate.min(new BigDecimal("100")));
                } else {
                    levelWithStatus.setAchievementRate(new BigDecimal("100"));
                }
                
                levelsWithStatus.add(levelWithStatus);
            }
            
            status.setPromotionLevelsWithStatus(levelsWithStatus);
            
            log.info("获取用户{}推广状态成功 - 当前等级: {}, 总粉丝: {}, 付费粉丝: {}", 
                    userId, currentLevel, totalFansCount, paidFansCount);
            
        } catch (Exception e) {
            log.error("获取用户推广状态失败 - userId: {}", userId, e);
            throw new IllegalStateException("获取用户推广状态失败: " + e.getMessage(), e);
        }
        
        return status;
    }
    
    /**
     * 根据总粉丝数量计算推广等级
     * 
     * @deprecated 此方法已废弃。现在直接使用数据库中存储的promotion_level字段，
     *             避免重复计算，提高系统性能。
     * @param totalFansCount 总粉丝数量
     * @param allConfigs 所有推广等级配置
     * @return 推广等级，默认返回1
     */
    @Deprecated
    private Integer calculatePromotionLevelByFans(int totalFansCount, List<RevenueConfig> allConfigs) {
        // 为了保持向后兼容，返回默认等级1
        // 现在推广等级直接从用户表的promotion_level字段读取
        log.debug("calculatePromotionLevelByFans方法已废弃，返回默认等级1 - totalFansCount: {}", totalFansCount);
        return 1;
    }
     
    /**
     * 格式化佣金比例
     * @param commissionRate 原始佣金比例
     * @return 格式化后的佣金比例（百分比显示）
     */
    private BigDecimal formatCommissionRate(BigDecimal commissionRate) {
        if (commissionRate == null) {
            return BigDecimal.ZERO;
        }
        
        // 如果值大于1，说明已经是百分比格式，直接使用
        // 如果值小于等于1，说明是小数格式，需要乘以100转换为百分比
        if (commissionRate.compareTo(BigDecimal.ONE) > 0) {
            return commissionRate;
        } else {
            return commissionRate.multiply(new BigDecimal("100"));
        }
    }

    /**
     * 获取类型名称
     * @param configType 配置类型
     * @return 类型名称
     */
    private String getTypeName(String configType) {
        if (configType == null) return "未知";
        switch (configType) {
            case "video": return "视频播放";
            case "workflow": return "工作流复制";
            default: return "未知";
        }
    }
} 