using CloudBuilder.Core.DependencyInjection.Form;
using CloudBuilder.Core.Extensions;
using CloudBuilder.Core.Service;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);


builder.Services.Initialize();


// Add services to the container.
builder.Services.AddHttpClient().AddControllers()
        .AddNewtonsoftJson(options =>
        {
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
            options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
        });


builder.Services.AddSpaStaticFiles(options => { options.RootPath = "dist"; });

//================================上传文件==============================
//上传文件大小限制Kestrel设置
builder.Services.Configure<KestrelServerOptions>(options =>
{
    // Set the limit to 256 MB
    options.Limits.MaxRequestBodySize = null;
});
//上传文件大小限制IIS设置
builder.Services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = null;
});

builder.Services.Configure<FormOptions>(options =>
{
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = int.MaxValue;
    options.MultipartHeadersLengthLimit = int.MaxValue;
});
/*
如果是在VS中调试的项目
需要修改项目根目录.vs\CloudBuilder\config\applicationhost.config 中找到<requestFiltering>节点添加
<requestLimits maxAllowedContentLength="1073741824" />

如果是发布到IIS上的项目
找到web.config在<system.webServer>节点下添加。注意以后每次发布不要覆盖掉该web.config
<system.web>
    <compilation debug="true" targetFramework="4.5.2">
        <assemblies>
        <add assembly="System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        </assemblies>
    </compilation>
    <pages controlRenderingCompatibilityVersion="4.0" />
    <httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
    <security>
        <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483647" />
        </requestFiltering>
    </security>
</system.webServer>
IIS內修改ASP中修改最大请求实体主体限制
*/

//================================上传文件==============================

var app = builder.Build();

string urlOrigins = app.Configuration["UrlOrigins"];
//跨域是否使用SSL
if (urlOrigins.Contains("https"))
{
    app.UseHttpsRedirection();
}

app.UseCors(b =>
{
    b.WithOrigins(urlOrigins.Split(',')).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
});

//================================添加静态文件映射，在IIS及vs启动文件applicationhost.config的地方加入无效
//开发环境使用以下设置，如果上线还需在IIS设置MIME
var provider = FileExtension.GetFileExtensionContentTypeProvider();
provider.Mappings[".mp4"] = "application/x-mpegURL";
provider.Mappings[".flac"] = "audio/x-flac";
provider.Mappings[".m3u8"] = "application/vnd.apple.mpegurl";
provider.Mappings[".lrc"] = "application/octet-stream";
//虚拟文件,App.Configuration[VirtualPathPolicy.VirtualPath_RealPath]这个路径一定要存在，不然直接出错
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(app.Configuration["FileServiceSettings:PhysicalFileDirectory"]),
    RequestPath = app.Configuration["FileServiceSettings:RequestPath"],
    ContentTypeProvider = provider
});
//================================添加静态文件映射

// Configure the HTTP request pipeline.
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();

app.MapControllers();

app.UseSpaStaticFiles();
app.UseSpa(configuration => { });

app.Run();
