using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Com.FirmLib.Entity;

namespace Com.FirmLib.Common
{
    public static class JObjectExtension
    {
        /// <summary>
        /// 增加键值检测，如果value为null,则不对相关数据进行更新
        /// </summary>
        /// <param name="jObject"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool AddCheckNull(this JObject jObject,string key, string value)
        {
            if (value == null)
                return false;
            jObject.Add(key, value);
            return true;
        }
        public static List<ParameterItem> ConvertToParameterItems(this JObject jObject)
        {
            List<ParameterItem> items = new List<ParameterItem>();
            if (jObject == null)
                return items;
            foreach (var keyValue in jObject)
            {
                items.Add(new ParameterItem() { Code=keyValue.Key,Value=keyValue.Value.ToString()});
            }
            return items;
        }
        public static JObject ConvertToJObject(this List<ParameterItem> parameters)
        {
            JObject jObject = new JObject();
            foreach (var parameterItem in parameters)
            {
                jObject.Add(parameterItem.Code, parameterItem.Value);
            }
            return jObject;
        }

        /// <summary>
        /// 获取对应的值
        /// </summary>
        /// <param name="jObject"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCheckValue(this JObject jObject, string key)
        {
            string value = "";
            JToken jToken = null;
            if (jObject.TryGetValue(key, out jToken))
            {
                value = jToken.ToString();
            }
            return value;
        }
    }
}
