using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using Confluent.Kafka;
using System.Text.Json.Serialization;
using System.Text.Encodings.Web;

namespace JiShe.CollectBus.Kafka.Serialization
{
    /// <summary>
    /// JSON 序列化器（支持泛型）
    /// </summary>
    public class JsonSerializer<T> : ISerializer<T>, IDeserializer<T>
    {
        private static readonly JsonSerializerOptions _options = new JsonSerializerOptions
        {
            DefaultIgnoreCondition = JsonIgnoreCondition.Never,
            WriteIndented = false,// 设置格式化输出
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,// 允许特殊字符
            IgnoreReadOnlyFields = true,
            IgnoreReadOnlyProperties = true,
            NumberHandling = JsonNumberHandling.AllowReadingFromString, // 允许数字字符串
            AllowTrailingCommas = true, // 忽略尾随逗号
            ReadCommentHandling = JsonCommentHandling.Skip, // 忽略注释
            PropertyNameCaseInsensitive = true, // 属性名称大小写不敏感
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 属性名称使用驼峰命名规则
            Converters = { new DateTimeJsonConverter() } // 注册你的自定义转换器, 
        };

        public byte[] Serialize(T data, SerializationContext context)
        {
            if (data == null)
                return null;

            try
            {
                return JsonSerializer.SerializeToUtf8Bytes(data, _options);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Kafka序列化失败", ex);
            }
        }

        public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)
        {
            if (isNull)
                return default;
            try
            {
                if (data.IsEmpty)
                    return default;
                return  JsonSerializer.Deserialize<T>(data, _options)!;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Kafka反序列化失败", ex);
            }
        }
    }


    public class DateTimeJsonConverter : JsonConverter<DateTime>
    {
        private readonly string _dateFormatString;
        public DateTimeJsonConverter()
        {
            _dateFormatString = "yyyy-MM-dd HH:mm:ss";
        }

        public DateTimeJsonConverter(string dateFormatString)
        {
            _dateFormatString = dateFormatString;
        }

        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(_dateFormatString));
        }
    }


    public static class KafkaSerialization
    {

        /// <summary>
        /// 判断是否是json类型
        /// </summary>
        /// <param name="jsonObject"></param>
        /// <returns></returns>
        public static bool IsJsonType(this object jsonObject)
        {
            return jsonObject is JsonElement;
        }
        public static object? Deserialize(object value, Type valueType)
        {
            var _jsonSerializerOptions = new JsonSerializerOptions
            {
                DefaultIgnoreCondition = JsonIgnoreCondition.Never,
                WriteIndented = false,// 设置格式化输出
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,// 允许特殊字符
                IgnoreReadOnlyFields = true,
                IgnoreReadOnlyProperties = true,
                NumberHandling = JsonNumberHandling.AllowReadingFromString, // 允许数字字符串
                AllowTrailingCommas = true, // 忽略尾随逗号
                ReadCommentHandling = JsonCommentHandling.Skip, // 忽略注释
                PropertyNameCaseInsensitive = true, // 属性名称大小写不敏感
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 属性名称使用驼峰命名规则
                Converters = { new DateTimeJsonConverter() } // 注册你的自定义转换器, 
            };

            if (value is JsonElement jsonElement) return jsonElement.Deserialize(valueType, _jsonSerializerOptions);

            throw new NotSupportedException("Type is not of type JsonElement");
        }
    }
}
