using System.ComponentModel;
using System.Reflection;
using Microsoft.Extensions.Logging;
using QYZH.InteractiveMagazine.IService;
using QYZH.InteractiveMagazine.Models.Dto.SystemManagement;

namespace QYZH.InteractiveMagazine.Service;

/// <summary>
/// 系统管理服务实现
/// </summary>
public class SystemManagementService : ISystemManagementService
{
    private readonly ILogger<SystemManagementService> _logger;

    public SystemManagementService(ILogger<SystemManagementService> logger)
    {
        _logger = logger;
    }

    public Task<List<EnumInfoOutput>> GetAllEnumsAsync()
    {
        _logger.LogInformation("开始获取所有枚举信息");

        var enumAssembly = typeof(QYZH.InteractiveMagazine.Models.Enum.DefaultStatusEnum).Assembly;
        var enumNamespace = "QYZH.InteractiveMagazine.Models.Enum";

        var enumTypes = enumAssembly.GetTypes()
            .Where(t => t.IsEnum && t.Namespace == enumNamespace)
            .OrderBy(t => t.Name)
            .ToList();

        var result = new List<EnumInfoOutput>();

        foreach (var enumType in enumTypes)
        {
            var enumInfo = new EnumInfoOutput
            {
                EnumName = enumType.Name
            };

            var fields = Enum.GetValues(enumType)
                .Cast<object>()
                .Select(value => new
                {
                    Name = Enum.GetName(enumType, value),
                    Value = Convert.ToInt32(value),
                    Field = enumType.GetField(value.ToString()!)
                })
                .ToList();

            foreach (var field in fields)
            {
                var description = field.Field?
                    .GetCustomAttribute<DescriptionAttribute>()?
                    .Description;

                enumInfo.Items.Add(new EnumItemDto
                {
                    Name = field.Name!,
                    Value = field.Value,
                    Description = description
                });
            }

            result.Add(enumInfo);
        }

        _logger.LogInformation("获取枚举信息完成，共 {Count} 个枚举", result.Count);

        return Task.FromResult(result);
    }
}
