using Cis.Core;
using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.IO;
using Yitter.IdGenerator;
namespace Cis.Web.Core;
[AppStartup(1000)]
public class Startup : AppStartup
{
	/// 
	/// 配置应用所需服务,在该方法中可以添加应用所需要的功能或服务
	/// 
	/// 
	public void ConfigureServices(IServiceCollection services)
	{
		// 配置选项
		services.AddProjectOptions();
		// 缓存注册
		services.AddCache();
		// SqlSugar
		services.AddSqlSugar();
		// JWT
		services.AddJwt();
		// 允许跨域
		services.AddCorsAccessor();
		// 远程请求
		services.AddRemoteRequest();
		// 任务调度
		services.AddTaskScheduler();
		// 日志监听
		services.AddMonitorLogging();
		services.AddControllersWithViews()
			.AddNewtonsoftJson(options =>
			{
				options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 首字母小写(驼峰样式)
				options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;// 设置本地时区
				options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
				options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
				options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
			})
			.AddInjectWithUnifyResult();
		// 日志记录
		if (App.GetConfig("Logging:File:Enabled")) // 日志写入文件
		{
			Array.ForEach(new[] { LogLevel.Information, LogLevel.Warning, LogLevel.Error }, logLevel =>
			{
				services.AddFileLogging(options =>
				{
					options.FileNameRule = fileName => string.Format(fileName, DateTime.Now, logLevel.ToString()); // 每天创建一个文件
					options.WriteFilter = logMsg => logMsg.LogLevel == logLevel; // 日志级别
					options.HandleWriteError = (writeError) => // 写入失败时启用备用文件
					{
						writeError.UseRollbackFileName(Path.GetFileNameWithoutExtension(writeError.CurrentFileName) + "-oops" + Path.GetExtension(writeError.CurrentFileName));
					};
				});
			});
		}
		// 配置雪花Id算法机器码
		YitIdHelper.SetIdGenerator(new IdGeneratorOptions
		{
			WorkerId = App.GetOptions().WorkerId
		});
	}
	/// 
	/// 配置应用请求处理管道
	/// 
	/// 
	/// 
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		if (env.IsDevelopment())
		{
			app.UseDeveloperExceptionPage();
			app.UseForwardedHeaders();
		}
		else
		{
			app.UseExceptionHandler("/Home/Error");
			app.UseForwardedHeaders();
			app.UseHsts();
		}
		// 启用HTTPS
		app.UseHttpsRedirection();
		app.UseStaticFiles();
		app.UseRouting();
		app.UseCorsAccessor();
		app.UseAuthentication();
		app.UseAuthorization();
		app.UseInject();
		app.UseEndpoints(endpoints =>
		{
			endpoints.MapControllerRoute(
				name: "default",
				pattern: "{controller=Home}/{action=Index}/{id?}");
		});
	}
}