using Dnc.Api.Throttle;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Senparc.CO2NET;
using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.RegisterServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Unicode;

namespace Mall.WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>(x =>
            {
                x.AllowSynchronousIO = true;
                x.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
            })
            .Configure<IISServerOptions>(x => { x.AllowSynchronousIO = true; })
            ;
            services.AddControllers();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //注入http上下文
      
            services.AddSenparcGlobalServices(Configuration)//Senparc.CO2NET 全局注册
                     .AddSenparcWeixinServices(Configuration);//Senparc.Weixin 注册
            services.AddMvc().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });
            List<string> corsArray = new List<string>();
            string corsUrlStr = Common.Config.ReadConfigKey("corsUrl");
            foreach (var item in corsUrlStr.Split(','))
            {
                corsArray.Add(item);
            }
            services.AddCors(options => options.AddPolicy("AllowCors", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(corsArray.ToArray())));
            string redisConnStr = $"{Common.Config.RedisServer},password={Common.Config.RedisPwd},connectTimeout=5000,allowAdmin=false,defaultDatabase=0";
            //Api限流
            services.AddApiThrottle(options =>
            {
                //配置redis
                options.UseRedisCacheAndStorage(opts =>
                {
                    opts.ConnectionString = redisConnStr;
                    opts.KeyPrefix = "apithrottle"; //指定给所有key加上前缀，默认为apithrottle
                });
            });

            //这里添加ApiThrottleActionFilter拦截器
            services.AddMvc(opts => {
                opts.Filters.Add(typeof(ApiThrottleActionFilter));

            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.AddApiThrottle(options =>
            {
                options.Global.AddValves(
                    new BlackListValve
                    {
                        Policy = Policy.Ip,
                        Priority = 99
                    },
                    new WhiteListValve
                    {
                        Policy = Policy.UserIdentity,
                        Priority = 88
                    },
                    new BlackListValve
                    {
                        Policy = Policy.Header,
                        PolicyKey = "throttle",
                    }
                );
                options.OnIpAddress = (context) =>
                {
                    string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
                    if (string.IsNullOrEmpty(ip))
                    {
                        ip = context.Connection.RemoteIpAddress.ToString();
                    }
                    return ip;
                };
                //options.onIntercepted = (context, value, where) =>
                //{
                //    var request = context.Request;
                //    string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
                //    if (string.IsNullOrEmpty(ip))
                //    {
                //        ip = context.Connection.RemoteIpAddress.ToString();
                //    }
                //    Common.BackListHelper.Add(ip);
                //    string uToken = "";
                //    var parm = Helper.ApiTokenHelper.GetRequestParameters(request, ref uToken);
                //    if (!string.IsNullOrEmpty(uToken))
                //    {
                //        var userInfo = Helper.ApiTokenHelper.ParsingToken(uToken);
                //        if (userInfo != null && !string.IsNullOrEmpty(userInfo.uid))
                //        {
                //            Int32.TryParse(userInfo.uid, out int NewUserId);
                //            if (userInfo.requestFrom == Common.Enum.ApiRequestFromEnum.MiniProgram && NewUserId > 0)
                //            {
                //                UserReidsCache.Delete(userInfo.uid);
                //                new EducationModule().UpdateUserBlacklist(NewUserId);
                //            }
                //        }
                //    }
                //    return new ApiThrottleResult() { Content = "访问过于频繁!" };
                //};
            });
        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="appLifetime"></param>
        /// <param name="senparcSetting"></param>
        /// <param name="senparcWeixinSetting"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, IOptions<SenparcSetting> senparcSetting, IOptions<SenparcWeixinSetting> senparcWeixinSetting)
        {
            app.UseForwardedHeaders();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            
            app.UseApiThrottle();
            app.UseHttpsRedirection();

            app.UseRouting();
            // 允许所有跨域，cors是在ConfigureServices方法中配置的跨域策略名称
            app.UseCors("AllowCors");

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // 启动 CO2NET 全局注册，必须！
            IRegisterService register = RegisterService.Start(senparcSetting.Value)
                                                        .UseSenparcGlobal(false, null);

            //开始注册微信信息，必须！
            register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value);
            System.WebHttpContext.HttpContext.Configure(app.ApplicationServices.GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>());
            //启动信息发送
            //Task.Run(() => MessageCore.Init());

            //获取前面注入的Quartz调度类
            //var quartz = app.ApplicationServices.GetRequiredService<QuartzHelper>();
            appLifetime.ApplicationStarted.Register(() =>
            {
                Timers.TimerJobj.RunTimer(); //网站启动完成执行
            });

            appLifetime.ApplicationStopped.Register(() =>
            {
                Timers.TimerJobj.RunStop();  //网站停止完成执行
            });
            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "upfile");
            if (System.IO.Directory.Exists(filePath) == false)//如果不存在就创建file文件夹
            {
                System.IO.Directory.CreateDirectory(filePath);
            }
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "upfile")),
                RequestPath = "/upfile"
            });
        }
    }
}
