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

namespace HoneyBox.Core.Services;

/// <summary>
/// 资产服务实现
/// </summary>
public class AssetService : IAssetService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<AssetService> _logger;

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

    /// <inheritdoc />
    public async Task<AssetRecordPageResponse> GetMoneyRecordsAsync(int userId, int type, int page, int limit = 15)
    {
        _logger.LogInformation("获取余额明细: UserId={UserId}, Type={Type}, Page={Page}", userId, type, page);

        var query = _dbContext.ProfitMoneys.Where(p => p.UserId == userId);

        // 根据type参数过滤
        // type=0: 全部
        // type=1: 收入 (change_money > 0, type != 4)
        // type=2: 支出 (change_money < 0, type != 4)
        // type=3: 提现 (type = 4)
        query = type switch
        {
            1 => query.Where(p => p.Type != 4 && p.ChangeMoney > 0),
            2 => query.Where(p => p.Type != 4 && p.ChangeMoney < 0),
            3 => query.Where(p => p.Type == 4),
            _ => query
        };

        var totalCount = await query.CountAsync();
        var lastPage = (int)Math.Ceiling((double)totalCount / limit);
        if (lastPage < 1) lastPage = 1;

        var records = await query
            .OrderByDescending(p => p.Id)
            .Skip((page - 1) * limit)
            .Take(limit)
            .Select(p => new AssetRecordDto
            {
                ChangeMoney = p.ChangeMoney.ToString("0.##"),
                Content = p.Content,
                AddTime = p.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss")
            })
            .ToListAsync();

        return new AssetRecordPageResponse
        {
            List = records,
            LastPage = lastPage,
            CurrentPage = page,
            Total = totalCount
        };
    }

    /// <inheritdoc />
    public async Task<AssetRecordPageResponse> GetIntegralRecordsAsync(int userId, int type, int page, int limit = 15)
    {
        _logger.LogInformation("获取吧唧币明细: UserId={UserId}, Type={Type}, Page={Page}", userId, type, page);

        var query = _dbContext.ProfitIntegrals.Where(p => p.UserId == userId);

        // 根据type参数过滤
        // type=0: 全部
        // type=1: 收入 (change_money > 0)
        // type=2: 支出 (change_money < 0)
        query = type switch
        {
            1 => query.Where(p => p.ChangeMoney > 0),
            2 => query.Where(p => p.ChangeMoney < 0),
            _ => query
        };

        var totalCount = await query.CountAsync();
        var lastPage = (int)Math.Ceiling((double)totalCount / limit);
        if (lastPage < 1) lastPage = 1;

        var records = await query
            .OrderByDescending(p => p.Id)
            .Skip((page - 1) * limit)
            .Take(limit)
            .Select(p => new AssetRecordDto
            {
                ChangeMoney = p.ChangeMoney.ToString("0.##"),
                Content = p.Content,
                AddTime = p.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss")
            })
            .ToListAsync();

        return new AssetRecordPageResponse
        {
            List = records,
            LastPage = lastPage,
            CurrentPage = page,
            Total = totalCount
        };
    }

    /// <inheritdoc />
    public async Task<AssetRecordPageResponse> GetScoreRecordsAsync(int userId, int type, int page, int limit = 15)
    {
        _logger.LogInformation("获取积分明细: UserId={UserId}, Type={Type}, Page={Page}", userId, type, page);

        // 注意: PHP代码中profitScore查询的是ProfitMoney2表，不是ProfitScore表
        var query = _dbContext.ProfitMoney2s.Where(p => p.UserId == userId);

        // 根据type参数过滤
        // type=0: 全部
        // type=1: 收入 (change_money > 0)
        // type=2: 支出 (change_money < 0)
        query = type switch
        {
            1 => query.Where(p => p.ChangeMoney > 0),
            2 => query.Where(p => p.ChangeMoney < 0),
            _ => query
        };

        var totalCount = await query.CountAsync();
        var lastPage = (int)Math.Ceiling((double)totalCount / limit);
        if (lastPage < 1) lastPage = 1;

        var records = await query
            .OrderByDescending(p => p.Id)
            .Skip((page - 1) * limit)
            .Take(limit)
            .Select(p => new AssetRecordDto
            {
                ChangeMoney = p.ChangeMoney.ToString("0.##"),
                Content = p.Content,
                AddTime = p.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss")
            })
            .ToListAsync();

        return new AssetRecordPageResponse
        {
            List = records,
            LastPage = lastPage,
            CurrentPage = page,
            Total = totalCount
        };
    }

    /// <inheritdoc />
    public async Task<AssetRecordPageResponse> GetPayRecordsAsync(int userId, int page, int limit = 15)
    {
        _logger.LogInformation("获取支付记录: UserId={UserId}, Page={Page}", userId, page);

        var query = _dbContext.ProfitPays.Where(p => p.UserId == userId);

        var totalCount = await query.CountAsync();
        var lastPage = (int)Math.Ceiling((double)totalCount / limit);
        if (lastPage < 1) lastPage = 1;

        var records = await query
            .OrderByDescending(p => p.Id)
            .Skip((page - 1) * limit)
            .Take(limit)
            .Select(p => new AssetRecordDto
            {
                ChangeMoney = p.ChangeMoney.ToString("0.##"),
                Content = p.Content,
                AddTime = p.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss")
            })
            .ToListAsync();

        return new AssetRecordPageResponse
        {
            List = records,
            LastPage = lastPage,
            CurrentPage = page,
            Total = totalCount
        };
    }
}
