using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static Lucene.Net.Util.Fst.Util;

namespace Hotline.Share.Tools;
public static class ObjectExtensions
{
    /// <summary>
    /// 遍历类属性
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="model"></param>
    /// <param name="func">返回 true: contions; false: break</param>
    public static void ForeachClassProperties<T>(this T model, Func<T, PropertyInfo , string, object, Task<bool>> func)
    {
        var t = model.GetType();
        var propertyList = t.GetProperties();
        foreach (var item in propertyList)
        {
            var name = item.Name;
            var value = item.GetValue(model, null);
            var result = func(model, item, name, value).GetAwaiter().GetResult();
            if (result == false) break;
        }
    }

    public static string ToJson(this object obj)
    {
        return obj == null ? default(string) : JsonConvert.SerializeObject(obj);
    }

    public static T FromJson<T>(this string json)
    {
        return json.IsNullOrEmpty() ? default(T) : JsonConvert.DeserializeObject<T>(json);
    }
}
