using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Dnc.Api.Throttle;
using Mall.CacheManager.User;
using Mall.Module.Education;
using Mall.ThirdCore.Message;
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;

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)
                .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>()
            {
                "http://localhost:8081",
                "http://127.0.0.1:8081",
                "http://127.0.0.1:8085",
                "http://localhost:8181",
                "http://localhost:8080",
                "http://127.0.0.1:8080",
                "http://localhost:8082",
                "http://127.0.0.1:8082",
                "http://localhost:8083",
                "http://127.0.0.1:8083",
                "http://127.0.0.1:50512",
                "http://127.0.0.1:20224",
                "http://127.0.0.1:28221",
                "http://www.test.com:8080",
                "http://www.test.com:8081",
                "http://yx.oytour.com",
                "http://mall.oytour.com",
                "http://testmall.oytour.com",
                "http://yx.oytour.com",
                "https://mallapi.oytour.com",
                "http://edu.oytour.com",
                "http://jvs.oytour.com",
                "http://pic.oytour.com",
                "http://admin.jjsw.vip",
                "http://mallweb.jjsw.vip",
            };
            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"
            });
        }
    }
}
