using Microsoft.Extensions.Logging;
using QYZH.InteractiveMagazine.Common.Extensions;
using QYZH.InteractiveMagazine.IService;
using QYZH.InteractiveMagazine.Models.Common;
using QYZH.InteractiveMagazine.Models.Dto;
using QYZH.InteractiveMagazine.Models.Entity;
using QYZH.InteractiveMagazine.Models.Enum;
using QYZH.InteractiveMagazine.Repository;
using SqlSugar;

namespace QYZH.InteractiveMagazine.Service;

/// <summary>
/// 社区消息后台管理服务实现
/// </summary>
public class CommunityMessageService(BaseRepository<CommunityMessage> messageRepository, ILogger<CommunityMessageService> logger)
    : BaseRepository<CommunityMessage>, ICommunityMessageService
{

    /// <summary>
    /// 分页查询消息列表
    /// </summary>
    public async Task<PageListModel<AdminMessageDetailOutput>> GetListAsync(AdminMessageQueryInput input)
    {
        logger.LogInformation("正在查询社区消息列表，页码: {PageIndex}, 每页条数: {PageSize}", input.PageIndex, input.PageSize);

        if (input.PageIndex <= 0) throw new BusinessException("页码必须大于0", ResultCode.BAD_REQUEST);
        if (input.PageSize <= 0 || input.PageSize > 100) throw new BusinessException("每页条数必须在1-100之间", ResultCode.BAD_REQUEST);

        RefAsync<int> totalNumber = 0;
        var pageResult = await messageRepository.Queryable()
            .WhereIF(input.JournalId.HasValue, m => m.JournalId == input.JournalId.Value)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Type), m => m.Type.ToString() == input.Type)
            .WhereIF(input.Status.HasValue, m => m.Status == input.Status.Value)
            .WhereIF(input.IsFeatured.HasValue, m => m.IsFeatured == input.IsFeatured.Value)
            .WhereIF(input.IsActive.HasValue, m => m.IsActive == input.IsActive.Value)
            .WhereIF(!string.IsNullOrWhiteSpace(input.KeyWord), m => m.Content.Contains(input.KeyWord))
            .WhereIF(input.UserId.HasValue, m => m.UserId == input.UserId.Value)
            .OrderByDescending(m => m.IsFeatured)
            .OrderByDescending(m => m.CreatedAt)
            .Select(m => new AdminMessageDetailOutput
            {
                Id = m.Id,
                JournalId = m.JournalId,
                UserId = m.UserId,
                UserJournalId = m.UserJournalId,
                JournalTaskId = m.JournalTaskId,
                JournalTaskAnswerId = m.JournalTaskAnswerId,
                Content = m.Content,
                ImageUrl = m.ImageUrl,
                SortOrder = m.SortOrder,
                IsActive = m.IsActive,
                Type = m.Type.ToString(),
                LikeCount = m.LikeCount,
                IsFeatured = m.IsFeatured,
                Status = m.Status,
                CreatedBy = m.CreatedBy,
                CreatedAt = m.CreatedAt,
                UpdatedBy = m.UpdatedBy,
                UpdatedAt = m.UpdatedAt
            }, true)
            .ToPageListAsync(input.PageIndex, input.PageSize, totalNumber);

        return new PageListModel<AdminMessageDetailOutput>(pageResult, input.PageIndex, input.PageSize, totalNumber);
    }

    /// <summary>
    /// 查看消息详情
    /// </summary>
    public async Task<AdminMessageDetailOutput> GetDetailAsync(long id)
    {
        logger.LogInformation("正在获取社区消息详情，ID: {Id}", id);

        var message = await messageRepository.GetByIdAsync(id);
        if (message == null)
        {
            logger.LogWarning("未找到社区消息，ID: {Id}", id);
            throw new BusinessException("消息不存在", ResultCode.NOT_FOUND);
        }

        return new AdminMessageDetailOutput
        {
            Id = message.Id,
            JournalId = message.JournalId,
            UserId = message.UserId,
            UserJournalId = message.UserJournalId,
            JournalTaskId = message.JournalTaskId,
            JournalTaskAnswerId = message.JournalTaskAnswerId,
            Content = message.Content,
            ImageUrl = message.ImageUrl,
            SortOrder = message.SortOrder,
            IsActive = message.IsActive,
            Type = message.Type.ToString(),
            LikeCount = message.LikeCount,
            IsFeatured = message.IsFeatured,
            Status = message.Status,
            CreatedBy = message.CreatedBy,
            CreatedAt = message.CreatedAt,
            UpdatedBy = message.UpdatedBy,
            UpdatedAt = message.UpdatedAt
        };
    }

    /// <summary>
    /// 软删除消息
    /// </summary>
    public async Task DeleteAsync(long id)
    {
        logger.LogInformation("正在删除社区消息，ID: {Id}", id);

        var message = await messageRepository.GetByIdAsync(id);
        if (message == null)
        {
            logger.LogWarning("未找到要删除的社区消息，ID: {Id}", id);
            throw new BusinessException("消息不存在", ResultCode.NOT_FOUND);
        }

        var result = await messageRepository.DeleteByIdAsync(id);
        if (!result)
        {
            logger.LogError("社区消息删除失败，ID: {Id}", id);
            throw new BusinessException("删除消息失败", ResultCode.GLOBAL_ERROR);
        }

        logger.LogInformation("社区消息删除成功，ID: {Id}", id);
    }

    /// <summary>
    /// 冻结/解冻消息
    /// </summary>
    public async Task FreezeAsync(long id, int status)
    {
        logger.LogInformation("正在更新社区消息冻结状态，ID: {Id}, Status: {Status}", id, status);

        if (status != 1 && status != 2)
        {
            throw new BusinessException("状态值无效，只能为1(解冻/通过)或2(冻结)", ResultCode.BAD_REQUEST);
        }

        var message = await messageRepository.GetByIdAsync(id);
        if (message == null)
        {
            logger.LogWarning("未找到社区消息，ID: {Id}", id);
            throw new BusinessException("消息不存在", ResultCode.NOT_FOUND);
        }

        message.Status = status;
        message.UpdatedBy = "System";
        message.UpdatedAt = DateTime.Now;

        var result = await messageRepository.UpdateAsync(message);
        if (!result)
        {
            logger.LogError("社区消息冻结状态更新失败，ID: {Id}", id);
            throw new BusinessException("更新冻结状态失败", ResultCode.GLOBAL_ERROR);
        }

        logger.LogInformation("社区消息冻结状态更新成功，ID: {Id}, Status: {Status}", id, status);
    }

    /// <summary>
    /// 设置/取消精选
    /// </summary>
    public async Task SetFeaturedAsync(long id, int isFeatured)
    {
        logger.LogInformation("正在设置社区消息精选状态，ID: {Id}, IsFeatured: {IsFeatured}", id, isFeatured);

        if (isFeatured != 0 && isFeatured != 1)
        {
            throw new BusinessException("精选值无效，只能为0(取消)或1(精选)", ResultCode.BAD_REQUEST);
        }

        var message = await messageRepository.GetByIdAsync(id);
        if (message == null)
        {
            logger.LogWarning("未找到社区消息，ID: {Id}", id);
            throw new BusinessException("消息不存在", ResultCode.NOT_FOUND);
        }

        message.IsFeatured = isFeatured;
        message.UpdatedBy = "System";
        message.UpdatedAt = DateTime.Now;

        var result = await messageRepository.UpdateAsync(message);
        if (!result)
        {
            logger.LogError("社区消息精选设置失败，ID: {Id}", id);
            throw new BusinessException("设置精选失败", ResultCode.GLOBAL_ERROR);
        }

        logger.LogInformation("社区消息精选设置成功，ID: {Id}, IsFeatured: {IsFeatured}", id, isFeatured);
    }

    /// <summary>
    /// 设置排序权重
    /// </summary>
    public async Task SetSortOrderAsync(long id, int sortOrder)
    {
        logger.LogInformation("正在设置社区消息排序权重，ID: {Id}, SortOrder: {SortOrder}", id, sortOrder);

        var message = await messageRepository.GetByIdAsync(id);
        if (message == null)
        {
            logger.LogWarning("未找到社区消息，ID: {Id}", id);
            throw new BusinessException("消息不存在", ResultCode.NOT_FOUND);
        }

        message.SortOrder = sortOrder;
        message.UpdatedBy = "System";
        message.UpdatedAt = DateTime.Now;

        var result = await messageRepository.UpdateAsync(message);
        if (!result)
        {
            logger.LogError("社区消息排序权重设置失败，ID: {Id}", id);
            throw new BusinessException("设置排序权重失败", ResultCode.GLOBAL_ERROR);
        }

        logger.LogInformation("社区消息排序权重设置成功，ID: {Id}, SortOrder: {SortOrder}", id, sortOrder);
    }

    /// <summary>
    /// 批量发布消息
    /// </summary>
    public async Task BatchPublishAsync(List<long> ids)
    {
        logger.LogInformation("正在批量发布社区消息，数量: {Count}", ids.Count);

        if (ids == null || ids.Count == 0)
        {
            throw new BusinessException("消息ID列表不能为空", ResultCode.BAD_REQUEST);
        }

        var result = await Context.Updateable<CommunityMessage>()
            .SetColumns(m => m.IsActive == true)
            .Where(m => ids.Contains(m.Id))
            .ExecuteCommandAsync();

        logger.LogInformation("批量发布社区消息完成，影响行数: {Result}", result);
    }
}
