using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using Api.SignToken;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.IdentityModel.Tokens.Jwt;
using Pivotal.Discovery.Client;
using NLog.Extensions.Logging;
using NLog.Web;
using Microsoft.AspNetCore.Mvc.Versioning;
using MadRunFabric.Common.Options;
using AutoMapper;
using EquipmentApi.IRepositories;
using EquipmentApi.Repositories;
using MadRunFabric.Common;

namespace EquipmentApi
{
    public class Startup
    {
        
        public Startup(IHostingEnvironment env)
        {
            Configuration = new ConfigurationBuilder()
                            .SetBasePath(env.ContentRootPath)
                            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                            .AddEnvironmentVariables()
                            .Build();
        }

        public IConfiguration Configuration { get; }
        
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Cors 配置
            //生产环境 的cors
            services.AddCors(options =>
            {
            options.AddPolicy("CorsProd",
            builder => builder.AllowAnyOrigin()
            //builder => builder.WithOrigins(Configuration["Cors"].Split(','))
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials().SetPreflightMaxAge(TimeSpan.FromMinutes(40)));
            });
            //开发环境的cors
            services.AddCors(options =>
            {
            options.AddPolicy("CorsDev",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials().SetPreflightMaxAge(TimeSpan.FromMinutes(40)));
            });
            #endregion

            #region 授权配置
            //读取jwt配置文件
            var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"].ToString()));
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidateIssuer = true,
                ValidIssuer = Configuration["Jwt:Issuer"].ToString(),//发行人
                ValidateAudience = true,
                ValidAudience = Configuration["Jwt:Audience"].ToString(),//订阅人
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero,
                RequireExpirationTime = true,
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.RequireHttpsMetadata = false;
                o.TokenValidationParameters = tokenValidationParameters;
                o.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        if (context.Request.Path.Value.ToString() == "/api/logout")
                        {
                            var token = ((context as TokenValidatedContext).SecurityToken as JwtSecurityToken).RawData;
                        }
                        return Task.CompletedTask;
                    }
                };
            });
            #endregion

            #region redis配置
            services.AddDistributedRedisCache(options =>
            {
                options.InstanceName = Configuration["Redis:InstanceName"].ToString();
                options.Configuration = $"{Configuration["Redis:HostName"].ToString()}:{Configuration["Redis:Port"].ToString()},allowAdmin=true,password={Configuration["Redis:Password"].ToString()},defaultdatabase={Configuration["Redis:Defaultdatabase"].ToString()}";
            });
            #endregion

            services.AddSingleton<IConfiguration>(Configuration);

            //注入授权Handler
            services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();

            services.AddSingleton<IPermissionService, PermissionService>();
            services.AddSingleton<IHangfireService, HangfireService>();
            services.AddSingleton<ISignTokenService, SignTokenService>();
            services.AddSingleton<IWechatService, WechatService>();

            #region 版本控制
            services.AddApiVersioning(Options =>
            {
                Options.ReportApiVersions = true;//可选，为true API返回响应标头中支持的版本信息
                Options.ApiVersionReader = new QueryStringApiVersionReader(parameterName: "api-version");
                Options.AssumeDefaultVersionWhenUnspecified = true;
                Options.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(6, 0);
            });
            #endregion


            #region AutoMapper
            services.AddAutoMapper();
            #endregion

            services.AddMvc(options =>
            {
                options.Filters.Add(new ActionFilter());
                options.Filters.Add(new ExceptionFilter());
            }).AddJsonOptions(op => op.SerializerSettings.ContractResolver =
                                        new Newtonsoft.Json.Serialization.DefaultContractResolver());
           

            #region Mongodb配置
            services.Configure<MongodbOptions>(options =>
            {
                options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
                options.Database = Configuration.GetSection("MongoConnection:Database").Value;
            });
            #endregion

            #region steeltoe
            services.AddDiscoveryClient(Configuration);
            #endregion

            services.AddTransient<IPro_Project_InfoRepository, Pro_Project_InfoRepository>();
            services.AddTransient<IPro_Project_UserRepository, Pro_Project_UserRepository>();
            services.AddTransient<IPro_Project_LogRepository, Pro_Project_LogRepository>();
            services.AddTransient<IUser_Pro_StaffRepository, User_Pro_StaffRepository>();
            services.AddTransient<IWo_WashRepository, Wo_WashRepository>();
            services.AddTransient<IWo_Repair_BaseRepository, Wo_Repair_BaseRepository>();
            services.AddTransient<IWo_Repair_SendRepository, Wo_Repair_SendRepository>();
            services.AddTransient<IWo_Repair_DealRepository, Wo_Repair_DealRepository>();
            services.AddTransient<IWo_Repair_ItemsRepository, Wo_Repair_ItemsRepository>();
            services.AddTransient<IWo_Repair_EvaluateRepository, Wo_Repair_EvaluateRepository>();
            services.AddTransient<IWo_Maintain_BaseRepository, Wo_Maintain_BaseRepository>();
            services.AddTransient<IWo_Maintain_ItemsRepository, Wo_Maintain_ItemsRepository>();
            services.AddTransient<IWo_Maintain_PlanRepository, Wo_Maintain_PlanRepository>();
            services.AddTransient<ISys_DictionaryValueRepository, Sys_DictionaryValueRepository>();
            services.AddTransient<IPro_StudyMaterials_InfoRepository, Pro_StudyMaterials_InfoRepository>();
            //new
            services.AddTransient<IEqp_Equipment_InfoRepository, Eqp_Equipment_InfoRepository>();
            services.AddTransient<IEqp_Import_InfoRepository, Eqp_Import_InfoRepository>();
            services.AddTransient<IWo_EquipmentRunningRepository, Wo_EquipmentRunningRepository>();
            services.AddTransient<IWo_EquipmentRunning_ItemsRepository, Wo_EquipmentRunning_ItemsRepository>();
            services.AddTransient<IWo_EquipmentRunning_PlanRepository, Wo_EquipmentRunning_PlanRepository>();
            services.AddTransient<IRunningRepairRepository, RunningRepairRepository>();
            services.AddTransient<IWo_Order_User_MapRepository, Wo_Order_User_MapRepository>();
            services.AddTransient<IWo_TimeOutRepository, Wo_TimeOutRepository>();
            services.AddTransient<IWo_TimeOut_ItemsRepository, Wo_TimeOut_ItemsRepository>();
            services.AddTransient<IHangfire_PlanRepository, Hangfire_PlanRepository>();
            services.AddTransient<IRunningChartRepository, RunningChartRepository>();
            services.AddTransient<IWo_MattersRepository, Wo_MattersRepository>();

            services.AddTransient<ISys_User_AccountRepository, Sys_User_AccountRepository>();
            services.AddTransient<ISys_NewsRepository, Sys_NewsRepository>();
            services.AddTransient<IinfotxsRepository, infotxsRepository>();
            services.AddTransient<ISys_Role_InfoRepository, Sys_Role_InfoRepository>();
            services.AddTransient<IusercoldandclintidsRepository, usercoldandclintidsRepository>();
            services.AddTransient<IwxwpstimeRepository, wxwpstimeRepository>();
            services.AddTransient<ISys_Work_DayGroupRepository, Sys_Work_DayGroupRepository>();

             
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsProduction())
            {
                app.UseCors("CorsProd");
            }
            else
            {
                app.UseCors("CorsDev");
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }

            app.UseAuthentication();

            app.UseMvc();

            #region steeltoe
            app.UseDiscoveryClient();
            #endregion

            #region Nlog 引入
            loggerFactory.AddNLog();//添加NLog
            env.ConfigureNLog("nlog.config");//读取Nlog配置文件
            app.AddNLogWeb();
            #endregion
        }
    }
}
