using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace WaterCloud.Code
{
	#region JsonHelper

	public static class JsonHelper
	{
		/// <summary>
		/// 把数组转为逗号连接的字符串
		/// </summary>
		/// <param name="data"></param>
		/// <param name="Str"></param>
		/// <returns></returns>
		public static string ArrayToString(dynamic data, string Str)
		{
			string resStr = Str;
			foreach (var item in data)
			{
				if (resStr != "")
				{
					resStr += ",";
				}

				if (item is string)
				{
					resStr += item;
				}
				else
				{
					resStr += item.Value;
				}
			}
			return resStr;
		}

		public static object ToObject(this string Json)
		{
			return string.IsNullOrEmpty(Json) ? null : JsonConvert.DeserializeObject(Json);
		}

		public static T ToObject<T>(this string Json)
		{
			Json = Json.Replace("&nbsp;", "");
			return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
		}

		public static JObject ToJObject(this string Json)
		{
			return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", ""));
		}

		public static List<T> ToList<T>(this string Json)
		{
			return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
		}

		public static string ToJson(this object obj, string dateFormat = "yyyy/MM/dd HH:mm:ss")
		{
			return obj == null ? string.Empty : JsonConvert.SerializeObject(obj, new IsoDateTimeConverter { DateTimeFormat = dateFormat });
		}
	}

	#endregion JsonHelper

	#region JsonConverter

	/// <summary>
	/// Json数据返回到前端js的时候，把数值很大的long类型转成字符串
	/// </summary>
	public class StringJsonConverter : JsonConverter
	{
		public StringJsonConverter()
		{ }

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			return reader.Value.ToLong();
		}

		public override bool CanConvert(Type objectType)
		{
			return true;
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			if (value == null)
			{
				writer.WriteNull();
				return;
			}
			string sValue = value.ToString();
			writer.WriteValue(sValue);
		}
	}

	/// <summary>
	/// DateTime类型序列化的时候，转成指定的格式
	/// </summary>
	public class DateTimeJsonConverter : JsonConverter
	{
		public DateTimeJsonConverter()
		{ }

		public override bool CanConvert(Type objectType)
		{
			return true;
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			return reader.Value.ParseToString().ToDate();
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			if (value == null)
			{
				writer.WriteNull();
				return;
			}
			DateTime? dt = value as DateTime?;
			if (dt == null)
			{
				writer.WriteNull();
				return;
			}
			writer.WriteValue(dt.Value.ToString("yyyy/MM/dd HH:mm:ss"));
		}
	}

	#endregion JsonConverter
}