using HTCoreServiceApp.Common;
using HTCoreServiceApp.DataHandle;
using HTCoreServiceApp.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;

//using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System;
using System.Data;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using WebFirst.Entities;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace HTCoreServiceApp.WebApi
{
    [ApiController]
    //[Route("[controller]/[action]")]
    public class DataLiveCache //: ControllerBase
    {

        //[HttpGet]
        public async Task<string?> Get()  //请求方法行为
        {
            return "hello，这里是恒拓实时服务！";
        }
        //[HttpGet]
        public async Task<string> GetName(string Name)  //请求方法行为
        {
            return $"服务器收到字符串：{Name}";
        }

        public async Task<string> GetLiveSystemData(string systemName)
        {
            var db = new SqlSugarClient(StaticLibrary.DBConfig);
            var systemId = db.Queryable<MetaSystem>().Where(x => x.SystemName == systemName).First().SystemId;
            var groupList = db.Queryable<MetaGroup>().Where(x => x.SystemId == systemId).ToList();
            
            var driverdataDict = new Dictionary<string, List<Dictionary<string, JToken>>>();
            //var jlist = new List<JObject>();
            //var driverList  = new List<string>();
            foreach (var group in groupList)
            {
                var groupdataDict = new Dictionary<string, JToken>();

                var groupName = group.GroupName;


                var driverName = db.Queryable<MetaDriver>().Where(x => x.DriverId == group.DriverId).First().DriverName;
                
                
                var data = JsonConvert.DeserializeObject(new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(groupName).Result);//StaticLibrary.MemoryCacheHelper.GetString(groupName)

                groupdataDict.Add( groupName, (JToken?)data ); 

                if(driverdataDict.Keys.Contains(driverName))
                {
                    driverdataDict[driverName].Add(groupdataDict);
                }
                else
                {
                    driverdataDict.Add(driverName,new List<Dictionary<string, JToken>>() { groupdataDict });
                }
                //driverList.Add(driverName);
                //if (json.ContainsKey(driverName))
                //{
                //    json.Add(driverName, new JObject(groupName, data));
                //}
                //jlist.Add(new JObject(groupName, data));
            }
            db.Close();
            db.Dispose();
            var rejson = JsonConvert.SerializeObject(driverdataDict, Newtonsoft.Json.Formatting.Indented);
            return rejson;
            
            //var groupJson = new JObject
            //    {
            //        { groupName, (JToken?)data }
            //    };

            //json.Add(driverName, groupJson);
        }
        public async Task<string> GetLiveDriverData(string driverName)
        {
            var dict = new Dictionary<string, string>();
            var json = new JObject();
            var db = new SqlSugarClient(StaticLibrary.DBConfig);
            var driverId = db.Queryable<MetaDriver>().Where(x=>x.DriverName == driverName).First().DriverId;
            var groupList = db.Queryable<MetaGroup>().Where(x=>x.DriverId == driverId).ToList();
            foreach(var group in groupList )
            {
                var groupName = group.GroupName;
                var data = JsonConvert.DeserializeObject(new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(groupName).Result);
                json.Add(groupName, (JToken?)data);
            }
            db.Close();
            db.Dispose();
            return json.ToString();
        }
        //[HttpGet]
        public async Task<string> GetLiveGroupData(string groupName) 
        {
			//var cache = StaticLibrary.MemoryCacheHelper.Get<List<LiveGroupDictionary>>(driverName).Where(x=>x.GroupName == groupName).First();
			//var val = new List<LiveGroupDictionary>();
			//StaticLibrary.MemoryCacheHelper.TryGetValue(driverName,out val);
			//return LiveJsonIntegrate.MetaValues2Json(val.FirstOrDefault());

			//public static string StringToJson(string JsonString)
			//{ // string 转换成Json JsonDocument jsonDocument = JsonDocument.Parse(JsonString);//这里序列化成json return JsonSerializer.Serialize(jsonDocument.RootElement); }//在main中调用
            
			try
            {
                //var result = StaticLibrary.MemoryCacheHelper.GetString(groupName);

                //Console.WriteLine(result);
                //return result;
                //return valueJson.ToString();
                return new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(groupName).Result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        //[HttpGet]
        public async Task<string> GetLiveTagData(string groupName, string tagName)
        {
            //var cache = StaticLibrary.MemoryCacheHelper.Get<List<LiveGroupDictionary>>(driverName).Where(x=>x.GroupName == groupName).First();
            //var val = new List<LiveGroupDictionary>();
            //StaticLibrary.MemoryCacheHelper.TryGetValue(driverName,out val);
            //return LiveJsonIntegrate.MetaValues2Json(val.FirstOrDefault());


            //!!!!重要，校验有无groupName

            string value = "";
            if (tagName != null && tagName != "")
            {
                var jLiveData = new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(groupName).Result;
                JObject valueJson = JObject.Parse(jLiveData);
                value = valueJson[tagName].ToString();
            }
            return value;
        }
        //[HttpGet]
        //public string GetLiveTagData(string driverName, string groupName ,string tagName)
        //{
        //var cache = StaticLibrary.MemoryCacheHelper.Get<List<LiveGroupDictionary>>(driverName).Where(x => x.GroupName == groupName).First();
        //return LiveJsonIntegrate.MetaTagValue2Json(cache, tagName);
        //}

        public async Task<string> GetLiveAllSystemData()
        {
            var json = new JObject();
            var db = new SqlSugarClient(StaticLibrary.DBConfig);
            var systemList = db.Queryable<MetaSystem>().ToList();//.Where(x => x.SystemName == systemName).First().SystemId;
            foreach(var system in systemList)
            {
                var systemId = system.SystemId;
                var groupList = db.Queryable<MetaGroup>().Where(x => x.SystemId == systemId).ToList();
                foreach (var group in groupList)
                {
                    var data = JsonConvert.DeserializeObject(new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(group.GroupName).Result);
                    json.Merge((JToken?)data);
                }
            }
            
            db.Close();
            db.Dispose();

            return json.ToString();

        }

        public async Task<string> GetLiveSystemAllData(string systemName)
        {
            var json = new JObject();
            var db = new SqlSugarClient(StaticLibrary.DBConfig);
            var systemId = db.Queryable<MetaSystem>().Where(x => x.SystemName == systemName).First().SystemId;
            var groupList = db.Queryable<MetaGroup>().Where(x => x.SystemId == systemId).ToList();
            foreach (var group in groupList)
            {
                


                var data = JsonConvert.DeserializeObject(new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(group.GroupName).Result);
                json.Merge((JToken?)data);

                
            }
            db.Close();
            db.Dispose();

            return json.ToString();

            //var groupJson = new JObject
            //    {
            //        { groupName, (JToken?)data }
            //    };

            //json.Add(driverName, groupJson);
        }
        public async Task<string> GetLiveDriverAllData(string driverName)
        {
            var dict = new Dictionary<string, string>();
            var json = new JObject();
            var db = new SqlSugarClient(StaticLibrary.DBConfig);
            var driverId = db.Queryable<MetaDriver>().Where(x => x.DriverName == driverName).First().DriverId;
            var groupList = db.Queryable<MetaGroup>().Where(x => x.DriverId == driverId).ToList();
            foreach (var group in groupList)
            {
                var groupName = group.GroupName;
                var data = JsonConvert.DeserializeObject(new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(groupName).Result);
                json.Merge((JToken?)data);
            }
            db.Close();
            db.Dispose();
            return json.ToString();
        }
        //[HttpGet]
        public async Task<string> GetLiveGroupAllData(string groupName)
        {
            //var cache = StaticLibrary.MemoryCacheHelper.Get<List<LiveGroupDictionary>>(driverName).Where(x=>x.GroupName == groupName).First();
            //var val = new List<LiveGroupDictionary>();
            //StaticLibrary.MemoryCacheHelper.TryGetValue(driverName,out val);
            //return LiveJsonIntegrate.MetaValues2Json(val.FirstOrDefault());

            //public static string StringToJson(string JsonString)
            //{ // string 转换成Json JsonDocument jsonDocument = JsonDocument.Parse(JsonString);//这里序列化成json return JsonSerializer.Serialize(jsonDocument.RootElement); }//在main中调用

            try
            {
                //var result = StaticLibrary.MemoryCacheHelper.GetString(groupName);

                //Console.WriteLine(result);
                //return result;
                //return valueJson.ToString();
                return new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(groupName).Result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public async Task<string> GetLiveCustomData(string ApiName)
        {
            try
            {
                
                var json = new Dictionary<string,string>();
                //var restring = "";
                var db = new SqlSugarClient(StaticLibrary.DBConfig);
                var tcollstart = DateTime.Now;
                var apigroup = await db.Ado.GetDataTableAsync($"SELECT\n\tTagID,\n\tTagName,\n\tDescription,\n\tDataType,\n\tGroupID,\n\tSystemID \nFROM\n\tHT_Api_{ApiName}");//<HTApiBase>
                var tcollend = DateTime.Now;
                var timecolldiff = tcollend - tcollstart;
                Console.WriteLine($"单次提取：{timecolldiff},", ConsoleColor.Red);
                var groupedItems = apigroup.AsEnumerable().GroupBy(item => item["GroupID"]);

                var metagroup = db.Queryable<MetaGroup>().ToList();

                //var jsonlist = new List<JObject>();

                //int li = 0;
                //var cancellationTokens = new List<CancellationToken>();
                foreach (var group in groupedItems)
                {
                    //var cancellationToken = new CancellationTokenSource();
                    //cancellationTokens.Add(cancellationToken.Token);



                    //await Task.Run(() =>
                    //{
                    try
                    {
                        var groupid = group.Key;
                        var groupname = metagroup.Where(x => x.GroupId == Int16.Parse(groupid.ToString())).First().GroupName;
                        var datasrc = new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(groupname).Result;
                        if (datasrc.Length >= 1)
                        {
                            //var dataJson = JObject.Parse(datasrc);
                            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(datasrc);
                            foreach (var tag in group)
                            {
                                try
                                {
                                    //var tcollstart = DateTime.Now;
                                    json.Add((string)tag["TagName"], dict[(string)tag["TagName"]]);
                                    //var tcollend = DateTime.Now;
                                    //var timecolldiff = tcollend - tcollstart;
                                    //Console.WriteLine($"单次提取：{timecolldiff},",ConsoleColor.Red);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.Message);
                                    continue;
                                }
                            }
                        }
                        else
                        {
                               
                        }
                    }
                    catch (Exception ex)
                    { 
                        Console.WriteLine(ex.Message);
                    }
                    //});
                    
                }


                //db.Close();
                //db.Dispose();

                //return Regex.Replace(json.ToString(), @"\\u0022", "\""); 
                return JsonConvert.SerializeObject(json);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        //private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
        //public async Task<string> GetLiveCustomData(string ApiName)
        //{
        //    try
        //    {
        //        var json = new JObject();
        //        //var restring = "";
        //        var db = new SqlSugarClient(StaticLibrary.DBConfig);
        //        var apigroup = db.Ado.SqlQuery<HTApiBase>($"SELECT * FROM HT_Api_{ApiName}");
        //        var groupedItems = apigroup.GroupBy(item => item.GroupID);

        //        var metagroup = db.Queryable<MetaGroup>().ToList();

        //        var jsonlist = new List<JObject>();

        //        int li = 0;
        //        var cancellationTokens = new List<CancellationToken>();
        //        foreach (var group in groupedItems)
        //        {
        //            var cancellationToken = new CancellationTokenSource();
        //            cancellationTokens.Add(cancellationToken.Token);

        //            var gjson = new JObject(); 

        //            Task.Run(() =>
        //            {
        //                try
        //                {
        //                    var groupid = group.Key;
        //                    var groupname = metagroup.Where(x => x.GroupId == groupid).First().GroupName;
        //                    var datasrc = new CacheService(StaticLibrary.MemoryCache).GetDataFromDatabaseAsync(groupname).Result;
        //                    if (datasrc.Length >= 1)
        //                    {
        //                        var dataJson = JObject.Parse(datasrc);
        //                        var nym = 0;
        //                        //value = dataJson[tagName].ToString();
        //                        foreach (var tag in group)
        //                        {
        //                            //json.Merge((JToken?)data)
        //                            try
        //                            {
        //                                gjson.Add(tag.TagName, dataJson[tag.TagName]);
        //                            }
        //                            catch (Exception ex)
        //                            {
        //                                Console.WriteLine(ex.Message);
        //                                nym++;
        //                                continue;
        //                            }
        //                            nym++;
        //                        }
        //                        jsonlist.Add(gjson);
        //                        cancellationToken.Cancel();
        //                    }
        //                    else
        //                    {
        //                        cancellationToken.Cancel();
        //                    }
        //                }
        //                catch(Exception ex)
        //                { Console.WriteLine(ex.Message); }
        //            }, cancellationTokens[li]);
        //            li++;
        //        }

        //        //CancellationTokenSource source = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokens.ToArray());

        //        //var waitTask = Task.Run(() => source.Token.WaitHandle.WaitOne(), source.Token);



        //        try
        //        {
        //            // 等待任务完成，如果在等待过程中被取消，则会抛出TaskCanceledException
        //            //waitTask.Wait();
        //            var waitflag = true;
        //            while (waitflag)
        //            {
        //                Thread.Sleep(10);
        //                var tempbool = true;
        //                foreach(var tokens in cancellationTokens)
        //                {
        //                    tempbool = tempbool && tokens.IsCancellationRequested;
        //                }
        //                waitflag = !tempbool;
        //            }
        //            db.Close();
        //            db.Dispose();


        //            foreach (var jjson in jsonlist)
        //            {
        //                json.Merge(jjson, new() { MergeArrayHandling = MergeArrayHandling.Union });
        //            }
        //            return json.ToString();

        //        }
        //        catch (AggregateException ae)
        //        {
        //            // 处理任何等待过程中发生的异常
        //            foreach (var ex in ae.InnerExceptions)
        //            {
        //                Console.WriteLine(ex.Message);
        //            }
        //            db.Close();
        //            db.Dispose();


        //            foreach (var jjson in jsonlist)
        //            {
        //                json.Merge(jjson, new() { MergeArrayHandling = MergeArrayHandling.Union });
        //            }
        //            return json.ToString();
        //        }

        //        db.Close();
        //        db.Dispose();


        //        foreach(var jjson in jsonlist)
        //        {
        //            json.Merge(jjson, new() { MergeArrayHandling = MergeArrayHandling.Union });
        //        }
        //        return json.ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        return ex.Message;
        //    }
        //}
    }
}
