using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using System.Net;
using System.Net.Http;
using System;

namespace Mall.WebApi.Filter
{
    /// <summary>
    /// Api异常过滤
    /// </summary>
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 异常处理拦截
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            if (context.Exception.Message != "The operation was canceled." && !context.Exception.Message.Contains("已取消该操作"))
            {
                try
                {
                    LogHelper.WriteInfo("ApiExceptionFilterAttribute_OnException拦截异常信息:" + context.Exception);
                }
                catch
                {

                }
            }
            //记录错误日志
            if (context.HttpContext.Items[GlobalKey.UserPostInfo] != null)
            {
                LogHelper.Write(context.Exception,$"ApiExceptionFilterAttribute_InvokeServiceMethod请求地址：{Config.GetFilePath(context.HttpContext.Request.GetAbsoluteUri())},请求参数：{JsonConvert.SerializeObject(context.HttpContext.Items[GlobalKey.UserPostInfo].ToString())}");
                Console.WriteLine(context.Exception);
            }
            else
            {
                LogHelper.Write(context.Exception,$"ApiExceptionFilterAttribute_InvokeServiceMethod请求地址：{Config.GetFilePath(context.HttpContext.Request.GetAbsoluteUri())}");
                Console.WriteLine(context.Exception);
            }

            var robj = new ApiResult()
            {
                resultCode = (int)ResultCode.AbnormalServer,
                message = "服务器繁忙,请稍后再试",
                data = null
            }; 
            context.Result = new Microsoft.AspNetCore.Mvc.JsonResult(robj);
        }
    }
}