using CloudGaming.Code.AppExtend;
using CloudGaming.Code.DataAccess.MultiTenantUtil;
using HuanMeng.DotNetCore.MiddlewareExtend;
using HuanMeng.DotNetCore.CustomExtension;
using System.Diagnostics;

using System.Reflection;
using HuanMeng.DotNetCore.Utility.AssemblyHelper;
using HuanMeng.DotNetCore.SwaggerUtile;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Serilog;
using Newtonsoft.Json;
using CloudGaming.Code.AppExtend.JsonConverHelper.JsonConverterUtil;
using CloudGaming.Code.AppExtend.JsonConverHelper;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Options;
using CloudGaming.GameModel.Db.Db_Ext;
using CloudGaming.Code.MiddlewareExtend;
using CloudGaming.Code.Filter;
using CloudGaming.Code.Contract;
using Refit;
using CloudGaming.Code.JY;
using CloudGaming.Code.Extend;
var builder = WebApplication.CreateBuilder(args);
#region 日志
// Add services to the container.
builder.Host.UseSerilog((context, services, configuration) => configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext());

builder.Services.AddSingleton(typeof(ILogger<CloudGamingBase>), serviceProvider =>
{
    var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
    return loggerFactory.CreateLogger<CloudGamingBase>();
});
//
builder.Services.AddSingleton(typeof(ILogger<ExceptionMiddleware>), serviceProvider =>
{
    var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
    return loggerFactory.CreateLogger<ExceptionMiddleware>();
});
#endregion
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient();
builder.Services.AddHttpContextAccessor(); //添加httpContext注入访问

#region 返回数据解析   
//services.AddControllers(options =>
//{
//    // 添加自定义的 ResultFilter 到全局过滤器中
//    options.Filters.Add<CustomResultFilter>();
//});
builder.Services.AddControllers(options =>
{
    // 添加自定义的 ResultFilter 到全局过滤器中
    options.Filters.Add<CustomResultFilter>();
    options.Filters.Add<CustomExceptionFilter>();
})
    .AddNewtonsoftJson(options =>
    {
        // 配置 Newtonsoft.Json 选项
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // 忽略循环引用
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();// 首字母小写（驼峰样式）
        //options.SerializerSettings.ContractResolver = new LanguageContractResolver(builder.Services);
        options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";// 时间格式化
        options.SerializerSettings.Converters.Add(new StringConverter());
        // 设置序列化深度为3（这里你可以根据实际需求修改这个值）
        options.SerializerSettings.MaxDepth = 10;

        //options.SerializerSettings.ContractResolver =
#if !DEBUG
        options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
#endif
        //options.SerializerSettings.Converters.Add()
        // 其他配置...
    });
//CustomResultFilter
//builder.Services.AddSingleton<ObjectResultExecutor, CustomObjectResultExecutor>();

#endregion
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
#region jwt
builder.Services.AddSwaggerGen(c =>
{

    var securityScheme = new OpenApiSecurityScheme
    {
        Name = "JWT 身份验证（Authentication）",
        Description = "请输入登录后获取JWT的**token**",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Scheme = "bearer", //必须小写
        BearerFormat = "JWT",
        Reference = new OpenApiReference
        {
            Id = JwtBearerDefaults.AuthenticationScheme,
            Type = ReferenceType.SecurityScheme
        }
    };
    c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {securityScheme, Array.Empty<string>()}
    });
    string description = "";
    //.versionDescribe
    var filePath = Path.GetFullPath(".versionDescribe");
    if (File.Exists(filePath))
    {
        description = File.ReadAllText(filePath);
        //string[] lines = File.ReadAllLines(filePath);
        //foreach (string line in lines)
        //{
        //    if (line.Contains("##"))
        //    {
        //        description += $"**{line}**"; // 使用Markdown的加粗

        //    }
        //    else
        //    {
        //        description += line + "<br />";
        //    }
        //}
        //description = $"{description}";
    }
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "蒸汽云游戏", Version = "0.1.7", Description = description });
    foreach (var assemblies in AppDomain.CurrentDomain.GetAssemblies())
    {
        // 添加 XML 注释文件路径
        var xmlFile = $"{assemblies.GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        if (File.Exists(xmlPath))
        {
            c.IncludeXmlComments(xmlPath);
        }
    }
    c.ParameterFilter<LowercaseParameterFilter>();
    c.RequestBodyFilter<LowercaseRequestFilter>();
});

#endregion

#region  automap
var mapperDomain = AppDomain.CurrentDomain.GetAssemblies().Where(it => it.FullName.Contains("HuanMeng") || it.FullName.Contains("CloudGaming.")).ToList();
Type type = typeof(T_App_Config);
if (type != null)
{
    Assembly assembly = Assembly.GetAssembly(type);
    if (!mapperDomain.Any(it => it.FullName == assembly.FullName))
    {
        mapperDomain.Add(assembly);
    }
}

builder.Services.AddAutoMapper(mapperDomain);
#endregion

await builder.AddAppConfigClient();
//添加jwt验证
builder.AddJwtConfig();
#region 添加跨域
var _myAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCustomCors(_myAllowSpecificOrigins);
#endregion
builder.Services.AddScoped<JYApiHandler>();
// 配置 HttpClientFactory 和 Refit

builder.Services.AddRefitClient<IJYApi>()
    .AddHttpMessageHandler<JYApiHandler>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://default-api.example.com"));
//添加jwt验证
//builder.AddJwtConfig();

var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
//    app.UseSwagger();
//    app.UseSwaggerUI(); 
//}

app.UseSwagger();
app.UseSwaggerUI(c =>
{

    c.EnableDeepLinking();
    c.DefaultModelsExpandDepth(3);
    c.DefaultModelExpandDepth(3);
    c.EnableFilter("true");
    //c.RoutePrefix = string.Empty;
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "蒸汽云游戏 API V1");
    // 使用自定义CSS
    c.InjectStylesheet("/custom.css");
});

app.UseHttpsRedirection();

//注册身份验证中间件
app.UseAuthorization();
//数据库中间件
app.UseMultiTenant();
//使用跨域
app.UseCors(_myAllowSpecificOrigins);
app.MapControllers();
app.UseStaticFiles();//静态文件访问配置
//执行扩展中间件
app.UseMiddlewareAll();
//缓存中间件
app.UseCloudGamingMiddlewareAll();
#region 默认请求
app.UseAppRequest("api");
#endregion
app.Run();
