using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Data;
using HoneyBox.Model.Entities;
using HoneyBox.Model.Models.Equity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace HoneyBox.Core.Services;

/// <summary>
/// 权益服务实现
/// </summary>
public class EquityService : IEquityService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<EquityService> _logger;

    public EquityService(HoneyBoxDbContext dbContext, ILogger<EquityService> logger)
    {
        _dbContext = dbContext;
        _logger = logger;
    }

    /// <inheritdoc />
    public async Task<EquityInfoResponse> GetEquityInfoAsync(int userId)
    {
        // 获取用户信息
        var user = await _dbContext.Users
            .Where(u => u.Id == userId)
            .Select(u => new { u.Id, u.Nickname, u.HeadImg, u.Vip })
            .FirstOrDefaultAsync();

        if (user == null)
        {
            throw new InvalidOperationException("用户不存在");
        }

        // 计算并更新权益等级
        var currentLevel = await CalculateEquityLevelAsync(userId, user.Vip);

        // 获取所有权益等级列表
        var equityLevels = await _dbContext.EquityLevels
            .Where(v => v.DeletedAt == null)
            .OrderBy(v => v.Level)
            .ToListAsync();

        // 获取最大权益等级
        var maxLevel = equityLevels.Any() ? equityLevels.Max(v => v.Level) : 0;

        // 构建用户权益信息
        var userInfo = new EquityUserInfoDto
        {
            Nickname = user.Nickname,
            Headimg = user.HeadImg,
            Vip = currentLevel,
            UpgradeMoney = "0",
            LastVip = 0,
            JinDu = 0,
            Notice = string.Empty
        };

        // 如果未达到最高等级，计算升级进度
        if (currentLevel < maxLevel)
        {
            // 计算累计消费
            var totalOrder = await GetTotalOrderConsumptionAsync(userId);

            // 获取下一个权益等级的条件
            var nextLevel = equityLevels
                .Where(v => v.Level > currentLevel)
                .OrderBy(v => v.Level)
                .FirstOrDefault();

            if (nextLevel != null)
            {
                var upgradeMoney = nextLevel.Number - totalOrder;
                userInfo.UpgradeMoney = upgradeMoney > 0 ? upgradeMoney.ToString("F2") : "0";
                userInfo.LastVip = nextLevel.Level;

                // 计算进度百分比
                if (totalOrder >= nextLevel.Number)
                {
                    userInfo.JinDu = 100;
                }
                else if (nextLevel.Number > 0)
                {
                    userInfo.JinDu = Math.Round((decimal)totalOrder / nextLevel.Number * 100, 2);
                }
            }
        }
        else
        {
            userInfo.UpgradeMoney = "0";
            userInfo.LastVip = 0;
            userInfo.JinDu = 100;
        }

        // 获取当前等级的提示信息
        var currentLevelInfo = equityLevels.FirstOrDefault(v => v.Level == currentLevel);
        if (currentLevelInfo != null)
        {
            userInfo.Notice = currentLevelInfo.Title;
        }

        // 构建权益等级列表DTO
        var levelDtos = equityLevels.Select(v => new EquityLevelDto
        {
            Id = v.Id,
            Level = v.Level,
            Title = v.Title,
            Imgurl = string.Empty,
            Condition = v.Number,
            Discount = 0,
            Notice = v.Title
        }).ToList();

        return new EquityInfoResponse
        {
            Userinfo = userInfo,
            Data = levelDtos
        };
    }

    /// <inheritdoc />
    public async Task<int> CalculateEquityLevelAsync(int userId, int currentLevel)
    {
        // 计算累计消费
        var totalOrder = await GetTotalOrderConsumptionAsync(userId);

        // 查找符合升级条件的最高等级
        // 条件：等级 > 当前等级 且 升级条件 <= 累计消费
        var newLevel = await _dbContext.EquityLevels
            .Where(v => v.DeletedAt == null)
            .Where(v => v.Level > currentLevel)
            .Where(v => v.Number <= totalOrder)
            .OrderByDescending(v => v.Level)
            .FirstOrDefaultAsync();

        if (newLevel != null)
        {
            // 更新用户权益等级
            var user = await _dbContext.Users.FindAsync(userId);
            if (user != null)
            {
                user.Vip = (byte)newLevel.Level;
                await _dbContext.SaveChangesAsync();
                _logger.LogInformation("用户 {UserId} 权益等级从 {OldLevel} 升级到 {NewLevel}", 
                    userId, currentLevel, newLevel.Level);
            }
            return newLevel.Level;
        }

        return currentLevel;
    }

    /// <inheritdoc />
    public async Task<List<EquityLevelDto>> GetEquityLevelsAsync()
    {
        var equityLevels = await _dbContext.EquityLevels
            .Where(v => v.DeletedAt == null)
            .OrderBy(v => v.Level)
            .ToListAsync();

        return equityLevels.Select(v => new EquityLevelDto
        {
            Id = v.Id,
            Level = v.Level,
            Title = v.Title,
            Imgurl = string.Empty,
            Condition = v.Number,
            Discount = 0,
            Notice = v.Title
        }).ToList();
    }

    /// <summary>
    /// 获取用户累计订单消费金额
    /// </summary>
    private async Task<decimal> GetTotalOrderConsumptionAsync(int userId)
    {
        // 计算累计消费：status=1（已支付）且 order_type<5
        var totalOrder = await _dbContext.Orders
            .Where(o => o.UserId == userId)
            .Where(o => o.Status == 1)
            .Where(o => o.OrderType < 5)
            .SumAsync(o => o.OrderTotal);

        return totalOrder;
    }
}
