using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.Diamond;
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 DiamondService : IDiamondService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<DiamondService> _logger;

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

    /// <inheritdoc />
    public async Task<PagedResult<DiamondProductResponse>> GetDiamondProductsAsync(DiamondProductListRequest request)
    {
        var query = _dbContext.DiamondProducts.AsNoTracking();

        // 应用过滤条件
        if (!string.IsNullOrWhiteSpace(request.Name))
        {
            query = query.Where(p => p.Name.Contains(request.Name));
        }

        if (request.Status.HasValue)
        {
            query = query.Where(p => p.Status == request.Status.Value);
        }

        // 获取总数
        var total = await query.CountAsync();

        // 获取商品列表
        var products = await query
            .OrderByDescending(p => p.SortOrder)
            .ThenByDescending(p => p.Id)
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        // 映射结果
        var list = products.Select(MapToResponse).ToList();

        return PagedResult<DiamondProductResponse>.Create(list, total, request.Page, request.PageSize);
    }

    /// <inheritdoc />
    public async Task<DiamondProductResponse?> GetDiamondProductByIdAsync(int id)
    {
        var product = await _dbContext.DiamondProducts
            .AsNoTracking()
            .FirstOrDefaultAsync(p => p.Id == id);

        return product == null ? null : MapToResponse(product);
    }

    /// <inheritdoc />
    public async Task<int> CreateDiamondProductAsync(DiamondProductCreateRequest request)
    {
        // 验证必填字段
        ValidateRequest(request);

        var now = DateTime.Now;
        var product = new DiamondProduct
        {
            Name = request.Name,
            ProductsId = request.ProductsId,
            ProductsType = request.ProductsType,
            BaseReward = request.BaseReward,
            Price = request.Price,
            IsFirst = (byte)request.IsFirst,
            FirstBonusReward = request.FirstBonusReward,
            FirstChargeImage = request.FirstChargeImage,
            FirstSelectChargeImage = request.FirstSelectChargeImage,
            NormalImage = request.NormalImage,
            NormalSelectImage = request.NormalSelectImage,
            SortOrder = request.SortOrder,
            Status = (byte)request.Status,
            CreatedAt = now,
            UpdatedAt = now
        };

        _dbContext.DiamondProducts.Add(product);
        await _dbContext.SaveChangesAsync();

        _logger.LogInformation("创建钻石商品成功: Id={Id}, Name={Name}", product.Id, product.Name);

        return product.Id;
    }

    /// <inheritdoc />
    public async Task<bool> UpdateDiamondProductAsync(int id, DiamondProductUpdateRequest request)
    {
        var product = await _dbContext.DiamondProducts.FirstOrDefaultAsync(p => p.Id == id);
        if (product == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "钻石商品不存在");
        }

        // 验证必填字段
        ValidateRequest(request);

        product.Name = request.Name;
        product.ProductsId = request.ProductsId;
        product.ProductsType = request.ProductsType;
        product.BaseReward = request.BaseReward;
        product.Price = request.Price;
        product.IsFirst = (byte)request.IsFirst;
        product.FirstBonusReward = request.FirstBonusReward;
        product.FirstChargeImage = request.FirstChargeImage;
        product.FirstSelectChargeImage = request.FirstSelectChargeImage;
        product.NormalImage = request.NormalImage;
        product.NormalSelectImage = request.NormalSelectImage;
        product.SortOrder = request.SortOrder;
        product.Status = (byte)request.Status;
        product.UpdatedAt = DateTime.Now;

        var result = await _dbContext.SaveChangesAsync() > 0;

        _logger.LogInformation("更新钻石商品成功: Id={Id}, Name={Name}", id, product.Name);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> DeleteDiamondProductAsync(int id)
    {
        var product = await _dbContext.DiamondProducts.FirstOrDefaultAsync(p => p.Id == id);
        if (product == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "钻石商品不存在");
        }

        _dbContext.DiamondProducts.Remove(product);
        var result = await _dbContext.SaveChangesAsync() > 0;

        _logger.LogInformation("删除钻石商品成功: Id={Id}, Name={Name}", id, product.Name);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> UpdateDiamondProductStatusAsync(int id, int status)
    {
        var product = await _dbContext.DiamondProducts.FirstOrDefaultAsync(p => p.Id == id);
        if (product == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "钻石商品不存在");
        }

        var oldStatus = product.Status;
        product.Status = (byte)status;
        product.UpdatedAt = DateTime.Now;

        var result = await _dbContext.SaveChangesAsync() > 0;

        _logger.LogInformation("更新钻石商品状态: Id={Id}, OldStatus={OldStatus}, NewStatus={NewStatus}",
            id, oldStatus, status);

        return result;
    }

    /// <inheritdoc />
    public async Task<int> GetMaxSortOrderAsync()
    {
        var maxSort = await _dbContext.DiamondProducts.MaxAsync(p => (int?)p.SortOrder) ?? 0;
        return maxSort;
    }

    #region Private Helper Methods

    /// <summary>
    /// 验证请求参数
    /// </summary>
    private void ValidateRequest(DiamondProductCreateRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.Name))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "商品名称不能为空");
        }

        if (string.IsNullOrWhiteSpace(request.ProductsId))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "商品编号不能为空");
        }

        if (request.Price <= 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "价格必须大于0");
        }

        if (string.IsNullOrWhiteSpace(request.BaseReward))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "基础奖励不能为空");
        }
    }

    /// <summary>
    /// 映射实体到响应模型
    /// </summary>
    private DiamondProductResponse MapToResponse(DiamondProduct product)
    {
        return new DiamondProductResponse
        {
            Id = product.Id,
            Name = product.Name,
            ProductsId = product.ProductsId,
            ProductsType = product.ProductsType,
            BaseReward = product.BaseReward,
            Price = product.Price,
            IsFirst = product.IsFirst ?? 0,
            FirstBonusReward = product.FirstBonusReward,
            FirstChargeImage = product.FirstChargeImage,
            FirstSelectChargeImage = product.FirstSelectChargeImage,
            NormalImage = product.NormalImage,
            NormalSelectImage = product.NormalSelectImage,
            SortOrder = product.SortOrder ?? 0,
            Status = product.Status ?? 0,
            CreatedAt = product.CreatedAt,
            UpdatedAt = product.UpdatedAt
        };
    }

    #endregion
}
