using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.Task;
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 AdminTaskService : IAdminTaskService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<AdminTaskService> _logger;

    /// <summary>
    /// 任务类型名称映射
    /// </summary>
    private static readonly Dictionary<int, string> TaskTypeNames = new()
    {
        { 1, "每日任务" },
        { 2, "每周任务" }
    };

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

    /// <inheritdoc />
    public async Task<PagedResult<TaskResponse>> GetTasksAsync(TaskListRequest request)
    {
        var query = _dbContext.Tasks
            .AsNoTracking()
            .Where(t => t.DeletedAt == null);

        // 按关键词搜索（搜索标题）
        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            query = query.Where(t => t.Title.Contains(request.Keyword));
        }

        // 按任务类型筛选
        if (request.Type.HasValue)
        {
            query = query.Where(t => t.Type == request.Type.Value);
        }

        var total = await query.CountAsync();

        var items = await query
            .OrderBy(t => t.Sort ?? 0)
            .ThenByDescending(t => t.CreatedAt)
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        var list = items.Select(MapToResponse).ToList();

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

    /// <inheritdoc />
    public async Task<TaskResponse?> GetTaskByIdAsync(int id)
    {
        var entity = await _dbContext.Tasks
            .AsNoTracking()
            .FirstOrDefaultAsync(t => t.Id == id && t.DeletedAt == null);

        if (entity == null)
        {
            return null;
        }

        return MapToResponse(entity);
    }

    /// <inheritdoc />
    public async Task<int> CreateTaskAsync(TaskCreateRequest request)
    {
        // 验证请求
        ValidateCreateRequest(request);

        var entity = new T_Task
        {
            Title = request.Title,
            Type = (byte)request.Type,
            Cate = (byte)request.Cate,
            IsImportant = request.IsImportant.HasValue ? (byte?)request.IsImportant.Value : null,
            Number = request.Number,
            ZNumber = request.ZNumber,
            Sort = request.Sort,
            CreatedAt = DateTime.Now,
            UpdatedAt = DateTime.Now
        };

        _dbContext.Tasks.Add(entity);
        await _dbContext.SaveChangesAsync();

        _logger.LogInformation("创建任务成功: Id={Id}, Title={Title}, Type={Type}",
            entity.Id, entity.Title, entity.Type);

        return entity.Id;
    }

    /// <inheritdoc />
    public async Task<bool> UpdateTaskAsync(int id, TaskUpdateRequest request)
    {
        var entity = await _dbContext.Tasks
            .FirstOrDefaultAsync(t => t.Id == id && t.DeletedAt == null);

        if (entity == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "任务不存在");
        }

        // 验证请求
        ValidateUpdateRequest(request);

        entity.Title = request.Title;
        entity.Type = (byte)request.Type;
        entity.Cate = (byte)request.Cate;
        entity.IsImportant = request.IsImportant.HasValue ? (byte?)request.IsImportant.Value : null;
        entity.Number = request.Number;
        entity.ZNumber = request.ZNumber;
        entity.Sort = request.Sort;
        entity.UpdatedAt = DateTime.Now;

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

        _logger.LogInformation("更新任务成功: Id={Id}", id);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> DeleteTaskAsync(int id)
    {
        var entity = await _dbContext.Tasks
            .FirstOrDefaultAsync(t => t.Id == id && t.DeletedAt == null);

        if (entity == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "任务不存在");
        }

        // 软删除
        entity.DeletedAt = DateTime.Now;
        entity.UpdatedAt = DateTime.Now;

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

        _logger.LogInformation("删除任务成功: Id={Id}", id);

        return result;
    }

    #region Private Helper Methods

    /// <summary>
    /// 验证创建请求
    /// </summary>
    private void ValidateCreateRequest(TaskCreateRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.Title))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "任务标题不能为空");
        }

        if (request.Type < 1 || request.Type > 2)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "任务类型必须为1（每日任务）或2（每周任务）");
        }

        if (request.Number <= 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "任务次数必须大于0");
        }

        if (request.ZNumber <= 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "奖励数量（欧气值）必须大于0");
        }
    }

    /// <summary>
    /// 验证更新请求
    /// </summary>
    private void ValidateUpdateRequest(TaskUpdateRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.Title))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "任务标题不能为空");
        }

        if (request.Type < 1 || request.Type > 2)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "任务类型必须为1（每日任务）或2（每周任务）");
        }

        if (request.Number <= 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "任务次数必须大于0");
        }

        if (request.ZNumber <= 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "奖励数量（欧气值）必须大于0");
        }
    }

    /// <summary>
    /// 将实体映射为响应模型
    /// </summary>
    private static TaskResponse MapToResponse(T_Task entity)
    {
        return new TaskResponse
        {
            Id = entity.Id,
            Title = entity.Title,
            Type = entity.Type,
            TypeName = TaskTypeNames.GetValueOrDefault(entity.Type, "未知"),
            Cate = entity.Cate,
            IsImportant = entity.IsImportant,
            Number = entity.Number,
            ZNumber = entity.ZNumber,
            Sort = entity.Sort,
            CreatedAt = entity.CreatedAt,
            UpdatedAt = entity.UpdatedAt
        };
    }

    #endregion
}
