using HTCoreServiceApp.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace HTCoreServiceApp.DataHandle
{

    public class DataLiving
    {
        private static readonly IDistributedCache cache;
        public static void DataLive2CaChe(List<MetaTagValue> metaTagvalues, string driverName, string GroupName)
        {
            var t3 = DateTime.Now;
            var cache = StaticLibrary.MemoryCacheHelper;
            int Result = 0;
            //if (cache.IsExist(driverName))
            //{
            try
            {
                foreach (var tlist in metaTagvalues)
                {
                    if (tlist.DataType == (short)DataType.FLOAT)
                    {
                        try
                        {
                            var d_value = decimal.Parse(tlist.TagValue);
                            string s_d_value = string.Format("{0:#,0.########}", d_value).Replace(",", "");
                            tlist.TagValue = s_d_value;
                        }
                        catch 
                        {
							tlist.TagValue = "";
						}
                    }
                }
                var liveGroupDictionary = new LiveGroupDictionary()
                {
                    GroupName = GroupName,
                    MetaTagValues = metaTagvalues
                };
                var cacheService = new CacheService(StaticLibrary.MemoryCache);
                var re = cacheService.AddDataAsync(GroupName, LiveJsonIntegrate.MetaValues2Json(liveGroupDictionary));
                //LiveJsonIntegrate.MetaValues2Json
                //cache.SetString(GroupName, LiveJsonIntegrate.MetaValues2Json(liveGroupDictionary));

                var t4 = DateTime.Now;
                var timediff2 = t4 - t3;
                Console.WriteLine($"{driverName}_{GroupName}异步操作实时缓存耗时：{timediff2}");
                //}
                //else 
                //{
                //var groupCache = cache.Get<List<LiveGroupDictionary>>(driverName);
                //if (groupCache.Count(x => x.GroupName == GroupName) > 0)
                //{
                //    groupCache.Where(v=>v.GroupName == GroupName).FirstOrDefault().MetaTagValues = metaTagvalues;
                //}
                //else
                //{
                //    groupCache.Add(new LiveGroupDictionary()
                //    {
                //        GroupName= GroupName,
                //        MetaTagValues = metaTagvalues
                //    });
                //}
                //}

                //引用还是赋值？？？？

                GC.Collect();
            }
            catch(Exception ex) 
            {
                LogHelper.LogWrite(ex.ToString());

			}
        }

        
    }
}
