using IRaCIS.Core.Application.Contracts;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace IRaCIS.Core.API
{
    public static  class SwaggerSetup
    {
        public static void AddSwaggerSetup(this IServiceCollection services)
        {
            services.AddSwaggerExamplesFromAssemblyOf<JsonPatchUserRequestExample>();

            services.AddSwaggerGen(options =>
            {
                //此处的Name 是控制器上分组的名称     Title是界面的大标题
                //分组
              
                options.SwaggerDoc("Reviewer", new OpenApiInfo {Title = "医生模块",Version = "Reviewer", });
                options.SwaggerDoc("Trial", new OpenApiInfo { Title = "项目模块", Version = "Trial" });
                options.SwaggerDoc("Enroll", new OpenApiInfo { Title = "入组模块", Version = "Enroll" });
                options.SwaggerDoc("Workload", new OpenApiInfo { Title = "工作量模块", Version = "Workload" });
                options.SwaggerDoc("Common", new OpenApiInfo { Title = "通用信息获取", Version = "Common" });
                options.SwaggerDoc("Institution", new OpenApiInfo { Title = "机构信息模块", Version = "Institution" });
                options.SwaggerDoc("Dashboard&Statistics", new OpenApiInfo { Title = "统计模块", Version = "Dashboard&Statistics" });
              
                options.SwaggerDoc("Financial", new OpenApiInfo { Title = "财务模块", Version = "Financial" });
                options.SwaggerDoc("Management", new OpenApiInfo { Title = "管理模块", Version = "Management" });
                options.SwaggerDoc("Image", new OpenApiInfo { Title = "影像模块", Version = "Image" });
                options.SwaggerDoc("Reading", new OpenApiInfo { Title = "读片模块", Version = "Reading" });
            

                // 接口排序
                options.OrderActionsBy(o => o.GroupName);

                options.DocInclusionPredicate((docName, apiDes) =>
                {
                    if (!apiDes.TryGetMethodInfo(out MethodInfo methodInfo)) return false;
                    var versions = methodInfo.DeclaringType.GetCustomAttributes(true)
                    .OfType<ApiExplorerSettingsAttribute>()
                    .Select(attr => attr.GroupName);

                    return versions.Any(v => v.ToString() == docName);
                });

                var xmlPath = Path.Combine(AppContext.BaseDirectory, "IRaCIS.Core.API.xml");//这个就是刚刚配置的xml文件名
                options.IncludeXmlComments(xmlPath, true);

                var xmlPath2 = Path.Combine(AppContext.BaseDirectory, "IRaCIS.Core.Application.xml");//这个就是刚刚配置的xml文件名
                options.IncludeXmlComments(xmlPath2, true);
                //默认的第二个参数是false，这个是controller的注释，记得修改


                // 在header中添加token，传递到后台
                options.OperationFilter<SecurityRequirementsOperationFilter>();

                options.DocumentFilter<JsonPatchDocumentFilter>();

                // 添加登录按钮
                options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",

                    //In = "header",
                    //Type = "apiKey"
                });


                //// Bearer 
                //options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                //{
                //    Description = "JWT Authorization header using the Bearer scheme.",
                //    Name = "Authorization",
                //    In = ParameterLocation.Header,
                //    Scheme = "bearer",
                //    Type = SecuritySchemeType.Http,
                //    BearerFormat = "JWT"
                //});
            });
        }

        public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                //此处的Name 是页面  选择文档下拉框 显示的名称
                options.SwaggerEndpoint($"swagger/Reviewer/swagger.json", "医生模块");
                options.SwaggerEndpoint($"swagger/Trial/swagger.json", "项目模块");
                options.SwaggerEndpoint($"swagger/Enroll/swagger.json", "入组模块");
                options.SwaggerEndpoint($"swagger/Workload/swagger.json", "工作量模块");
                options.SwaggerEndpoint($"swagger/Dashboard&Statistics/swagger.json", "统计模块");
                options.SwaggerEndpoint($"swagger/Common/swagger.json", "通用模块");
              
                options.SwaggerEndpoint($"swagger/Financial/swagger.json", "财务模块");
                options.SwaggerEndpoint($"swagger/Institution/swagger.json", "机构信息模块");
                options.SwaggerEndpoint($"swagger/Management/swagger.json", "管理模块");
                options.SwaggerEndpoint($"swagger/Image/swagger.json", "影像模块");
                options.SwaggerEndpoint($"swagger/Reading/swagger.json", "读片模块");
              

                //路径配置，设置为空，表示直接在根域名（localhost:8001）访问该文件,
                //注意localhost:8001/swagger是访问不到的，去launchSettings.json把launchUrl去掉，如果你想换一个路径，直接写名字即可，比如直接写c.Route = "doc";
                //options.RoutePrefix = string.Empty;

                var data = Assembly.GetExecutingAssembly().Location;
                options.IndexStream = () => Assembly.GetExecutingAssembly()
                .GetManifestResourceStream("IRaCIS.Core.API.wwwroot.swagger.ui.Index.html");

                options.RoutePrefix = string.Empty;

                //DocExpansion设置为none可折叠所有方法
                options.DocExpansion(DocExpansion.None);
                //DefaultModelsExpandDepth设置为 - 1 可不显示models
                options.DefaultModelsExpandDepth(-1);


                // 引入静态文件添加登录功能
                // 清除静态文件缓存
                // options.IndexStream = () => null;

                
            });


        }
    }
}
