using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IRepositories;
using System.Linq;
using System.Repositories;
using System.Text;
using System.Threading.Tasks;
using System.Common;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using NLog.Extensions.Logging;
using NLog.Web;
using SignToken;
using Steeltoe.Discovery.Client;

namespace TVShoppingCallCenter_ZLJ
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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 配置
            services.AddCors(options =>
            {
                options.AddPolicy("Cors",
                builder => builder.AllowAnyOrigin()//builder.WithOrigins(Configuration["Cors"].Split(','))
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials().SetPreflightMaxAge(TimeSpan.FromMinutes(30)));
            });
            #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 配置数据库
            BaseContext.DB_ConnectionString = Configuration.GetConnectionString("DefaultConnection");
            #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

            #region 注入
            services.AddSingleton<IConfiguration>(Configuration);
            //services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
            //services.AddSingleton<IPermissionService, PermissionService>();

            services.AddTransient<ISys_UserAccountRepository, Sys_UserAccountRepository>();
            services.AddTransient<ISys_RoleInfoRepository, Sys_RoleInfoRepository>();
            services.AddTransient<ISys_SeatGroupRepository, Sys_SeatGroupRepository>();
            services.AddTransient<ISys_LoginLogsRepository, Sys_LoginLogsRepository>();

            services.AddTransient<ISys_DepartmentRepository, Sys_DepartmentRepository>();
            services.AddTransient<ISys_DictionaryValueRepository, Sys_DictionaryValueRepository>();
            services.AddTransient<ISys_ModuleButtonInfoRepository, Sys_ModuleButtonInfoRepository>();
            services.AddTransient<ISys_ModuleInfoRepository, Sys_ModuleInfoRepository>();
            services.AddTransient<ISys_RoleFunctionRepository, Sys_RoleFunctionRepository>();
            services.AddTransient<ISys_SeatPermissionConfigRepository, Sys_SeatPermissionConfigRepository>();
            services.AddTransient<ISys_SystemConfigRepository, Sys_SystemConfigRepository>();


            services.AddTransient<IBus_ProductClassRepository, Bus_ProductClassRepository>();
            services.AddTransient<IBus_ProductRepository, Bus_ProductRepository>();

            services.AddTransient<ICus_VipInfoRepository, Cus_VipInfoRepository>();
            services.AddTransient<ICus_VipLabelInfoRepository, Cus_VipLabelInfoRepository>();
            #endregion

            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddMvc(options =>
            {
                options.Filters.Add(new ActionFilter());
                options.Filters.Add(new ExceptionFilter());
            }).AddJsonOptions(op => op.SerializerSettings.ContractResolver =
                                        new Newtonsoft.Json.Serialization.DefaultContractResolver());
            #region steeltoe
            //services.AddDiscoveryClient(Configuration);
            #endregion
        }

        // 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)
        {
            app.UseCors("Cors");
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();

            //app.UseHttpsRedirection();
            //引入授权
            app.UseAuthentication();

            app.UseMvc();

            #region steeltoe
            //app.UseDiscoveryClient();
            #endregion

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