using Newtonsoft.Json;

namespace QYZH.InteractiveMagazine.Common.Helpers
{
    /// <summary>
    /// JSON工具类
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// JSON序列化设置
        /// </summary>
        private static readonly JsonSerializerSettings _settings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            DateFormatString = "yyyy-MM-dd HH:mm:ss",
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };

        /// <summary>
        /// 将对象序列化为JSON字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>JSON字符串</returns>
        public static string Serialize(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }

            return JsonConvert.SerializeObject(obj, _settings);
        }

        /// <summary>
        /// 将对象序列化为格式化的JSON字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>格式化的JSON字符串</returns>
        public static string SerializePretty(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }

            return JsonConvert.SerializeObject(obj, Formatting.Indented, _settings);
        }

        /// <summary>
        /// 将JSON字符串反序列化为指定类型
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="json">JSON字符串</param>
        /// <returns>反序列化后的对象</returns>
        public static T? Deserialize<T>(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return default;
            }

            return JsonConvert.DeserializeObject<T>(json, _settings);
        }

        /// <summary>
        /// 将JSON字符串反序列化为指定类型(带异常处理)
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="json">JSON字符串</param>
        /// <param name="defaultValue">反序列化失败时的默认值</param>
        /// <returns>反序列化后的对象或默认值</returns>
        public static T? TryDeserialize<T>(string json, T? defaultValue = default)
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return defaultValue;
            }

            try
            {
                T? result = JsonConvert.DeserializeObject<T>(json, _settings);
                return result ?? defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }
    }
}
