using HoneyBox.Admin.Business.Models.Dashboard;
using HoneyBox.Admin.Business.Services.Interfaces;
using HoneyBox.Model.Data;
using HoneyBox.Model.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace HoneyBox.Admin.Business.Services;

/// <summary>
/// 仪表盘服务实现
/// </summary>
public class DashboardService : IDashboardService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<DashboardService> _logger;

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

    /// <summary>
    /// 获取仪表盘概览数据
    /// </summary>
    public async Task<DashboardOverviewResponse> GetOverviewAsync()
    {
        var today = DateTime.Today;
        var tomorrow = today.AddDays(1);

        // 今日注册用户数
        var todayRegistrations = await _dbContext.Users
            .CountAsync(u => u.CreatedAt >= today && u.CreatedAt < tomorrow);

        // 今日消费金额
        var todayConsumption = await _dbContext.Orders
            .Where(o => o.Status == 1 && o.CreatedAt >= today && o.CreatedAt < tomorrow)
            .SumAsync(o => (decimal?)o.Price) ?? 0;

        // 今日新消费用户数（今日首次消费的用户）
        var todayNewConsumers = await _dbContext.Orders
            .Where(o => o.Status == 1 && o.CreatedAt >= today && o.CreatedAt < tomorrow)
            .Select(o => o.UserId)
            .Distinct()
            .CountAsync(userId => !_dbContext.Orders
                .Any(o2 => o2.UserId == userId && o2.Status == 1 && o2.CreatedAt < today));

        // 总广告收入（基于订单中的广告ID统计）
        var totalAdRevenue = await _dbContext.Orders
            .Where(o => o.Status == 1 && o.AdId != null && o.AdId > 0)
            .SumAsync(o => (decimal?)o.Price) ?? 0;

        // 总用户数
        var totalUsers = await _dbContext.Users.CountAsync();

        // 总订单数
        var totalOrders = await _dbContext.Orders.CountAsync(o => o.Status == 1);

        // 总消费金额
        var totalConsumption = await _dbContext.Orders
            .Where(o => o.Status == 1)
            .SumAsync(o => (decimal?)o.Price) ?? 0;

        return new DashboardOverviewResponse
        {
            TodayRegistrations = todayRegistrations,
            TodayConsumption = todayConsumption,
            TodayNewConsumers = todayNewConsumers,
            TotalAdRevenue = totalAdRevenue,
            TotalUsers = totalUsers,
            TotalOrders = totalOrders,
            TotalConsumption = totalConsumption
        };
    }

    /// <summary>
    /// 获取广告账户列表
    /// </summary>
    public async Task<List<AdAccountDto>> GetAdAccountsAsync()
    {
        var adverts = await _dbContext.Adverts
            .OrderBy(a => a.Sort)
            .ThenByDescending(a => a.Id)
            .ToListAsync();

        return adverts.Select(a => new AdAccountDto
        {
            Id = a.Id,
            ImgUrl = a.ImgUrl,
            Url = a.Url,
            Sort = a.Sort,
            Type = a.Type,
            Ttype = a.Ttype,
            CouponId = a.CouponId,
            GoodsId = a.GoodsId,
            CreatedAt = a.CreatedAt,
            UpdatedAt = a.UpdatedAt
        }).ToList();
    }

    /// <summary>
    /// 创建广告账户
    /// </summary>
    public async Task<int> CreateAdAccountAsync(AdAccountCreateRequest request)
    {
        var advert = new Advert
        {
            ImgUrl = request.ImgUrl,
            Url = request.Url,
            Sort = request.Sort,
            Type = request.Type,
            Ttype = request.Ttype,
            CouponId = request.CouponId,
            GoodsId = request.GoodsId,
            CreatedAt = DateTime.Now,
            UpdatedAt = DateTime.Now
        };

        _dbContext.Adverts.Add(advert);
        await _dbContext.SaveChangesAsync();

        _logger.LogInformation("Created ad account: {Id}", advert.Id);

        return advert.Id;
    }

    /// <summary>
    /// 删除广告账户
    /// </summary>
    public async Task<bool> DeleteAdAccountAsync(int id)
    {
        var advert = await _dbContext.Adverts.FindAsync(id);
        if (advert == null)
        {
            return false;
        }

        _dbContext.Adverts.Remove(advert);
        await _dbContext.SaveChangesAsync();

        _logger.LogInformation("Deleted ad account: {Id}", id);

        return true;
    }
}
