using Hotline.Settings;
using Hotline.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;
using Newtonsoft.Json;
using Hotline.KnowledgeBase;
using XF.Domain.Repository;
using Serilog;
using Hotline.Api.Controllers;
using Microsoft.Data.SqlClient;
using Hotline.Repository.SqlSugar.CallCenter;

namespace Hotline.Api.Filter
{
	public class LogFilterAttribute : ActionFilterAttribute
	{
		public LogFilterAttribute(string name = "", bool record = true)
		{
			this.name = name;
			this.record = record;
		}

		public string name { get; set; }

		public bool record { get; set; }


		public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var repository = context.HttpContext.RequestServices.GetService<IRepository<SystemLog>>();

			//进入方法
			var resultContext =  await next();
			if (record)
			{
				#region 记录日志
				SystemLog log = new SystemLog();
				log.Name = name;
				var Method = "";
				switch (context.HttpContext.Request.Method.ToUpper())
				{
					case "GET":
						Method = "GET";
						log.ExecuteParam = context.HttpContext.Request.QueryString;
						break;

					case "POST":
						Method = "POST";
						if (context.ActionArguments?.Count > 0)
						{
							log.ExecuteUrl += context.HttpContext.Request.QueryString.Value;
							log.ExecuteParam = context.ActionArguments;
						}
						else
						{
							log.ExecuteParam = context.HttpContext.Request.QueryString;
						}
						break;
				}
				log.ExecuteUrl = Method + "|" + context.HttpContext.Request.Path;
				if (resultContext.Exception != null)
				{
					StringBuilder sbException = new StringBuilder();
					Exception exception = resultContext.Exception;
					sbException.AppendLine(exception.Message);
					while (exception.InnerException != null)
					{
						sbException.AppendLine(exception.InnerException.Message);
						exception = exception.InnerException;
					}
					sbException.AppendLine(LogTool.GetSubString(resultContext.Exception.StackTrace, 4000));
					log.ExecuteResult = sbException.ToString();
					log.Status = 0;
				}
				else
				{
					log.Status = 1;
					ObjectResult result = context.Result as ObjectResult;
					if (result != null)
					{
						log.ExecuteResult = JsonConvert.SerializeObject(result.Value);
					}
				}
				await repository.AddAsync(log);

				#endregion
			}
		}
	}
}
