using CallCenter.Utility;
using System.Collections.Generic;
using System.Web.Mvc;

namespace CallCenterApi.Interface
{
    public class ErrorAttribute : HandleErrorAttribute
    {
        //此处代码说明，将所有网站异常的日志全部记录 log4net error文件
        public override void OnException(ExceptionContext context)
        {
            base.OnException(context);
            WriteLog(context);
            context.ExceptionHandled = true;
            context.HttpContext.Response.StatusCode = 200;
            context.Result = new ContentResult { Content = new AjaxResult { state = ResultTypes.error.ToString(), message = context.Exception.Message}.ToJson() };
        }

        private void WriteLog(ExceptionContext context)
        {
            if (context == null)
                return;
            var log = LogFactory.GetLogger(context.Controller.ToString() + "/" + context.RouteData.Values["Action"].ToString());
            //log.Error(context.Exception.ToString());

            var cnt = context.RequestContext.HttpContext;
            var rt = cnt.Request;
            Dictionary<string, string> Params = new Dictionary<string, string>();
            Params.Add("request_url", rt.Url.ToString());

            if (rt.HttpMethod.ToUpper() != "GET")
            {
                foreach (var key in rt.Params.AllKeys)
                {
                    if (key == "ALL_HTTP")
                    {
                        break;
                    }
                    Params.Add(key, rt.Params[key]);
                }
            }
            string usercode = cnt.User?.Identity.Name ?? "";

            log.Error("系统异常，操作账号：" + usercode + "，请求信息：" + Params.ToJson(), context.Exception);
        }
    }
}