package com.dora.service.impl;

import com.dora.entity.PromotionLevelConfig;
import com.dora.entity.RevenueConfig;
import com.dora.entity.User;
import com.dora.mapper.RevenueConfigMapper;
import com.dora.mapper.UserMapper;
import com.dora.service.PromotionLevelService;
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.util.List;
import java.util.stream.Collectors;

/**
 * 推广等级服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class PromotionLevelServiceImpl implements PromotionLevelService {

    private final RevenueConfigMapper revenueConfigMapper;
    private final UserMapper userMapper;

    @Override
    public List<PromotionLevelConfig> getAllPromotionLevels() {
        // 从 revenue_config 表读取推广等级配置
        List<RevenueConfig> revenueConfigs = revenueConfigMapper.selectByConfigType("promotion");
        
        // 转换为 PromotionLevelConfig 对象以保持接口兼容
        return revenueConfigs.stream()
                .map(this::convertToPromotionLevelConfig)
                .collect(Collectors.toList());
    }

    @Override
    public int calculatePromotionLevel(int paidFansCount) {
        // 从 revenue_config 表查找匹配的推广等级
        List<RevenueConfig> configs = revenueConfigMapper.selectByConfigType("promotion");
        
        // 按粉丝数要求倒序排列，找到第一个满足条件的等级
        RevenueConfig matchedConfig = configs.stream()
                .filter(config -> config.getMinFans() != null && paidFansCount >= config.getMinFans())
                .sorted((a, b) -> Integer.compare(b.getMinFans(), a.getMinFans())) // 倒序排序
                .findFirst()
                .orElse(null);
                
        return matchedConfig != null ? matchedConfig.getLevel() : 1; // 默认返回1级
    }

    /**
     * @deprecated 此方法已废弃。根据新的设计，推广等级仅在用户注册时更新，
     *             避免重复计算，提高系统性能。请使用PromotionLevelCalculator.updateUserPromotionLevelOnRegistration()
     */
    @Override
    @Transactional
    @Deprecated
    public void updateUserPromotionLevel(Long userId) {
        // 为了保持向后兼容，此方法不再执行实际的等级更新操作
        // 推广等级现在仅在用户注册时更新，以提高系统性能
        log.debug("updateUserPromotionLevel方法已废弃，不再执行等级更新操作 - userId: {}", userId);
        
        // 原有逻辑已停用，避免重复计算：
        // int paidFansCount = userMapper.countPaidFansByInviterId(userId);
        // int newLevel = calculatePromotionLevel(paidFansCount);
        // ...更新逻辑...
    }

    @Override
    public PromotionLevelConfig getUserCurrentLevelConfig(Long userId) {
        User user = userMapper.selectById(userId);
        Integer currentLevel = user != null ? user.getPromotionLevel() : 1; // 默认1级
        
        // 从 revenue_config 表查找对应等级的配置
        RevenueConfig revenueConfig = revenueConfigMapper.selectByConfigTypeAndLevel("promotion", currentLevel);
        return revenueConfig != null ? convertToPromotionLevelConfig(revenueConfig) : null;
    }

    @Override
    public PromotionLevelConfig getUserNextLevelConfig(Long userId) {
        User user = userMapper.selectById(userId);
        Integer currentLevel = user != null ? user.getPromotionLevel() : 1; // 默认1级
        
        // 从 revenue_config 表查找下一等级的配置
        RevenueConfig nextConfig = revenueConfigMapper.selectNextLevelConfig("promotion", currentLevel);
        return nextConfig != null ? convertToPromotionLevelConfig(nextConfig) : null;
    }

    @Override
    public int getFansToNextLevel(Long userId) {
        // 获取用户当前付费粉丝数
        int paidFansCount = userMapper.countPaidFansByInviterId(userId);
        
        // 获取下一等级配置
        PromotionLevelConfig nextLevelConfig = getUserNextLevelConfig(userId);
        
        if (nextLevelConfig == null) {
            return 0; // 已经是最高等级
        }
        
        int fansToNextLevel = nextLevelConfig.getMinPaidFans() - paidFansCount;
        return Math.max(0, fansToNextLevel);
    }
    
    /**
     * 将 RevenueConfig 转换为 PromotionLevelConfig 以保持接口兼容性
     */
    private PromotionLevelConfig convertToPromotionLevelConfig(RevenueConfig revenueConfig) {
        PromotionLevelConfig config = new PromotionLevelConfig();
        config.setId(revenueConfig.getLevel() != null ? Long.valueOf(revenueConfig.getLevel()) : null);
        config.setLevelName(revenueConfig.getLevelName());
        config.setMinPaidFans(revenueConfig.getMinFans());
        config.setCommissionRate(revenueConfig.getCommissionRate());
        config.setCreateTime(revenueConfig.getCreateTime());
        config.setUpdateTime(revenueConfig.getUpdateTime());
        config.setIsDeleted(revenueConfig.getIsDeleted());
        return config;
    }
} 