using Furion;
using Furion.DataValidation;
using Furion.FriendlyException;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;

namespace YBEE.EQM.Core
{
    /// <summary>
    /// 规范化RESTful风格返回值
    /// </summary>
    [UnifyModel(typeof(XnRestfulResult<>))]
    public class XnRestfulResultProvider : IUnifyResultProvider
    {
        /// <summary>
        /// 异常返回值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public IActionResult OnException(ExceptionContext context, ExceptionMetadata metadata)
        {
            AntShowType showType = AntShowType.ERROR_MESSAGE;
            int statusCode = metadata.Errors.ToString() == "unauthorized" ? 401 : metadata.StatusCode;
            //int errorCode = (int)(metadata.ErrorCode ?? 400);
            int errorCode = 500;
            if (metadata.Errors.ToString() == "unauthorized") { errorCode = 401; }
            if (metadata.OriginErrorCode is ErrorCode && metadata.ErrorCode.ToString() != "")
            {
                string ec = metadata.ErrorCode.ToString().ToUpper();
                string st = ec[..1];
                switch (st)
                {
                    case "S": showType = AntShowType.SILENT; break;
                    case "W": showType = AntShowType.WARN_MESSAGE; break;
                    case "E": showType = AntShowType.ERROR_MESSAGE; break;
                    case "N": showType = AntShowType.NOTIFICATION; break;
                    case "R": showType = AntShowType.REDIRECT; break;
                }
                if (int.TryParse(ec.AsSpan(1), out int ecode))
                {
                    errorCode = ecode;
                }
            }
            return new JsonResult(RESTfulResult(statusCode, errors: metadata.Errors, errorCode: errorCode, showType: showType));
        }

        /// <summary>
        /// 成功返回值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public IActionResult OnSucceeded(ActionExecutedContext context, object data)
        {
            return new JsonResult(RESTfulResult(StatusCodes.Status200OK, true, data));
        }

        /// <summary>
        /// 验证失败返回值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public IActionResult OnValidateFailed(ActionExecutingContext context, ValidationMetadata metadata)
        {
            return new JsonResult(RESTfulResult(metadata.StatusCode ?? StatusCodes.Status400BadRequest, errors: metadata.ValidationResult, errorCode: 500, showType: AntShowType.NOTIFICATION));
        }

        /// <summary>
        /// 处理输出状态码
        /// </summary>
        /// <param name="context"></param>
        /// <param name="statusCode"></param>
        /// <param name="unifyResultSettings"></param>
        /// <returns></returns>
        public async Task OnResponseStatusCodes(HttpContext context, int statusCode, UnifyResultSettingsOptions unifyResultSettings)
        {
            // 设置响应状态码
            UnifyContext.SetResponseStatusCodes(context, statusCode, unifyResultSettings);

            switch (statusCode)
            {
                // 处理 401 状态码
                case StatusCodes.Status401Unauthorized:
                    await context.Response.WriteAsJsonAsync(RESTfulResult(statusCode, errors: "401 未授权或授权已过期"), App.GetOptions<JsonOptions>()?.JsonSerializerOptions);
                    break;
                // 处理 403 状态码
                case StatusCodes.Status403Forbidden:
                    await context.Response.WriteAsJsonAsync(RESTfulResult(statusCode, errors: "403 禁止访问"), App.GetOptions<JsonOptions>()?.JsonSerializerOptions);
                    break;

                default: break;
            }
        }

        /// <summary>
        /// 返回 RESTful 风格结果集
        /// </summary>
        /// <param name="statusCode"></param>
        /// <param name="succeeded"></param>
        /// <param name="data"></param>
        /// <param name="errors"></param>
        /// <param name="errorCode"></param>
        /// <param name="showType"></param>
        /// <returns></returns>
        private static XnRestfulResult<object> RESTfulResult(int statusCode, bool succeeded = default, object data = default, object errors = default, int errorCode = 0, AntShowType showType = AntShowType.ERROR_MESSAGE)
        {
            return new XnRestfulResult<object>
            {
                Success = succeeded,
                Code = statusCode,
                ErrorCode = errorCode,
                ErrorMessage = errors,
                ShowType = showType,
                Data = data,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            };
        }

        public IActionResult OnAuthorizeException(DefaultHttpContext context, ExceptionMetadata metadata)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// RESTful风格---Antd返回格式
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class XnRestfulResult<T>
    {
        /// <summary>
        /// 执行成功
        /// </summary>
        public bool Success { get; set; }
        /// <summary>
        /// 状态码
        /// </summary>
        public int? Code { get; set; }
        /// <summary>
        /// 错误码
        /// </summary>
        public int? ErrorCode { get; set; } = 0;
        /// <summary>
        /// 错误信息
        /// </summary>
        public object ErrorMessage { get; set; }
        /// <summary>
        /// 前端错误显示级别
        /// </summary>
        public AntShowType? ShowType { get; set; }
        /// <summary>
        /// 数据
        /// </summary>
        public T Data { get; set; }
        /// <summary>
        /// 附加数据
        /// </summary>
        public object Extras { get; set; }
        /// <summary>
        /// 时间戳
        /// </summary>
        public long Timestamp { get; set; }
    }
}