using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
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.Hosting;
using Microsoft.Extensions.Logging;
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; }

        // This method gets called by the runtime. Use this method to add services to the container.
        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://localhost:8080",
                "http://localhost:8082",
                "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",
            };
            services.AddCors(options => options.AddPolicy("AllowCors", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(corsArray.ToArray())));
         
            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;
            });
        }
 

        // 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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            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();  //网站停止完成执行
            });
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "upfile")),
                RequestPath = "/upfile"
            });
        }
    }
}
