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

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

		public IStringLocalizer _localizer;

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

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

                if (context.Exception.GetType() == typeof(BusinessValidationFailedException))
                {
					var error = context.Exception as BusinessValidationFailedException;

					context.Result = new JsonResult(ResponseOutput.NotOk(context.Exception.Message, error!.Code));
				}
                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(_localizer["Project_ExceptionContactDeveloper"] + (context.Exception.InnerException is null ? (context.Exception.Message /*+ context.Exception.StackTrace*/)
                        : (context.Exception.InnerException?.Message /*+ context.Exception.InnerException?.StackTrace*/)), ApiResponseCodeEnum.BackEndAnomaly));
                }


                _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;//标记当前异常已经被处理过了
        }
    }
}
