using HTCoreServiceApp.Common;
using HTCoreServiceApp.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;

namespace HTCoreServiceApp.DataHandle
{
	public class DataStorage
	{
		private static object _locker = new();
		/// <summary>
		/// 实时数据存储至历史数据表
		/// </summary>
		public static int DataSave2DB(List<MetaTagValue> metaTagvalues,string systenName, string driverName, string GroupName, long hdatetime)
		{
            var t5 = DateTime.Now;
            //lock (_locker)
            //{
            var sysTypeList = metaTagvalues.Select(t => t.SysType).Distinct().ToList();
			if(sysTypeList.Count == 1 && sysTypeList[0] == null)
			{
                string sql = "";
                //string tableName = $"{GroupName}_etldata";
                string tableName = $"ED_{systenName}_{driverName}_{GroupName}";
                sql += $"INSERT INTO dbo.{tableName} ";
                string field = "HDATETIME,HTIME";
                string value = "";
                var htime = hdatetime / 1000;
                //long hdatetime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
                value += $"{hdatetime},{htime}";
                foreach (MetaTagValue metaTagValue in metaTagvalues)
                {
                    field += $",{metaTagValue.TagName}";
                    decimal d_value = 0.00000000M;
                    if (metaTagValue.DataType == (short)DataType.BOOL)
                    {
                        if (metaTagValue.TagValue == "True")
                        {
                            value += $",1.00000000";
                        }
                        else
                        {
                            value += $",0.00000000";
                        }
                    }
                    else
                    {
                        try
                        {
                            d_value = decimal.Parse(metaTagValue.TagValue);

                            string s_d_value = string.Format("{0:#,0.########}", d_value).Replace(",", "");
                            value += $",{s_d_value}";
                        }
                        catch
                        {
                            value += $",null";//null
                        }

                    }
                }
                sql += $"({field}) VALUES ({value});";
                var t9 = DateTime.Now;
                //string ConnectionStrings = AESKeyEncrypt.DecryptDES(ConfigHelper.ReadAppSettings("ConnectionStrings", "SqlServer"));
                var db =new SqlSugarClient(StaticLibrary.DBConfig);
                try
                {
                    
                    int sqlExecuteResult = db.Ado.ExecuteCommand(sql);  //db.Database.ExecuteSqlRaw(sql);
                    
                    if (sqlExecuteResult == 1)
                    {
                        Console.WriteLine($"{driverName}_{GroupName} 写入成功： {sqlExecuteResult}");
                    }
                    else
                    {
                        Console.WriteLine($"{driverName}_{GroupName} 写入失败：{sqlExecuteResult}");
                    }
                    db.Dispose();

                    var t6 = DateTime.Now;
                    var timediff3 = t6 - t9;
                    Console.WriteLine($"{driverName}_{GroupName}数据储存耗时：{timediff3}");

                    return 0;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{driverName}_{GroupName} 写入出错：{ex}");
                    db.Dispose();
                    return -1;
                }

            }
			else
			{
                var sqlcol = "";
                foreach (var sysType in sysTypeList)
                {
                    sqlcol = "";
                    var metaTagofSys = metaTagvalues.Where(x => x.SysType == sysType).ToList();
                    string sql = "";
                    //string tableName = $"{GroupName}_etldata";
                    string tableName = $"ED_{systenName}_{driverName}_{GroupName}_{sysType}";
                    sql += $"INSERT INTO dbo.{tableName} ";
                    string field = "HDATETIME,HTIME";
                    string value = "";
                    var htime = hdatetime / 1000;
                    //long hdatetime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
                    value += $"{hdatetime},{htime}";
                    foreach (MetaTagValue metaTagValue in metaTagofSys)
                    {
                        field += $",{metaTagValue.TagName}";
                        decimal d_value = 0.00000000M;
                        if (metaTagValue.DataType == (short)DataType.BOOL)
                        {
                            if (metaTagValue.TagValue == "True")
                            {
                                value += $",1.00000000";
                            }
                            else
                            {
                                value += $",0.00000000";
                            }
                        }
                        else
                        {
                            try
                            {
                                //var t11 = DateTime.Now;
                                
                                //d_value = decimal.Parse(metaTagValue.TagValue);
                                //var t12 = DateTime.Now;
                                //var timediff12 = t12 - t11;
                                //Console.WriteLine($"{driverName}_{GroupName}string转decimal耗时：{timediff12}");

                                //string s_d_value = string.Format("{0:#,0.########}", d_value).Replace(",", "");
                                //var t13 = DateTime.Now;
                                //var timediff13 = t13 - t11;
                                //Console.WriteLine($"{driverName}_{GroupName}处理科学计数法耗时：{timediff13}");

                                value += $",{metaTagValue.TagValue}";
                            }
                            catch
                            {
                                value += $",null";//null
                            }

                        }
                    }
                    sql += $"({field}) VALUES ({value});";
                    sqlcol += sql;


                    var t7 = DateTime.Now;
                    var timediff7 = t7 - t5;
                    Console.WriteLine($"{driverName}_{GroupName}SQL数据整理耗时：{timediff7}");

                    //string ConnectionStrings = AESKeyEncrypt.DecryptDES(ConfigHelper.ReadAppSettings("ConnectionStrings", "SqlServer"));
                    var db = new SqlSugarClient(StaticLibrary.DBConfig);
                    var t9 = DateTime.Now;
                    try
                    {
                        int sqlExecuteResult = db.Ado.ExecuteCommand(sqlcol); //db.Database.ExecuteSqlRaw(sqlcol);
                        if (sqlExecuteResult == 1)
                        {
                            Console.WriteLine($"{driverName}_{GroupName}写入成功：{sqlExecuteResult}行");
                        }
                        else
                        {
                            Console.WriteLine($"{driverName}_{GroupName}写入失败：{sqlExecuteResult}");
                        }
                        db.Dispose();
                        //return 0;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"{driverName}_{GroupName}写入出错：{ex}");
                        db.Dispose();
                        //return -1;
                    }
                    var t6 = DateTime.Now;
                    var timediff3 = t6 - t9;
                    Console.WriteLine($"{driverName}_{GroupName}数据储存耗时：{timediff3}");
                    
                }
                

                return 0;

            }
            
            #region 旧代码
            /*
            string sql = "";
			//string tableName = $"{GroupName}_etldata";
			string tableName = $"ETLDATA_{driverName}_{GroupName}";
			sql += $"INSERT INTO dbo.{tableName} ";
			string field = "HDATETIME";
			string value = "";
			//long hdatetime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
			value += hdatetime;
			foreach (MetaTagValue metaTagValue in metaTagvalues)
			{
				field += $",{metaTagValue.TagName}";
				decimal d_value = 0.00000000M;
				if (metaTagValue.DataType == (short)DataType.BOOL)
				{
					if (metaTagValue.TagValue == "True")
					{
						value += $",1.00000000";
					}
					else
					{
						value += $",0.00000000";
					}
				}
				else
				{
					try
					{
						d_value = decimal.Parse(metaTagValue.TagValue);

						string s_d_value = string.Format("{0:#,0.########}", d_value).Replace(",", "");
						value += $",{s_d_value}";
					}
					catch
					{
						value += $",null";//null
					}

				}
			}
			sql += $"({field}) VALUES ({value});";

			string ConnectionStrings = ConfigHelper.ReadAppSettings("ConnectionStrings", "SqlServer");
			var db = new ScadaContext(ConnectionStrings);
			try
			{
				int sqlExecuteResult = db.Database.ExecuteSqlRaw(sql);
				if (sqlExecuteResult == 1)
				{
					Console.WriteLine($"写入成功：{sqlExecuteResult}行");
				}
				else
				{
					Console.WriteLine($"写入失败：{sqlExecuteResult}");
				}
				return 0;
			}
			catch (Exception ex)
			{
				Console.WriteLine($"写入出错：{ex}");
				return -1;
			}
            //}
			*/
            #endregion
        }
    }
}
