using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NLog;
using System;
using System.Collections.Generic;
using System.Text;

namespace System.Common
{
    public class ExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var log = LogManager.GetLogger(context.ActionDescriptor.AttributeRouteInfo.Template);

            var request = context.HttpContext.Request;
            var ip = request.Headers["X-Forwarded-For"];
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
            }
            string userinfo = string.Empty;
            var claims = context.HttpContext.User.Claims.GetEnumerator();
            while (claims.MoveNext())
            {
                if (claims.Current.Type.IndexOf("/") >= 0)
                {
                    userinfo += claims.Current.Type.Substring(claims.Current.Type.LastIndexOf('/') + 1) + ":" + claims.Current.Value + ";";
                }
            }

            var param = string.Empty;

            try
            {
                if (request.Method == "GET")
                {
                    param = request.Query.ToJson();
                }
                else
                {
                    param = request.Form.ToJson();
                }
            }
            catch
            {
                param = "参数获取失败";
            }
            string strError = "IP：" + ip.ToString() + "|||UserInfo：" + userinfo + "|||ContentType：" + request.ContentType + "|||Params：" + param 
                + "|||Error："+ context.Exception.ToString() + "|||/r/n<br>\\r\\n" + context.Exception.StackTrace;
            log.Error(strError);

            //context.Result = new ContentResult() { Content = new AjaxResult { state = ResultTypes.error.ToString(), message = "系统异常，请稍后重试" }.ToJson() };
            context.Result = new ContentResult() { Content = new AjaxResult { state = ResultTypes.error.ToString(), message = strError }.ToJson() };

            base.OnException(context);
        }
    }
}
