using BPA.MES.Base.Application.Entitys.KepData;
using FreeRedis;
using Furion.ClayObject.Extensions;
using Furion.RemoteRequest;
using Newtonsoft.Json;
//using ServiceStack.Redis;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using static ServiceStack.Diagnostics.Events;

namespace BPA.MES.Base.Application.Services.KepServerDataService.Services
{
    [AllowAnonymous]
    [ApiDescriptionSettings("大屏数据", Order = 4, Name = "KepData", Tag = "大屏数据", KeepName = true, SplitCamelCase = true, KeepVerb = true)]
    public class KepDataService: KepServerSqlsugar, IKepDataService,ITransient, IDynamicApiController
    {
        public KepDataService()
        { 

        }
        [HttpPost]
        public async Task<List<object>> GetList()
        {
            //to_days(now()) - to_days(o._TIMESTAMP) = 1
            // to_days(o._TIMESTAMP) = to_days(now())
            var list = KepDb.Queryable<object>().AS("ch01_device1", "o").Where(" to_days(o._TIMESTAMP) = to_days(now())").ToList();
            //var data =await KepDb.Queryable<ch1_device1>().Where(x=> SqlFunc.DateIsSame(x._TIMESTAMP, DateTime.Now)).Take(1000).ToListAsync();
            //var dicdatass = KepDb.Queryable<ch1_device1>().GroupBy(x => x._NAME).Where(x => SqlFunc.DateIsSame(x._TIMESTAMP, DateTime.Now)).Select(x => x._NAME).ToArray();
            //var dicdata = KepDb.Queryable<ch1_device1>().GroupBy(x => x._NAME).Where(x => SqlFunc.DateIsSame(x._TIMESTAMP, DateTime.Now)).Select(x=>x._NAME).ToDictionary();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            //DataTable table = new DataTable();
            //foreach (var item in dicdatass)
            //{
            //    var key = item.ToString();
            //    var values = data.Where(x => x._NAME == key).Select(x=>x._VALUE).ToList();
            //    dic.Add(key, values);
            //}
            //var JsonString = JsonConvert.SerializeObject(dic);
            return list;
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<bool> DeleteKep()
        {
            var sql = "delete from ch01_device1 where 1=1 order by id limit 1000;";
            var list = KepDb.Ado.ExecuteCommand(sql);
            return true;
        }

        public async Task<string> GetA1()
        {
            //await using (RedisClient client = new RedisClient("10.2.1.21", 6379, "1178661552398188544", 0))
            //{
            //    if (client == null) return string.Empty;
            //    string configData = client.Get<string>("ns=2;s=CH1.Device1.A1");
            //    return configData;

            //}
            return "";
        }


        [HttpGet]
        [AllowAnonymous]
        public Task<bool> CodeFirst()
        {
            var types = Assembly.Load("BPA.MES.Base.Application").GetTypes()
                .Where(x => x.GetCustomAttribute<SugarTable>() != null
                            && x.Namespace == "BPA.MES.Base.Application.Entitys.KepData").ToArray();
            KepDb.CodeFirst.InitTables(types);
            return Task.FromResult(true);
        }


        /// <summary>
        /// 添加报警限制
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<bool> AddDataVAlarmLimit(DataVAlarmLimit inputDto)
        {
            inputDto.Id = YitIdHelper.NextId().ToString();
            var res = await KepDb.Insertable<DataVAlarmLimit>(inputDto).ExecuteCommandAsync();
            return res > 0;
        }

        /// <summary>
        /// 修改报警限制
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<bool> UpdateDataVAlarmLimit(DataVAlarmLimit inputDto)
        {
            var res = await KepDb.Updateable<DataVAlarmLimit>(inputDto).ExecuteCommandAsync();
            return res > 0;
        }

        /// <summary>
        /// 获取报警限制
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<SqlSugarPagedList<DataVAlarmLimit>> GetDataVAlarmLimitList(RequestPage input)
        {
            var entity = await KepDb.Queryable<DataVAlarmLimit>()
                .ToPagedListAsync(input.PageIndex, input.PageSize);
            SqlSugarPagedList<DataVAlarmLimit> output = entity.Adapt<SqlSugarPagedList<DataVAlarmLimit>>();
            return output;
        }

        /// <summary>
        /// 删除报警限制
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<bool> DelDataVAlarmLimitList(string id)
        {
            var res = await KepDb.Deleteable<DataVAlarmLimit>().Where(x=>x.Id==id).ExecuteCommandAsync();
            return res>0;
        }

        [HttpGet]
        [AllowAnonymous]
        public Dictionary<string, string> GetDataVList()
        {
          
           // var client = new ServiceStack.Redis.RedisClient("10.2.1.21", 6379, "1178661552398188544");

            //var client = new RedisClient("10.2.1.21:6379,password=1178661552398188544,defaultDatabase=13");
           
          
            try
            {
                var client = new FreeRedis.RedisClient("10.2.1.21:6379,password=1178661552398188544,defaultDatabase=0");
                var res = new Dictionary<string, string>();

                for (int i = 1; i <= 28; i++)
                {
                    var str = "ns=2;WFZ.Device1.A" + i;
                    var value = client.Get<string>(str);
                    if (!string.IsNullOrEmpty(value)&&i!=4)
                    {
                        if (value.Length>=4)
                        {
                            value = value.Substring(0, 2);
                        }
                    }
                    res.Add("Device1.A" + i, value);
                }
                for (int i = 1; i <=31; i++)
                {
                    var str = "ns=2;WFZ.Device2.A" + i;
                    var value = client.Get<string>(str);
                    if (!string.IsNullOrEmpty(value) )
                    {
                        if (value.Length >= 4)
                        {
                            value = value.Substring(0, 2);
                        }
                    }
                    res.Add("Device2.A" + i, value);
                }
                for (int i = 1; i <=7; i++)
                {
                    var str = "ns=2;WFZ.Device3.A" + i;
                    var value = client.Get<string>(str);
                    res.Add("Device3.A" + i, value);
                }
                for (int i = 1; i <= 1; i++)
                {
                    var str = "ns=2;WFZ.Device4.A" + i;
                    var value = client.Get<string>(str);
                    res.Add("Device4.A" + i, value);
                }
                return res;
            }
            catch (Exception e)
            {
                var res = new Dictionary<string, string>();
                return res;

            }
          
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<List<List<string>>> GetLogsAsync()
        {
            var result = new List<List<string>>();
            var entity = await KepDb.Queryable<AlarmLog>().Where(x=>x.CreateTime.Date==DateTime.Now.Date).ToListAsync();

            foreach (var item in entity)
            {
                var data = new List<string>();
                var thisData = new object();

                thisData = item.GetType().GetProperty("Name").GetValue(item, null);
                data.Add(thisData == null ? "" : thisData.ToString());
                thisData = item.GetType().GetProperty("ValueStr").GetValue(item, null);
                data.Add(thisData == null ? "" : thisData.ToString());
                thisData = item.GetType().GetProperty("CreateTime").GetValue(item, null);
                data.Add(thisData == null ? "" : thisData.ToString());

                result.Add(data);
            }
            return result;
        }
    }
}
