using BLW_Log.Controllers;
using BLW_Log.Models;
using BLW_Log.Push;
using BLW_Log.services;
using Common;
using Commonlib;
using DAL.PGModels;
using IronPython.Hosting;
using LiteDB;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Hosting;
using NLog;
using NLog.Extensions.Logging;
using NLog.Web;
using Quartz;
using RestSharp;
using System.Buffers;
using System.Data;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Text;
using static IronPython.Modules.PythonCsvModule;
namespace BLW_Log
{
    public class A
    {
        public string IP { get; set; }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            //var N = DateTime.Now.ToString("yyyy-MM-dd#HH:mm:ss:fff");
            var builder = WebApplication.CreateBuilder(args);

            //builder.Services.AddSingleton<MyMemoryCache>();

            builder.Services.AddMemoryCache();

            //AddDbContext默认已经将DbContext注册为Scoped生命周期，再次显式注册会导致冲突
            builder.Services.AddDbContext<PostgresContext>(options =>
            {
                options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"));
            });

            //builder.Services.AddScoped<PostgresContext>();

            //builder.Services.AddSingleton<TaskQueue>();
            builder.Services.AddHostedService<PanelSelectionClass>();
            // Add services to the container.
            builder.Services.AddControllersWithViews();
            //builder.Logging.AddNLog();

            builder.Services.AddCors(options =>
            {
                options.AddPolicy(name: "KuaYu",
                                  policy =>
                                  {
                                      policy
                                       .AllowAnyOrigin()
                                       .AllowAnyHeader()
                                       .AllowAnyMethod();
                                  });
            });
            builder.Services.AddAuthorization();
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(option =>
                {
                    string DefaultKey = "hQ%]d?V4W.fbbQ@6M^S2hE392xr~9:%?'0_D}8JI.36R3Q@b5&e906Z]02Yn0ZadSer4kH4,7z0j8a7.C?nGD6Z8dusY8P7Ur2z@h8:2y_25MY>wS7ih:Vd2}3#Z~nhP";
                    var sec = Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"] ?? DefaultKey);

                    option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,

                        ValidateIssuerSigningKey = true,
                        ValidIssuer = builder.Configuration["JwT:Issuer"],
                        ValidAudience = builder.Configuration["JwT:Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(sec)
                    };

                    option.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = context =>
                        {
                            var token = context.Request.Headers["token"].FirstOrDefault();
                            if (string.IsNullOrEmpty(token))
                            {
                                // 如果没有找到 token 头部，则继续检查 Authorization 头部
                                token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
                            }
                            // 如果找到了 token，则将其设置到 HttpContext 中
                            if (!string.IsNullOrEmpty(token))
                            {
                                context.Token = token;
                            }
                            return Task.CompletedTask;
                        }
                    };
                });
            builder.Services.AddSingleton<Dictionary<string, IRestClient>>(provider =>
            {
                return new Dictionary<string, IRestClient>
                {
                    ["NoStopShengJi"] = new RestClient("https://www.boonlive-rcu.com/"),
                };
            });

            string ttt1 = builder.Configuration["ExcelGenerater"].ToString();
            string[] ssk1 = ttt1.Split(',');
            int h = int.Parse(ssk1[0]);
            int m = int.Parse(ssk1[1]);
            int s = int.Parse(ssk1[2]);
            builder.Services.AddQuartz(q =>
            {
                //var jobKey = new JobKey("SendEmailJob");
                //q.AddJob<DelLogJob>(opts => opts.WithIdentity(jobKey));

                //q.AddTrigger(opts => opts
                //    .ForJob(jobKey)
                //    .WithIdentity("SendEmailJob-trigger")
                //    .WithCalendarIntervalSchedule(x =>
                //    {
                //        x.WithIntervalInMinutes(30).Build();
                //    })
                //);

                var jobKey1 = new JobKey("ExcelGenerateJob");
                q.AddJob<MyExcel>(opts => opts.WithIdentity(jobKey1));

                q.AddTrigger(opts => opts
                    .ForJob(jobKey1)
                    .WithIdentity("ExcelGenerateJob-trigger")
                    .StartAt(DateBuilder.TodayAt(h, m, s))
                    .WithCalendarIntervalSchedule(x => x
                    .WithIntervalInDays(1)
                    .InTimeZone(TimeZoneInfo.Local))
                );
                //q.AddTrigger(opts => opts
                //    .ForJob(jobKey1)
                //    .WithIdentity("ExcelGenerateJob-trigger")
                //    .WithCronSchedule("0 0 17 * * ?", (schedule) =>
                //    {
                //        schedule.WithMisfireHandlingInstructionDoNothing().InTimeZone(TimeZoneInfo.Local);
                //    }) // 每天17:00
                //);


                var jobKey2 = new JobKey("ScanExcel");
                q.AddJob<ExcelScan>(opts => opts.WithIdentity(jobKey2));
                q.AddTrigger(opts => opts
                    .ForJob(jobKey2)
                    .WithIdentity("ExcelScan-trigger")
                    .WithCalendarIntervalSchedule(x =>
                    {
                        x.WithIntervalInSeconds(30).Build();
                    })
                );


                var jobKey3 = new JobKey("DeleteFile");
                q.AddJob<ExcelScan>(opts => opts.WithIdentity(jobKey3));
                q.AddTrigger(opts => opts
                    .ForJob(jobKey3)
                    .WithIdentity("DeleteFile-trigger")
                    .WithCronSchedule("0 0 1 * * ?", (schedule) =>
                    {
                        schedule.WithMisfireHandlingInstructionDoNothing().InTimeZone(TimeZoneInfo.Local);
                    }) // 每天17:00
                );


                var isenable = builder.Configuration["ShengJi:IsEnable"];
                if (isenable.Equals("1"))
                {
                    //不停升级
                    var jobKey5 = new JobKey("BuTingShengJi");
                    q.AddJob<ShengJiCaoZuoA>(opts => opts.WithIdentity(jobKey5));
                    q.AddTrigger(opts => opts
                        .ForJob(jobKey5)
                        .WithIdentity("BuTingShengJi-trigger")
                        .StartAt(DateTimeOffset.Now.AddMinutes(1))
                    );
                }

            });
            builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
            builder.Services.AddSignalR();
            var app = builder.Build();
            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseCors("KuaYu");
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<DataPush>("/blw/datapush");
            });
            // 配置静态文件服务，添加CDR文件的MIME类型
            app.UseStaticFiles(new StaticFileOptions
            {
                ServeUnknownFileTypes = true, // 允许服务未知文件类型
                DefaultContentType = "application/octet-stream",
                OnPrepareResponse = context =>
                {
                    // 如果是CDR文件，设置下载头
                    if (context.File.Name.EndsWith(".cdr") || context.File.Name.EndsWith(".png"))
                    {
                        context.Context.Response.Headers.Append("Content-Disposition", "attachment");
                    }
                }
            });
            StaticData.GetWebAPIMethod();
            StaticData.GetGetLoginData();

            app.Run();
        }

    }
}
