using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.Announcement;
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 AnnouncementService : IAnnouncementService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<AnnouncementService> _logger;

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

    /// <inheritdoc />
    public async Task<PagedResult<AnnouncementAdminDto>> GetListAsync(int page = 1, int pageSize = 20, string? keyword = null)
    {
        var query = _dbContext.PrizeAnnouncements.AsNoTracking();

        // 关键词搜索
        if (!string.IsNullOrWhiteSpace(keyword))
        {
            query = query.Where(a => a.UserName.Contains(keyword) || a.PrizeName.Contains(keyword));
        }

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

        // 分页查询，按排序值升序、创建时间降序
        var list = await query
            .OrderBy(a => a.Sort)
            .ThenByDescending(a => a.CreatedAt)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        var dtoList = list.Select(MapToDto).ToList();

        return PagedResult<AnnouncementAdminDto>.Create(dtoList, total, page, pageSize);
    }

    /// <inheritdoc />
    public async Task<AnnouncementAdminDto> GetByIdAsync(int id)
    {
        var announcement = await _dbContext.PrizeAnnouncements
            .AsNoTracking()
            .FirstOrDefaultAsync(a => a.Id == id);

        if (announcement == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "公告不存在");
        }

        return MapToDto(announcement);
    }


    /// <inheritdoc />
    public async Task<AnnouncementAdminDto> CreateAsync(CreateAnnouncementRequest request)
    {
        // 验证必填字段
        ValidateRequiredFields(request.UserName, request.PrizeLevel, request.PrizeName);

        var now = DateTime.Now;
        var announcement = new PrizeAnnouncement
        {
            UserAvatar = request.UserAvatar,
            UserName = request.UserName,
            PrizeLevel = request.PrizeLevel,
            PrizeName = request.PrizeName,
            Sort = request.Sort,
            IsEnabled = request.IsEnabled,
            CreatedAt = now,
            UpdatedAt = now
        };

        _dbContext.PrizeAnnouncements.Add(announcement);
        await _dbContext.SaveChangesAsync();

        _logger.LogInformation(
            "创建中奖公告成功: Id={Id}, UserName={UserName}, PrizeName={PrizeName}",
            announcement.Id, announcement.UserName, announcement.PrizeName);

        return MapToDto(announcement);
    }

    /// <inheritdoc />
    public async Task<AnnouncementAdminDto> UpdateAsync(int id, UpdateAnnouncementRequest request)
    {
        var announcement = await _dbContext.PrizeAnnouncements
            .FirstOrDefaultAsync(a => a.Id == id);

        if (announcement == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "公告不存在");
        }

        // 更新字段（只更新非null的字段）
        if (request.UserAvatar != null)
        {
            announcement.UserAvatar = request.UserAvatar;
        }

        if (request.UserName != null)
        {
            if (string.IsNullOrWhiteSpace(request.UserName))
            {
                throw new BusinessException(BusinessErrorCodes.ValidationFailed, "用户名称不能为空");
            }
            announcement.UserName = request.UserName;
        }

        if (request.PrizeLevel != null)
        {
            if (string.IsNullOrWhiteSpace(request.PrizeLevel))
            {
                throw new BusinessException(BusinessErrorCodes.ValidationFailed, "奖品等级不能为空");
            }
            announcement.PrizeLevel = request.PrizeLevel;
        }

        if (request.PrizeName != null)
        {
            if (string.IsNullOrWhiteSpace(request.PrizeName))
            {
                throw new BusinessException(BusinessErrorCodes.ValidationFailed, "奖品名称不能为空");
            }
            announcement.PrizeName = request.PrizeName;
        }

        if (request.Sort.HasValue)
        {
            announcement.Sort = request.Sort.Value;
        }

        if (request.IsEnabled.HasValue)
        {
            announcement.IsEnabled = request.IsEnabled.Value;
        }

        announcement.UpdatedAt = DateTime.Now;

        await _dbContext.SaveChangesAsync();

        _logger.LogInformation(
            "更新中奖公告成功: Id={Id}, UserName={UserName}",
            id, announcement.UserName);

        return MapToDto(announcement);
    }

    /// <inheritdoc />
    public async Task<bool> DeleteAsync(int id)
    {
        var announcement = await _dbContext.PrizeAnnouncements
            .FirstOrDefaultAsync(a => a.Id == id);

        if (announcement == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "公告不存在");
        }

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

        _logger.LogInformation(
            "删除中奖公告成功: Id={Id}, UserName={UserName}, PrizeName={PrizeName}",
            id, announcement.UserName, announcement.PrizeName);

        return result;
    }

    /// <inheritdoc />
    public async Task<AnnouncementAdminDto> ToggleStatusAsync(int id)
    {
        var announcement = await _dbContext.PrizeAnnouncements
            .FirstOrDefaultAsync(a => a.Id == id);

        if (announcement == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "公告不存在");
        }

        announcement.IsEnabled = !announcement.IsEnabled;
        announcement.UpdatedAt = DateTime.Now;

        await _dbContext.SaveChangesAsync();

        _logger.LogInformation(
            "切换中奖公告状态成功: Id={Id}, IsEnabled={IsEnabled}",
            id, announcement.IsEnabled);

        return MapToDto(announcement);
    }

    #region Private Helper Methods

    /// <summary>
    /// 验证必填字段
    /// </summary>
    private static void ValidateRequiredFields(string userName, string prizeLevel, string prizeName)
    {
        if (string.IsNullOrWhiteSpace(userName))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "用户名称不能为空");
        }

        if (string.IsNullOrWhiteSpace(prizeLevel))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "奖品等级不能为空");
        }

        if (string.IsNullOrWhiteSpace(prizeName))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "奖品名称不能为空");
        }
    }

    /// <summary>
    /// 映射实体到DTO
    /// </summary>
    private static AnnouncementAdminDto MapToDto(PrizeAnnouncement entity)
    {
        return new AnnouncementAdminDto
        {
            Id = entity.Id,
            UserAvatar = entity.UserAvatar ?? string.Empty,
            UserName = entity.UserName,
            PrizeLevel = entity.PrizeLevel,
            PrizeName = entity.PrizeName,
            Sort = entity.Sort,
            IsEnabled = entity.IsEnabled,
            CreatedAt = entity.CreatedAt,
            UpdatedAt = entity.UpdatedAt
        };
    }

    #endregion
}
