
using StackExchange.Redis;
using Autofac.Core;
using OASystem.API;
using OASystem.RedisRepository.RedisAsyncHelper;
using OASystem.RedisRepository.Config;
using OASystem.API.OAMethodLib;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using OASystem.API.OAMethodLib.JuHeAPI;
using OASystem.API.OAMethodLib.YouDaoAPI;
using Quartz.Impl;
using Quartz.Spi;
using Quartz;
using QuzrtzJob.Factory;
using System.Runtime.CompilerServices;
using OASystem.API.OAMethodLib.QiYeWeChatAPI;

var builder = WebApplication.CreateBuilder(args);
var basePath = AppContext.BaseDirectory;

//引入配置文件
var _config = new ConfigurationBuilder()
                 .SetBasePath(basePath)
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 .Build();
builder.Services.AddSingleton(new AppSettingsHelper(_config));

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        //空字段不响应Response
        //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;

        options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());

        //时间格式化响应
        options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));

        ////decimal 四位小数
        //options.JsonSerializerOptions.Converters.Add(new JsonConverterDecimal(0.0000M));
    });



#region Cors
builder.Services.AddCors(policy =>
{
    policy.AddPolicy("Cors", opt => opt
    .AllowAnyOrigin()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .WithExposedHeaders("X-Pagination"));
});
#endregion

#region 上传文件 
builder.Services.AddCors(policy =>
{
    policy.AddPolicy("Cors", opt => opt
    .AllowAnyOrigin()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .WithExposedHeaders("X-Pagination"));
});

builder.Services.Configure<FormOptions>(options =>
{
    options.KeyLengthLimit = int.MaxValue;
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = int.MaxValue;
    options.MultipartHeadersLengthLimit = int.MaxValue;
});

builder.Services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = int.MaxValue;
    options.Limits.MaxRequestBufferSize = int.MaxValue;
});

#endregion

#region 接口分组
var groups = new List<Tuple<string, string>>
{
    //new Tuple<string, string>("Group1","分组一"),
    //new Tuple<string, string>("Group2","分组二")
};
#endregion

#region 注入数据库
builder.Services.AddScoped(options =>
{
    return new SqlSugarClient(new List<ConnectionConfig>()
    {
        new ConnectionConfig() {
            ConfigId = DBEnum.OA2023DB,
            ConnectionString = _config.GetConnectionString("OA2023DB"),
            DbType = DbType.SqlServer, IsAutoCloseConnection = true },
        new ConnectionConfig()
        {
            ConfigId = DBEnum.OA2014DB,
            ConnectionString = _config.GetConnectionString("OA2014DB"),
            DbType = DbType.SqlServer, IsAutoCloseConnection = true },
    });
});
#endregion

#region 注入Swagger注释(启用)

if (AppSettingsHelper.Get("UseSwagger").ToBool())
{
    builder.Services.AddSwaggerGen(a =>
    {
        a.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "Api",
            Description = "Api接口文档"
        });
        foreach (var item in groups)
        {
            a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" });
        }
        a.DocumentFilter<SwaggerApi>();
        a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
        a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
        a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            Description = "Value: Bearer {token}",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer"
        });
        a.AddSecurityRequirement(new OpenApiSecurityRequirement()
        {{
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
            }
        });
    });
}
#endregion

#region 添加swagger注释
//if (AppSettingsHelper.Get("UseSwagger").ToBool())
//{
//    builder.Services.AddSwaggerGen(c =>
//    {
//        c.SwaggerDoc("v1", new OpenApiInfo
//        {
//            Version = "v1",
//            Title = "文华商旅支付测试接口",
//            Description = "请先从Auth鉴权=>login获取token进行认证,输入:token进行认证(Bearer)"
//        });
//        c.DocumentFilter<SwaggerApi>();
//        var xmlPath = Path.Combine(basePath, "OASystem.API.xml");
//        c.IncludeXmlComments(xmlPath, true);
//        var xmlDomainPath = Path.Combine(basePath, "OASystem.Domain.xml");
//        c.IncludeXmlComments(xmlDomainPath, true);
//        c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
//        {
//            Description = "Value: Bearer {token}",
//            Name = "Authorization",
//            In = ParameterLocation.Header,
//            Type = SecuritySchemeType.ApiKey,
//            Scheme = "Bearer"
//        });
//        c.AddSecurityRequirement(new OpenApiSecurityRequirement()
//        {
//          {
//            new OpenApiSecurityScheme
//            {
//              Reference = new OpenApiReference
//              {
//                Type = ReferenceType.SecurityScheme,
//                Id = "Bearer"
//              },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
//            },new List<string>()
//          }
//        });
//    });
//}
#endregion

#region 添加校验

//builder.Services.AddTransient<OASystemAuthentication>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidAudience = "OASystem.com",
                ValidIssuer = "OASystem.com",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
                ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值，解决服务器端时间不同步问题（秒）
                RequireExpirationTime = true,
            };
        });
#endregion

#region 初始化日志
Log.Logger = new LoggerConfiguration()
       .MinimumLevel.Debug()
       .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
       .CreateLogger();
#endregion

#region 引入注册Autofac Module
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    try
    {
        builder.RegisterModule(new AutofacRegister());
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message + "\n" + ex.InnerException);
    }
});
#endregion

#region AutoMapper

AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
{
    cfg.AddProfile<_baseMappingProfile>();
});
builder.Services.AddSingleton(config);
builder.Services.AddScoped<IMapper, Mapper>();

#endregion

#region 聚合API 服务
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
#endregion

#region 企业微信API 服务

builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));

#endregion

#region 有道API 服务
//builder.Services.AddControllersWithViews();
//builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
//builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
#endregion

#region Quartz

builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
builder.Services.AddSingleton<QuartzFactory>();
builder.Services.AddSingleton<ALiYunPostMessageJob>();
//# new business
builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();

#endregion

var app = builder.Build();
AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication(); // 认证
app.UseAuthorization();  // 授权
app.UseCors("Cors");  //Cors
//app.UseCors("AllowSpecificOrigin");  //Cors

#region 启用swaggerUI
if (AppSettingsHelper.Get("UseSwagger").ToBool())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
        foreach (var item in groups)
        {
            c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
        }
        c.RoutePrefix = string.Empty;
        c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
        c.DefaultModelsExpandDepth(-1);
    });
}
#endregion

#region Quartz

//获取容器中的QuartzFactory
var quartz = app.Services.GetRequiredService<QuartzFactory>();
app.Lifetime.ApplicationStarted.Register(async () =>
{
    await quartz.Start();
});

app.Lifetime.ApplicationStopped.Register(() =>
{
    //Quzrtz关闭方法
    //quartz.Stop();
});

#endregion


app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
