using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace IRaCIS.Core.Application.Filter
{
    public class ProjectExceptionFilter : Attribute, IExceptionFilter
    {
        private readonly ILogger<ProjectExceptionFilter> _logger;

        public ProjectExceptionFilter(ILogger<ProjectExceptionFilter> logger)
        {
            _logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            //context.ExceptionHandled;//记录当前这个异常是否已经被处理过了

            if (!context.ExceptionHandled)
            {
                if (context.Exception.GetType().Name == "DbUpdateConcurrencyException")
                {
                    context.Result = new JsonResult(ResponseOutput.NotOk("并发更新，当前不允许该操作" + context.Exception.Message));
                }

                if (context.Exception.GetType() == typeof(BusinessValidationFailedException) || context.Exception.GetType() == typeof(DBSaveFailedException))
                {
                    context.Result = new JsonResult(ResponseOutput.NotOk(context.Exception.Message,ApiResponseCodeEnum.BusinessValidationFailed));
                }
                else if(context.Exception.GetType() == typeof(QueryBusinessObjectNotExistException))
                {
                    context.Result = new JsonResult(ResponseOutput.NotOk( context.Exception.Message, ApiResponseCodeEnum.DataNotExist));
                }
                else
                {
                    context.Result = new JsonResult(ResponseOutput.NotOk("当前操作失败，请联系开发人员查看系统日志排查 ", ApiResponseCodeEnum.ProgramException));
                }


                _logger.LogError(context.Exception.InnerException is null ? (context.Exception.Message + context.Exception.StackTrace) : (context.Exception.InnerException?.Message + context.Exception.InnerException?.StackTrace));


            }
            else
            {
                //继续
            }
            context.ExceptionHandled = true;//标记当前异常已经被处理过了
        }
    }
}
