using System;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace StaffManagement.Extensions
{
    /// <summary>
    /// Api控制器返回异常
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = true,Inherited = true)]
    public class ApiExceptionFilterAttribute:ExceptionFilterAttribute
    {
        public ILogger Logger { get; set; }

        public ApiExceptionFilterAttribute(ILogger<ApiExceptionFilterAttribute> logger) {
            this.Logger = logger;
        }
        public override void OnException(ExceptionContext context) {
            var id = Guid.NewGuid().ToString("N");
            int code;
            var errMsg = new StringBuilder();
            errMsg.Append($"错误ID：{id}\n");
            if(context.Exception is ApiException ae) {
                code = StatusCodes.Status400BadRequest;
                var rqStr = JsonSerializer.Serialize(ae.Param);
                errMsg.Append($"请求参数:{rqStr}\n");
            } else {
                code = StatusCodes.Status500InternalServerError;
            }
            errMsg.Append($"异常信息：{ context.Exception}\n");
            this.Logger.LogError(errMsg.ToString());

            var result = new ApiErrorResult {
                Message = context.Exception.Message,
                Id = id,
            };

            context.Result = new JsonResult(result) { StatusCode = code };
        }

    }
}
