using Newtonsoft.Json;
using System;
using System.ComponentModel;

namespace JiaZhiQuan.Common.Response {
    public sealed class NumberConverter : JsonConverter {
        /// <summary>
        /// 转换成字符串的类型
        /// </summary>
        private readonly NumberConverterShip? _ship;
        private readonly string _format;
        /// <summary>
        /// 大数据json序列化重写实例化
        /// </summary>
        public NumberConverter() {
        }

        /// <summary>
        /// 大数据json序列化重写实例化
        /// </summary>
        /// <param name="ship">转换成字符串的类型</param>
        public NumberConverter(NumberConverterShip ship, string format=null) {
            _ship = ship;
            _format = format;
        }

        /// <inheritdoc />
        /// <summary>
        /// 确定此实例是否可以转换指定的对象类型。
        /// </summary>
        /// <param name="objectType">对象的类型。</param>
        /// <returns>如果此实例可以转换指定的对象类型，则为：<c>true</c>，否则为：<c>false</c></returns>
        public override bool CanConvert(Type objectType) {
            var typecode = Type.GetTypeCode(objectType.Name.Equals("Nullable`1") ?
                objectType.GetGenericArguments()[0] : objectType);
            return typecode switch {
                TypeCode.Decimal => _ship == null || (_ship & NumberConverterShip.Decimal) == NumberConverterShip.Decimal,
                TypeCode.Double => _ship == null || (_ship & NumberConverterShip.Double) == NumberConverterShip.Double,
                TypeCode.Int64 => _ship == null || (_ship & NumberConverterShip.Int64) == NumberConverterShip.Int64,
                TypeCode.UInt64 => _ship == null || (_ship & NumberConverterShip.UInt64) == NumberConverterShip.UInt64,
                TypeCode.Single => _ship == null || (_ship & NumberConverterShip.Single) == NumberConverterShip.Single,
                _ => false,
            };
        }

        /// <inheritdoc />
        /// <summary>
        /// 读取对象的JSON表示。
        /// </summary>
        /// <param name="reader">从 <see cref="T:Newtonsoft.Json.JsonReader" /> 中读取。</param>
        /// <param name="objectType">对象的类型。</param>
        /// <param name="existingValue">正在读取的对象的现有值。</param>
        /// <param name="serializer">调用的序列化器实例。</param>
        /// <returns>对象值。</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
            return reader.Value == null ? null: AsType(reader.Value.ToString(), objectType);
        }

        /// <summary>
        /// 字符串格式数据转其他类型数据
        /// </summary>
        /// <param name="input">输入的字符串</param>
        /// <param name="destinationType">目标格式</param>
        /// <returns>转换结果</returns>
        public static object AsType(string input, Type destinationType) {
            try {
                var converter = TypeDescriptor.GetConverter(destinationType);
                if (converter.CanConvertFrom(typeof(string))) {
                    return converter.ConvertFrom(null, null, input);
                }

                converter = TypeDescriptor.GetConverter(typeof(string));
                if (converter.CanConvertTo(destinationType)) {
                    return converter.ConvertTo(null, null, input, destinationType);
                }
            } catch {
                return null;
            }
            return null;
        }

        /// <inheritdoc />
        /// <summary>
        /// 写入对象的JSON表示形式。
        /// </summary>
        /// <param name="writer">要写入的 <see cref="T:Newtonsoft.Json.JsonWriter" /> 。</param>
        /// <param name="value">要写入对象值</param>
        /// <param name="serializer">调用的序列化器实例。</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
            if (value == null) {
                writer.WriteNull();
            } else {
                var objectType = value.GetType();
                var typeCode = Type.GetTypeCode(objectType.Name.Equals("Nullable`1") ?
                    objectType.GetGenericArguments()[0] : objectType);
                switch (typeCode) {
                    case TypeCode.Decimal:
                        writer.WriteValue(((decimal)value).ToString(_format ?? "f6"));
                        break;
                    case TypeCode.Double:
                        writer.WriteValue(((double)value).ToString(_format ?? "f4"));
                        break;
                    case TypeCode.Single:
                        writer.WriteValue(((float)value).ToString(_format ?? "f2"));
                        break;
                    case TypeCode.Int64:
                        var typedInt64Value = (long)value;
                        if (typedInt64Value < Int32.MaxValue && typedInt64Value > Int32.MinValue)
                        {
                            writer.WriteValue(typedInt64Value);
                        }
                        else
                        {
                            writer.WriteValue(value.ToString());
                        }
                        break;
                    case TypeCode.UInt64:
                        var typedUInt64Value = (ulong)value;
                        if (typedUInt64Value < UInt32.MaxValue && typedUInt64Value > UInt32.MinValue)
                        {
                            writer.WriteValue(typedUInt64Value);
                        }
                        else
                        {
                            writer.WriteValue(value.ToString());
                        }
                        break;
                    default:
                        writer.WriteValue(value);
                        break;
                }
            }
        }
    }

    /// <summary>
    /// 转换成字符串的类型
    /// </summary>
    [Flags]
    public enum NumberConverterShip {
        /// <summary>
        /// 长整数
        /// </summary>
        Int64 = 1,

        /// <summary>
        /// 无符号长整数
        /// </summary>
        UInt64 = 2,

        /// <summary>
        /// 浮点数
        /// </summary>
        Single = 4,

        /// <summary>
        /// 双精度浮点数
        /// </summary>
        Double = 8,

        /// <summary>
        /// 大数字
        /// </summary>
        Decimal = 16
    }
}
