Files
jinko.yikatong/Src/Dlhis.Common/EnumSetting/EnumsController.cs
2024-03-18 15:09:16 +08:00

104 lines
3.0 KiB
C#

using System.Reflection;
using Dlhis.Common.FileOperation.Response;
using Dlhis.Entity.Basic.Entity;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.SqlSugar.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Common.EnumSetting;
/// <summary>
/// 枚举
/// </summary>
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class EnumsController : ControllerBase
{
private readonly IDbContext _dbContext;
public EnumsController(IDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// 获取所有枚举/基础类型
/// </summary>
/// <param name="code">code</param>
/// <returns></returns>
[HttpGet]
public List<CommonEnumResponse> GetEnums(string code)
{
var types = Assembly.Load("Dlhis.Entity")
.GetTypes()
.Where(x => x.IsEnum);
var result = types.Select(x =>
{
var d = x.GetDescription();
return new CommonEnumResponse
{
Code = x.Name,
Name = d,
Data = x.GetFields(BindingFlags.Public | BindingFlags.Static).Select(item =>
{
var e = (Enum)Enum.Parse(item.FieldType, item.GetValue(null).ToString());
var fd = e.GetDescription();
return new KeyValueDto
{
Key = fd,
Value = (int)item.GetValue(null)
};
}).ToList()
};
})
.ToList();
var dbTypes = _dbContext.Queryable<BasicTypeEntity>().OrderBy(x => x.Sequence).ToList();
var dbResult = dbTypes.GroupBy(x => x.Type).Select(g =>
{
var type = g.Key;
return new CommonEnumResponse
{
Code = type,
Name = type,
Data = g.AsEnumerable().Select(x => new KeyValueDto
{
Key = x.Code,
Value = x.Display
})
.ToList()
};
});
result.AddRange(dbResult);
result.Add(GetCurrentEnums("LogLevel", "日志级别", typeof(LogLevel)));
return result.WhereIf(code.IsPresent(), x => x.Code == code).ToList();
}
private static CommonEnumResponse GetCurrentEnums(string code, string name, Type enumType)
{
return new CommonEnumResponse
{
Code = code,
Name = name,
Data = enumType.GetFields(BindingFlags.Public | BindingFlags.Static).Select(item =>
{
var e = (Enum)Enum.Parse(item.FieldType, item.GetValue(null).ToString());
var fd = e.GetDescription();
return new KeyValueDto
{
Key = fd,
Value = (int)item.GetValue(null)
};
})
.ToList()
};
}
}