using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Filter
{
    public class ExceptionFilter : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            base.OnException(context);

            var cnt = context.RequestContext.HttpContext;
            var rt = cnt.Request;

            string param = string.Empty;
            if (rt.QueryString != null && rt.QueryString.Count > 0)
            {
                param = rt.QueryString.ToJson();
            }

            if (rt.ContentLength > 0)
            {
                using (var ms = new MemoryStream())
                {
                    rt.InputStream.CopyTo(ms);
                    param = Encoding.UTF8.GetString(ms.ToArray());
                    //上传文件时截取
                    if (param.IndexOf("\r\n\r\n") > 0)
                    {
                        param = param.Substring(0, param.IndexOf("\r\n\r\n"));
                    }
                }

                rt.InputStream.Position = 0;
            }

            string usercode = cnt.User?.Identity.Name ?? "";
            LogHelper.Error("系统异常，操作账号：" + usercode + "，请求地址：" + rt.Url.ToString() + "，参数：" + param + "，请求头：" + HttpUtility.UrlDecode(rt.Headers.ToString()), context.Exception);

            context.ExceptionHandled = true;
            context.HttpContext.Response.StatusCode = 200;
            context.Result = new ContentResult { Content = new AjaxResult { state = ResultTypes.error.ToString(), message = "系统异常，请稍后重试" }.ToJson() };
        }
    }
}