using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Dnc.Api.Throttle;
using JWT;
using JWT.Serializers;
using Mall.CacheManager.User;
using Mall.Common.Plugin;
using Mall.Module.Education;
using Mall.Module.User;
using Mall.ThirdCore.Message;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using Senparc.CO2NET;
using Senparc.CO2NET.HttpUtility;
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; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddHttpClient("elite-wechat").ConfigurePrimaryHttpMessageHandler(() =>
            //{
            //    var httpClientHandler = HttpClientHelper.GetHttpClientHandler(null, RequestUtility.SenparcHttpClientWebProxy, System.Net.DecompressionMethods.GZip);
            //    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errir) => true;
            //    return httpClientHandler;
            //});

      
            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://localhost:8181",
                "http://localhost:8080",
                "http://localhost:8082",
                 "http://localhost: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"
            };
            services.AddCors(options => options.AddPolicy("AllowCors", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(corsArray.ToArray())));

            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor
                | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto;
                options.KnownProxies.Add(IPAddress.Parse("47.96.12.235"));
            });
            //services.AddCap(x =>
            //{
            //    x.UseMongoDB(Common.Config.Mongo);
            //    x.UseRabbitMQ(cfg =>
            //    {
            //        cfg.HostName = Common.Config.ReadConfigKey("RabbitMqConfig", "HostName");
            //        cfg.VirtualHost = Common.Config.ReadConfigKey("RabbitMqConfig", "VirtualHost");
            //        cfg.Port = Convert.ToInt32(Common.Config.ReadConfigKey("RabbitMqConfig", "Port"));
            //        cfg.UserName = Common.Config.ReadConfigKey("RabbitMqConfig", "UserName");
            //        cfg.Password = Common.Config.ReadConfigKey("RabbitMqConfig", "Password");
            //    });
            //    //失败后的重试次数，默认50次；在FailedRetryInterval默认60秒的情况下，即默认重试50*60秒(50分钟)之后放弃失败重试
            //    x.FailedRetryCount = 10;
            //    //失败后的重拾间隔，默认60秒
            //    x.FailedRetryInterval = 10;
            //    //设置成功信息的删除时间默认24*3600秒
            //    x.SucceedMessageExpiredAfter = 3600;
            //});
            //Api限流
            services.AddApiThrottle(options => {
                //配置redis
                //如果Cache和Storage使用同一个redis，则可以按如下配置
                options.UseRedisCacheAndStorage(opts => {
                    opts.ConnectionString = "47.96.23.199,password=Viitto2018,connectTimeout=5000,allowAdmin=false,defaultDatabase=0";
                    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 = "";
                        ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
                        if (string.IsNullOrEmpty(ip))
                        {
                            ip = context.Connection.RemoteIpAddress.ToString();
                        }
                        Common.Plugin.LogHelper.Write("ConfigureServices_ip_【" + ip + "】");
                        return ip;
                    };
                    //options.onIntercepted = (context, value, where) =>
                    //  {
                    //      Object parm = new JObject();
                    //      var request = context.Request;
                    //      request.EnableBuffering();
                    //      string responseData = "";
                    //      using (var reader = new StreamReader(request.Body, encoding: Encoding.UTF8))
                    //      {
                    //          var body = reader.ReadToEndAsync();
                    //          // Do some processing with body…
                    //          // Reset the request body stream position so the next middleware can read it
                    //          responseData = body.Result;
                    //          request.Body.Position = 0;
                    //      }
                    //      string ip = "";
                    //      ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
                    //      if (string.IsNullOrEmpty(ip))
                    //      {
                    //          ip = context.Connection.RemoteIpAddress.ToString();
                    //      }
                    //      Common.BackListHelper.Add(ip);
                    //      Common.Plugin.LogHelper.Write("ConfigureServices_ip2222_【" + ip + "】");
                    //      if (!string.IsNullOrWhiteSpace(responseData.Trim()))
                    //      {
                    //          try
                    //          {
                    //             var jsonParm = JObject.Parse(responseData);
                    //             var token = jsonParm.GetStringValue("token");
                    //              if (!string.IsNullOrWhiteSpace(token))
                    //              {
                    //                  IJsonSerializer serializer = new JsonNetSerializer();
                    //                  IDateTimeProvider provider = new UtcDateTimeProvider();
                    //                  IJwtValidator validator = new JwtValidator(serializer, provider);
                    //                  IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    //                  IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                    //                  string secret = Common.Config.JwtSecretKey;
                    //                  var json = decoder.Decode(token, secret, verify: true);//token为之前生成的字符串
                    //                  JObject jwtJson = JObject.Parse(json);
                    //                  var mall_userInfo = JObject.Parse(jwtJson.GetStringValue("mall_userInfo"));
                    //                  var requestFrom = mall_userInfo.GetInt("requestFrom");
                    //                  var uid = mall_userInfo.GetInt("uid");
                    //                  if (requestFrom == 2 && uid > 0)
                    //                  {
                    //                      UserReidsCache.Delete(uid.ToString());
                    //                      new EducationModule().UpdateUserBlacklist(uid);
                    //                  }
                                      
                    //              }
                    //          }
                    //          catch (Exception ex)
                    //          {
                                  
                    //          }
                    //      }

                    //      return new ApiThrottleResult() { Content = "访问过于频繁!" };
                    //  };
                });
        }


 



        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        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"
            });
        }
    }
}
