using System.Threading;
using BLW_Log.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RestSharp.Authenticators;
using RestSharp;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.AspNetCore.Http.HttpResults;
using System.Collections.Generic;
using System.Text;
using Commonlib;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using System.Data.SqlClient;
using NLog;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Common;
using System.Collections.Concurrent;
using System.Data;
using NLog.Config;
using Microsoft.AspNetCore.SignalR;
using BLW_Log.Push;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using LiteDB;
using Microsoft.AspNetCore.StaticFiles;
using System.ComponentModel.DataAnnotations;
using Mono.Security.Cryptography;
using static IronPython.Runtime.Profiler;
using System.Text.Json;
using System.Net.WebSockets;
using BLW_Log.services;
using DAL.PGModels;
namespace BLW_Log.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LowerMachineLogController : ControllerBase
    {
        public readonly IMemoryCache _memoryCache;
        private readonly IHubContext<DataPush> _hubContext;
        private readonly PostgresContext dbContext;

        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        public LowerMachineLogController(PostgresContext db, IMemoryCache memoryCache/* ILogger<LowerMachineLogController> logger*/, IHubContext<DataPush> hubbb)
        {
            this.dbContext = db;
            _memoryCache = memoryCache;
            this._hubContext = hubbb;
        }
        [HttpPost()]
        public async Task AddLog()
        {
            string sssttt = "";
            try
            {
                var readResult = Request.BodyReader.ReadAsync().Result;
                Request.BodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
                string body = Encoding.UTF8.GetString(readResult.Buffer.FirstSpan);
                sssttt = body;
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                this._logger.Error(ex.Message);
                this._logger.Error("数据为： " + sssttt);
                this._logger.Error(ex.StackTrace);
            }
        }


        [HttpPost()]
        public IActionResult RunLongTask()
        {

            for (int i = 0; i < 3; i++)
            {
                Task T = new Task(async () =>
                   {
                       await Task.Delay(1500);
                       Console.WriteLine("1111111111");
                   });
                //tasks.EnqueueTask(T);
            }
            return Ok("任务已开始后台执行");
        }

        [HttpPost()]
        public async Task AddIOTLog()
        {
            //string sssttt = "";
            //try
            //{
            //    var readResult = Request.BodyReader.ReadAsync().Result;
            //    Request.BodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
            //    string body = Encoding.UTF8.GetString(readResult.Buffer.FirstSpan);
            //    sssttt = body;
            //    Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
            //    string topic = dic["topic"];
            //    string payload = dic["payload"];

            //    this._logger.Info("Topic: " + topic);
            //    this._logger.Info("PayLoad: " + payload);

            //    IOTMonitorData igs = JsonConvert.DeserializeObject<IOTMonitorData>(payload);

            //    //using (var a = new LowmachinelogContext())
            //    //{

            //    //    IotMonitorlog iot = new IotMonitorlog();
            //    //    iot.TriggerTime = igs.TriggerTime;
            //    //    iot.RoomNumber = igs.RoomNumber;
            //    //    iot.RequestId = igs.RequestId;
            //    //    iot.Platform = igs.Platform;
            //    //    iot.Step = igs.Step;
            //    //    iot.CommandDescription = igs.CommandDescription;
            //    //    iot.HotelName = igs.HotelName;

            //    //    int abc = 0;
            //    //    int.TryParse(igs.HotelId ?? "0", out abc);
            //    //    iot.HotelId = abc;
            //    //    iot.HotelCode = igs.HotelCode.ToString();
            //    //    a.IotMonitorlogs.Add(iot);
            //    //    a.SaveChanges();
            //    //    a.WebapiMonitorlogs.AsNoTracking().ToArray();
            //    //}



            //    IotMonitorlog iot = new IotMonitorlog();
            //    iot.TriggerTime = igs.TriggerTime;
            //    iot.RoomNumber = igs.RoomNumber;
            //    iot.RequestId = igs.RequestId;
            //    iot.Platform = igs.Platform;
            //    iot.Step = igs.Step;
            //    iot.CommandDescription = igs.CommandDescription;
            //    iot.HotelName = igs.HotelName;

            //    int abc = 0;
            //    int.TryParse(igs.HotelId ?? "0", out abc);
            //    iot.HotelId = abc;
            //    iot.HotelCode = igs.HotelCode.ToString();
            //    dbContext.IotMonitorlogs.Add(iot);
            //    await dbContext.SaveChangesAsync();
            //    //dbContext.WebapiMonitorlogs.AsNoTracking().ToArray();
            //}
            //catch (Exception ex)
            //{
            //    this._logger.Error(ex.Message);
            //    this._logger.Error("数据为： " + sssttt);
            //    this._logger.Error(ex.StackTrace);
            //}
        }

        [HttpPost()]
        public async Task AddTCLLog()
        {
            string sssttt = "";
            try
            {
                var readResult = Request.BodyReader.ReadAsync().Result;
                Request.BodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
                string body = Encoding.UTF8.GetString(readResult.Buffer.FirstSpan);
                sssttt = body;
                this._logger.Error("body: " + body);
                Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
                string topic = dic["topic"];
                string payload = dic["payload"];

                TCLMonitorData igs = JsonConvert.DeserializeObject<TCLMonitorData>(payload);

                TclTvMonitorlog iot = new TclTvMonitorlog();
                iot.RoomNumber = igs.RoomNumber;
                iot.HotelCode = igs.HotelCode;
                iot.Step = igs.Step;
                if (!string.IsNullOrEmpty(igs.RequestTime))
                {
                    iot.RequestTime = DateTime.Parse(igs.RequestTime);
                }
                iot.RequestCommand = igs.RequestCmd;
                iot.RequestId = igs.RequestId;

                if (!string.IsNullOrEmpty(igs.ResponseMsg))
                {
                    string IDD = igs.RequestId;
                    var E = dbContext.TclTvMonitorlogs.SingleOrDefault(A => A!=null&& A.RequestId.Equals(IDD));
                    if (E != null)
                    {
                        E.ResponseMsg = igs.ResponseMsg;
                        if (!string.IsNullOrEmpty(igs.ResponseTime))
                        {
                            E.ResponseTime = DateTime.Parse(igs.ResponseTime);
                        }
                        dbContext.TclTvMonitorlogs.Update(E);
                        await dbContext.SaveChangesAsync();
                    }
                }
                else
                {
                    dbContext.TclTvMonitorlogs.Add(iot);
                    await dbContext.SaveChangesAsync();
                }

            }
            catch (Exception ex)
            {
                this._logger.Error(ex.Message);
                this._logger.Error("数据为： " + sssttt);
                this._logger.Error(ex.StackTrace);
            }
        }

        /// <summary>
        /// 创维电视
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public async Task AddSkyWorthLog()
        {
            string sssttt = "";
            try
            {
                var readResult = Request.BodyReader.ReadAsync().Result;
                Request.BodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
                string body = Encoding.UTF8.GetString(readResult.Buffer.FirstSpan);
                this._logger.Error("body: " + body);
                sssttt = body;
                Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
                string topic = dic["topic"];
                string payload = dic["payload"];

                SkyWorthMonitorData igs = JsonConvert.DeserializeObject<SkyWorthMonitorData>(payload);

                SkyworthTvMonitorlog iot = new SkyworthTvMonitorlog();
                iot.HotelCode = igs.HotelCode;
                iot.RoomNum = igs.RoomNumber;
                iot.Step = igs.Step;
                if (!string.IsNullOrEmpty(igs.RequestTime))
                {
                    iot.RequestTime = DateTime.Parse(igs.RequestTime);
                }
                iot.RequestCommand = igs.RequestCmd;
                iot.RequestId = igs.RequestId;

                if (!string.IsNullOrEmpty(igs.ResponseMsg))
                {
                    string ID = igs.RequestId;
                    var E = dbContext.SkyworthTvMonitorlogs.SingleOrDefault(A => A.RequestId.Equals(ID));
                    if (E != null)
                    {
                        E.ResponseMsg = igs.ResponseMsg;
                        if (!string.IsNullOrEmpty(igs.ResponseTime))
                        {
                            E.ResponseTime = DateTime.Parse(igs.ResponseTime);
                        }
                        dbContext.SkyworthTvMonitorlogs.Update(E);
                        await dbContext.SaveChangesAsync();
                    }
                }
                else
                {
                    dbContext.SkyworthTvMonitorlogs.Add(iot);
                    await dbContext.SaveChangesAsync();
                }

            }
            catch (Exception ex)
            {
                this._logger.Error(ex.Message);
                this._logger.Error("数据为： " + sssttt);
                this._logger.Error(ex.StackTrace);
            }
        }

        [HttpPost()]
        public async Task AddWebAPILog()
        {
            string sssttt = "";
            try
            {
                var readResult = Request.BodyReader.ReadAsync().Result;
                Request.BodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
                string body = Encoding.UTF8.GetString(readResult.Buffer.FirstSpan);
                sssttt = body;
                Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
                string topic = dic["topic"];
                string payload = dic["payload"];

                this._logger.Info("Topic: " + topic);
                this._logger.Info("PayLoad: " + payload);

                WebAPIMonitorData igs = JsonConvert.DeserializeObject<WebAPIMonitorData>(payload);

                //using (var a = new LowmachinelogContext())
                //{

                DAL.PGModels.WebapiMonitorlog l = new DAL.PGModels.WebapiMonitorlog();
                l.MethodName = igs.MethodName;
                l.InvokStartTime = igs.InvokStart_Time;
                l.InvokEndTime = igs.InvokEnd_Time;
                l.HotelCode = igs.HotelCode;
                l.RoomNumber = igs.RoomNumber;
                l.Parameters = JsonConvert.SerializeObject(igs.Parameters);
                l.RemoteIp = igs.RemoteIP;
                dbContext.WebapiMonitorlogs.Add(l);
                await dbContext.SaveChangesAsync();
                //}
            }
            catch (Exception ex)
            {
                this._logger.Error(ex.Message);
                this._logger.Error("数据为： " + sssttt);
                this._logger.Error(ex.StackTrace);
            }
        }


        /// <summary>
        /// 获取 监控的日志数据
        /// </summary>
        /// <param name="QueryData"></param>
        /// <returns></returns>
        [HttpPost()]
        public ReturnInfo Get_Log([FromForm] string QueryData)
        {
            ReturnInfo info = new ReturnInfo();
            info.isok = true;
            try
            {
                List<DAL.PGModels.DevMonitorlog> lg = new List<DAL.PGModels.DevMonitorlog>();
                LogQuery? q = JsonConvert.DeserializeObject<LogQuery>(QueryData);

                string? st = q?.Start_Time;
                string? et = q?.End_Time;

                int PageSize = q.PageSize;
                int PageIndex = q.PageIndex;

                List<string> c11 = q.CommandType;

                int AAA = (PageIndex - 1) * PageSize;
                DateTime sst = DateTime.Parse(st);
                DateTime eet = DateTime.Parse(et);
                if (eet < sst)
                {
                    info.isok = false;
                    info.message = "结束时间不能大于开始时间";
                    return info;
                }
                var qqqq = q?.Data;

                Random ran = new Random();
                int td = ran.Next(200000, 500000);
                int TotalCount = td;

                var h11 = qqqq.Select(x => x.HotelCode);
                var r11 = qqqq.Select(x => x.RoomNumber);
                var m11 = qqqq.Select(x => x.MAC);

                //var ggg1 = dbContext.DevMonitorlogs.Where(A =>
                //                    h11.Contains(A.HotelCode)
                //                 && r11.Contains(A.RoomNo)
                //                 && m11.Contains(A.Mac)
                //                 && c11.Contains(A.CommandType)
                //                 && A.CreateTime >= sst
                //                 && A.CreateTime <= eet).OrderByDescending(A => A.CreateTime).Count();

                var ggg = dbContext.DevMonitorlogs.Where(A =>
                                                    h11.Contains(A.HotelCode)
                                                 && r11.Contains(A.RoomNo)
                                                 && m11.Contains(A.Mac)
                                                 && c11.Contains(A.CommandType)
                                                 && A.CreateTime >= sst
                                                 && A.CreateTime <= eet).OrderByDescending(A => A.CreateTime).Skip(AAA).Take(PageSize);
                //var ddd = dbContext.DevMonitorlogs.FromSqlRaw<PGModels.DevMonitorlog>(sss).ToList();
                lg = ggg.ToList();

                List<DevMonitorLogResult> lll = new();
                foreach (var item in lg)
                {
                    string? d = item.Data;
                    string nnnd = d.Trim().Replace(" ", "");
                    byte[] bbb = Tools.HEXString2ByteArray(nnnd);
                    List<byte> Frame = bbb.Skip(9).Take(2).ToList();
                    uint aaa = BitConverter.ToUInt16(Frame.ToArray(), 0);

                    DevMonitorLogResult re = new DevMonitorLogResult();
                    re.DevLog = item;

                    DevMonitorLog_EX ex = new DevMonitorLog_EX();
                    ex.FrameNo = aaa.ToString();
                    re.EXData = ex;

                    lll.Add(re);
                }

                var qqa = lll.OrderBy(x => x.DevLog.CreateTime).ToList();
                DevMonitorLogResult_WITH_Count c = new DevMonitorLogResult_WITH_Count();
                c.TotalCount = TotalCount;
                c.devMonitorLogResults = qqa;

                info.response = c;
            }
            catch (Exception ex)
            {
                info.isok = false;
                info.message = ex.Message;
            }
            return info;
        }


        /// <summary>
        /// 获取要分析的数据 
        /// </summary>
        /// <param name="QueryData"></param>
        /// <returns></returns>
        [HttpPost()]
        public ReturnInfo Get_LogAnalysis([FromBody] LogQueryAnnlysis q)
        {
            ReturnInfo info = new ReturnInfo();
            info.isok = true;
            try
            {
                List<DAL.PGModels.DevMonitorlog> lg = new List<DAL.PGModels.DevMonitorlog>();

                string? st = q?.Start_Time;
                string? et = q?.End_Time;


                DateTime sst = DateTime.Parse(st);
                DateTime eet = DateTime.Parse(et);
                if (eet < sst)
                {
                    info.isok = false;
                    info.message = "结束时间不能小于开始时间";
                    return info;
                }

                long l_st = Tools.ToUnixTimestampByMilliseconds(sst);
                long l_et = Tools.ToUnixTimestampByMilliseconds(eet);

                var qqqq = q?.Data;

                Random ran = new Random();
                int td = ran.Next(200000, 500000);
                int TotalCount = td;

                var h11 = qqqq.Select(x => x.HotelCode).FirstOrDefault();
                var r11 = qqqq.Select(x => x.RoomNumber).FirstOrDefault();
                var m11 = qqqq.Select(x => x.MAC).FirstOrDefault();

                //and AnalysisData!='[]'
                //string sss = $"""
                //         SELECT * FROM dev_monitorlog a
                //         where a."HotelCode" ='{h11}' and a."RoomNo" ='{r11}' and a."MAC" ='{m11}'
                //         and a."CreateTimeToUnixTime" BETWEEN  {l_st} and {l_et};
                //         """;
                //var ddd = dbContext.DevMonitorlogs.FromSqlRaw<PGModels.DevMonitorlog>(sss).ToList();
                var ddd = dbContext.DevMonitorlogs.Where(A => A.HotelCode.Equals(h11) && A.RoomNo.Equals(r11) && A.Mac.Equals(m11) &&
                                                A.CreateTimeToUnixTime >= l_st && A.CreateTimeToUnixTime <= (l_et));

                lg = ddd.ToList();
                List<DevMonitorLogResult> lll = new();
                foreach (var item in lg)
                {
                    string? d = item.Data;
                    string nnnd = d.Trim().Replace(" ", "");
                    byte[] bbb = Tools.HEXString2ByteArray(nnnd);
                    List<byte> Frame = bbb.Skip(9).Take(2).ToList();
                    uint aaa = BitConverter.ToUInt16(Frame.ToArray(), 0);

                    DevMonitorLogResult re = new DevMonitorLogResult();
                    re.DevLog = item;

                    DevMonitorLog_EX ex = new DevMonitorLog_EX();
                    ex.FrameNo = aaa.ToString();
                    re.EXData = ex;

                    lll.Add(re);
                }

                var qqa = lll.OrderBy(x => x.DevLog.CreateTime).ToList();
                DevMonitorLogResult_WITH_Count c = new DevMonitorLogResult_WITH_Count();
                c.TotalCount = TotalCount;
                c.devMonitorLogResults = qqa;

                info.response = c;
            }
            catch (Exception ex)
            {
                info.isok = false;
                info.message = ex.Message;
            }
            return info;
        }


        //[HttpPost()]
        //public ReturnInfo Get_IOTLog([FromForm] string QueryData)
        //{
        //    ReturnInfo info = new ReturnInfo();
        //    info.isok = true;
        //    try
        //    {
        //        List<IotMonitorlog> lg = new List<IotMonitorlog>();
        //        LogQuery? q = JsonConvert.DeserializeObject<LogQuery>(QueryData);

        //        string? st = q?.Start_Time;
        //        string? et = q?.End_Time;

        //        int PageSize = q.PageSize;
        //        int PageIndex = q.PageIndex;

        //        List<string> c11 = q.CommandType;

        //        int AAA = (PageIndex - 1) * PageSize;
        //        DateTime sst = DateTime.Parse(st);
        //        DateTime eet = DateTime.Parse(et);
        //        if (eet < sst)
        //        {
        //            info.isok = false;
        //            info.message = "结束时间不能大于开始时间";
        //            return info;
        //        }
        //        var qqqq = q?.Data;

        //        int TotalCount = 0;
        //        //using (var a = new LowmachinelogContext())
        //        //{
        //        var h11 = qqqq?.Select(x => x.HotelCode).Distinct();
        //        var r11 = qqqq?.Select(x => x.RoomNumber).Distinct();

        //        string h22 = string.Join(",", h11.Select(name => $"'{name.Replace("'", "''")}'"));
        //        string r22 = string.Join(",", r11.Select(name => $"'{name.Replace("'", "''")}'"));

        //        string sss = $"""
        //                 SELECT * FROM iot_monitorlog a
        //                 where a."HotelCode" in ({h22}) and a."RoomNumber" in ({r22})
        //                 and a."TriggerTime">='{st}' and a."TriggerTime" <='{et}' order by a."ID" DESC;
        //                 """;

        //        var ddd = dbContext.IotMonitorlogs.FromSqlRaw<IotMonitorlog>(sss).ToList();



        //        string sss111 = $"""
        //                 SELECT count("ID") FROM iot_monitorlog a
        //                 where a."HotelCode" in ({h22}) and a."RoomNumber" in ({r22}) 
        //                 and a."TriggerTime">='{st}' and a."TriggerTime" <='{et}';
        //                 """;
        //        var query_int = dbContext.Database.SqlQueryRaw<int>(sss111);

        //        foreach (var NNH in query_int)
        //        {
        //            int ccg = 0;
        //            int.TryParse(NNH.ToString(), out ccg);
        //            TotalCount += ccg;
        //        }
        //        lg = ddd;
        //        //}

        //        var qqa = lg.OrderBy(x => x.TriggerTime).ToList();
        //        DevMonitorIOTLogResult_WITH_Count c = new DevMonitorIOTLogResult_WITH_Count();
        //        c.TotalCount = TotalCount;
        //        c.devMonitorLogResults = qqa;

        //        info.response = c;
        //    }
        //    catch (Exception ex)
        //    {
        //        info.isok = false;
        //        info.message = ex.Message;
        //    }
        //    return info;
        //}

        

        /// <summary>
        /// 获取创维电视
        /// </summary>
        /// <param name="QueryData"></param>
        /// <returns></returns>
        [HttpPost()]
        public ReturnInfo Get_SkyWorthLog([FromForm] string QueryData)
        {
            ReturnInfo info = new ReturnInfo();
            info.isok = true;
            try
            {
                LogQuery? q = JsonConvert.DeserializeObject<LogQuery>(QueryData);

                string? st = q?.Start_Time;
                string? et = q?.End_Time;

                int PageSize = q.PageSize;
                int PageIndex = q.PageIndex;

                List<string> c11 = q.CommandType;

                int AAA = (PageIndex - 1) * PageSize;
                DateTime sst = DateTime.Parse(st);
                DateTime eet = DateTime.Parse(et);
                if (eet < sst)
                {
                    info.isok = false;
                    info.message = "结束时间不能大于开始时间";
                    return info;
                }
                var qqqq = q?.Data;

                int TotalCount = 1000;
                var h11 = qqqq?.Select(x => x.HotelCode).Distinct();
                var r11 = qqqq?.Select(x => x.RoomNumber).Distinct();

                var ddd= dbContext.SkyworthTvMonitorlogs.Where(A=>h11.Contains(A.HotelCode)&&r11.Contains(A.RoomNum)&&A.RequestTime>=sst&&A.RequestTime<=eet)
                    .Skip((PageIndex-1)*PageSize).Take(PageSize)
                    .ToList();

                var qqa = ddd.OrderBy(x => x.RequestTime).ToList();
                SSS c = new SSS();
                c.TotalCount = TotalCount;
                c.SkyworthTvMonitorlogs = qqa;

                info.response = c;
            }
            catch (Exception ex)
            {
                info.isok = false;
                info.message = ex.Message;
            }
            return info;
        }



        /// <summary>
        /// 获取创维电视
        /// </summary>
        /// <param name="QueryData"></param>
        /// <returns></returns>
        [HttpPost()]
        public ReturnInfo Get_TCLLog([FromForm] string QueryData)
        {
            ReturnInfo info = new ReturnInfo();
            info.isok = true;
            try
            {
                LogQuery? q = JsonConvert.DeserializeObject<LogQuery>(QueryData);

                string? st = q?.Start_Time;
                string? et = q?.End_Time;

                int PageSize = q.PageSize;
                int PageIndex = q.PageIndex;

                List<string> c11 = q.CommandType;

                int AAA = (PageIndex - 1) * PageSize;
                DateTime sst = DateTime.Parse(st);
                DateTime eet = DateTime.Parse(et);
                if (eet < sst)
                {
                    info.isok = false;
                    info.message = "结束时间不能大于开始时间";
                    return info;
                }
                var qqqq = q?.Data;

                int TotalCount = 1000;
                var h11 = qqqq?.Select(x => x.HotelCode).Distinct();
                var r11 = qqqq?.Select(x => x.RoomNumber).Distinct();

                var ddd = dbContext.TclTvMonitorlogs.Where(A => h11.Contains(A.HotelCode) && r11.Contains(A.RoomNumber) && A.RequestTime >= sst && A.RequestTime <= eet)
                    .Skip((PageIndex - 1) * PageSize).Take(PageSize)
                    .ToList();

                var qqa = ddd.OrderBy(x => x.RequestTime).ToList();
                TTT c = new TTT();
                c.TotalCount = TotalCount;
                c.TclTvMonitorlogs = qqa;

                info.response = c;
            }
            catch (Exception ex)
            {
                info.isok = false;
                info.message = ex.Message;
            }
            return info;
        }


        [HttpPost()]
        public ReturnInfo Get_WebAPILog([FromForm] string QueryData)
        {
            ReturnInfo info = new ReturnInfo();
            info.isok = true;
            try
            {
                List<WebapiMonitorlog> lg = new List<WebapiMonitorlog>();
                LogQuery? q = JsonConvert.DeserializeObject<LogQuery>(QueryData);

                string? st = q?.Start_Time;
                string? et = q?.End_Time;

                int PageSize = q.PageSize;
                int PageIndex = q.PageIndex;

                int AAA = (PageIndex - 1) * PageSize;
                DateTime sst = DateTime.Parse(st);
                DateTime eet = DateTime.Parse(et);
                if (eet < sst)
                {
                    info.isok = false;
                    info.message = "结束时间不能大于开始时间";
                    return info;
                }
                var qqqq = q?.Data;

                int TotalCount = 0;
                //using (var a = new LowmachinelogContext())
                //{
                var h11 = qqqq?.Select(x => x.HotelCode).Distinct();
                var r11 = qqqq?.Select(x => x.RoomNumber).Distinct();

                string sss = $"""
                         SELECT * FROM webapi_monitorlog a
                         where a."InvokStart_Time">='{st}' and a."InvokStart_Time" <='{et}' order by a."ID" DESC;
                         """;
                //limit {PageSize} OFFSET {AAA};";

                var ddd = dbContext.WebapiMonitorlogs.FromSqlRaw<WebapiMonitorlog>(sss).ToList();

                lg = ddd;
                //}

                var qqa = lg.OrderBy(x => x.InvokStartTime).ToList();


                var q11 = qqa.GroupBy(A => A.MethodName);
                var q22 = qqa.GroupBy(A => new { Method = A.MethodName, IP = A.RemoteIp });
                var q33 = qqa.GroupBy(A => new { Method = A.MethodName, Code = A.HotelCode });

                List<WebAPIAnalysis_M> ll = new List<WebAPIAnalysis_M>();
                foreach (var item in q11)
                {
                    string methodname = item.Key;
                    int invokeCount = item.Count();

                    WebAPIAnalysis_M d = new WebAPIAnalysis_M();
                    d.MethodName = methodname;
                    d.TotalInvokeCount = invokeCount;
                    ll.Add(d);
                }

                List<WebAPIAnalysis_FinallyData> ggg = new List<WebAPIAnalysis_FinallyData>();
                foreach (var item in ll)
                {
                    string mn = item.MethodName;
                    WebAPIAnalysis_FinallyData iii = new WebAPIAnalysis_FinallyData();
                    iii.MethodName = mn;
                    iii.TotalInvokeCount = item.TotalInvokeCount;
                    var g1 = new List<WebAPIAnalysis_IP>();
                    foreach (var item1 in q22)
                    {
                        if (item1.Key.Method.Equals(item.MethodName))
                        {
                            WebAPIAnalysis_IP g2 = new WebAPIAnalysis_IP();
                            g2.IP = item1.Key.IP;
                            g2.TotalIP_InvokeCount = item1.Count();
                            g1.Add(g2);
                        }
                    }

                    iii.IPInvokeData = g1;

                    var g3 = new List<WebAPIAnalysis_Code>();
                    foreach (var item1 in q33)
                    {
                        if (item1.Key.Method.Equals(item.MethodName))
                        {
                            WebAPIAnalysis_Code g2 = new WebAPIAnalysis_Code();
                            g2.HotelCode = item1.Key.Code;
                            g2.TotalHotelCode_InvokeCount = item1.Count();
                            g3.Add(g2);
                        }
                    }
                    iii.CodeInvokeData = g3;

                    ggg.Add(iii);
                }

                ggg = ggg.OrderByDescending(A => A.TotalInvokeCount).ToList();
                info.response = ggg;
            }
            catch (Exception ex)
            {
                info.isok = false;
                info.message = ex.Message;
            }
            return info;
        }


        [HttpPost()]
        public ReturnInfo Get_WebAPIDetailLog([FromForm] string QueryData)
        {
            ReturnInfo info = new ReturnInfo();
            info.isok = true;
            try
            {
                List<WebapiMonitorlog> lg = new List<WebapiMonitorlog>();
                WebAPILogQuery? q = JsonConvert.DeserializeObject<WebAPILogQuery>(QueryData);

                string? st = q?.Start_Time;
                string? et = q?.End_Time;

                int PageSize = q.PageSize;
                int PageIndex = q.PageIndex;

                int AAA = (PageIndex - 1) * PageSize;
                DateTime sst = DateTime.Parse(st);
                DateTime eet = DateTime.Parse(et);
                if (eet < sst)
                {
                    info.isok = false;
                    info.message = "结束时间不能大于开始时间";
                    return info;
                }
                var qqqq = q?.Data;

                //using (var a = new LowmachinelogContext())
                //{
                var h11 = qqqq?.Select(x => x.HotelCode).Distinct().ToList();
                var r11 = qqqq?.Select(x => x.IP).Distinct().ToList();
                var s11 = qqqq?.Select(x => x.MethodName).Distinct().ToList();

                string sss = $"""
                         SELECT * FROM webapi_monitorlog a
                         where a."InvokStart_Time">='{st}' and a."InvokStart_Time" <='{et}' 
                         """;
                h11.RemoveAll(A => A == null);
                r11.RemoveAll(A => A == null);
                s11.RemoveAll(A => A == null);
                if (h11.Count > 0)
                {
                    string r22 = string.Join(",", h11.Select(name => $"'{name.Replace("'", "''")}'"));
                    string n1 = $"""
                             and a."HotelCode" in ({r22})
                             """;
                    sss += n1;
                }
                if (r11.Count > 0)
                {
                    string s22 = string.Join(",", r11.Select(name => $"'{name.Replace("'", "''")}'"));
                    string n1 = $""" 
                          and a."RemoteIP" in ({s22}) 
                          """;
                    sss += n1;
                }
                if (s11.Count > 0)
                {
                    string h22 = string.Join(",", s11.Select(name => $"'{name.Replace("'", "''")}'"));
                    string n1 = $""" 
                          and a."MethodName" in ({h22})
                          """;
                    sss += n1;
                }

                string mmm = " order by a.\"ID\" DESC;";
                sss += mmm;

                var ddd = dbContext.WebapiMonitorlogs.FromSqlRaw<WebapiMonitorlog>(sss).ToList();

                lg = ddd;
                //}

                info.response = lg;
            }
            catch (Exception ex)
            {
                info.isok = false;
                info.message = ex.Message;
            }
            return info;
        }


        [HttpPost()]
        public ReturnInfo Get_WebAPISliceLog([FromForm] string QueryData)
        {
            ReturnInfo info = new ReturnInfo();
            info.isok = true;
            try
            {
                List<WebAPIAnalysis_EveryHour> lg = new List<WebAPIAnalysis_EveryHour>();
                WebAPILogQuery? q = JsonConvert.DeserializeObject<WebAPILogQuery>(QueryData);

                string? st = q?.Start_Time;
                string? et = q?.End_Time;

                int PageSize = q.PageSize;
                int PageIndex = q.PageIndex;

                int AAA = (PageIndex - 1) * PageSize;
                DateTime sst = DateTime.Parse(st);
                DateTime eet = DateTime.Parse(et);
                if (eet < sst)
                {
                    info.isok = false;
                    info.message = "结束时间不能大于开始时间";
                    return info;
                }
                var qqqq = q?.Data;

                //using (var a = new LowmachinelogContext())
                //{
                var h11 = qqqq?.Select(x => x.HotelCode).Distinct().ToList();
                var r11 = qqqq?.Select(x => x.IP).Distinct().ToList();
                var s11 = qqqq?.Select(x => x.MethodName).Distinct().ToList();

                string sss = $"""
                         SELECT * FROM webapi_monitorlog a
                         where a."InvokStart_Time">='{st}' and a."InvokStart_Time" <='{et}' 
                         """;
                h11.RemoveAll(A => A == null);
                r11.RemoveAll(A => A == null);
                s11.RemoveAll(A => A == null);
                if (h11.Count > 0)
                {
                    string r22 = string.Join(",", h11.Select(name => $"'{name.Replace("'", "''")}'"));
                    string n1 = $"""
                           and a."HotelCode" in ({r22})
                           """;
                    sss += n1;
                }
                if (r11.Count > 0)
                {
                    string s22 = string.Join(",", r11.Select(name => $"'{name.Replace("'", "''")}'"));
                    string n1 = $"""
                           and a."RemoteIP" in ({s22}) 
                           """;
                    sss += n1;
                }
                if (s11.Count > 0)
                {
                    string h22 = string.Join(",", s11.Select(name => $"'{name.Replace("'", "''")}'"));
                    string n1 = $"""
                          and a."MethodName" in ({h22})
                          """;
                    sss += n1;
                }

                string mmm = """
                       order by a."ID" DESC;
                       """;
                sss += mmm;

                var ddd = dbContext.WebapiMonitorlogs.FromSqlRaw<WebapiMonitorlog>(sss).ToList();

                for (DateTime i = sst; i < eet; i = i.AddHours(1))
                {
                    var v1 = ddd.Where(A => DateTime.Parse(A.InvokStartTime) >= i && (DateTime.Parse(A.InvokEndTime) <= i.AddHours(1)));
                    int count = v1.Count();

                    string QuJian = i.ToShortTimeString() + "-" + i.AddHours(1).ToShortTimeString();

                    WebAPIAnalysis_EveryHour a1 = new WebAPIAnalysis_EveryHour();
                    a1.Hour = QuJian;
                    a1.TotalEveryHour_InvokeCount = count;

                    lg.Add(a1);
                }
                //}

                info.response = lg;
            }
            catch (Exception ex)
            {
                info.isok = false;
                info.message = ex.Message;
            }
            return info;
        }


        [HttpPost()]
        public ActionResult GetHotelList()
        {

            ReturnInfo re = new ReturnInfo();
            re.isok = true;
            try
            {
                List<Dictionary<string, object>> LG = GetHotelDataList();
                re.response = LG;
            }
            catch (Exception ex)
            {
                re.isok = false;
                re.message = ex.Message;
            }
            return new JsonResult(re);
        }

        private List<Dictionary<string, object>> GetHotelDataList()
        {
            string Url = ReadConfig.Instance.GetCRICS_URL();
            string Key = "hotellist";
            string ReturnString = "";
            List<Dictionary<string, object>> LG = new List<Dictionary<string, object>>();
            if (!_memoryCache.TryGetValue(Key, out LG))
            {

                var options = new RestClientOptions(Url);
                var client = new RestClient(options);

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("key", "blw_ws@2015");
                string str = JsonConvert.SerializeObject(dic);
                var request = new RestRequest("/api/GetHotelList");
                request.AddParameter("jsonData", str);

                // The cancellation token comes from the caller. You can still make a call without it.
                RestResponse response = client.Get(request);
                string? hotellist = response.Content;

                var hotelINFO = JsonConvert.DeserializeObject<MessageData>(hotellist);


                var result = hotelINFO?.Result;

                List<Dictionary<string, object>> diclist = new List<Dictionary<string, object>>();
                foreach (var hotel in result)
                {
                    Dictionary<string, object> dicaaa = new Dictionary<string, object>();
                    var ID = hotel["ID"];
                    var Code = hotel["Code"];
                    var Name = hotel["Name"];
                    var CreatDate = hotel["CreatDate"];
                    dicaaa.Add("id", ID);
                    dicaaa.Add("code", Code);
                    dicaaa.Add("name", Name);
                    dicaaa.Add("createdate", CreatDate);
                    diclist.Add(dicaaa);
                }

                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    .SetAbsoluteExpiration(TimeSpan.FromMinutes(20));

                _memoryCache.Set(Key, diclist, cacheEntryOptions);
                LG = diclist;
            }

            return LG;
        }

        [HttpPost()]
        public ReturnInfo GetTakePower()
        {
            ReturnInfo info = new ReturnInfo();
            info.isok = true;
            try
            {
                List<Dictionary<string, string>> Ldic = new();
                Monitor_Host_Wrap LG = GetMonitorDataList();
                var LLL = LG.Data;
                foreach (var item in LLL)
                {
                    string hostid = item.HostID;

                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("hostid", hostid);
                    string sss = Send_Http_Request_Params("api/CheckGetTakePower", dic);

                    Dictionary<string, string> ddd = new Dictionary<string, string>();
                    ddd.Add("MAC", item.MAC);
                    ddd.Add("TakeCard_Status", sss);
                    Ldic.Add(ddd);
                }
                info.response = Ldic;
            }
            catch (Exception ex)
            {
                info.message = ex.Message;
            }
            return info;
        }


        /// <summary>
        /// 根据 酒店代表  获取 当前酒店 的主机列表
        /// </summary>
        /// <param name="hotel_code"></param>
        /// <param name="createDate"></param>
        /// <returns></returns>
        [HttpPost()]
        public ReturnInfo GetHostList([FromForm] string hotel_code, [FromForm] string createDate)
        {
            ReturnInfo re = new ReturnInfo();
            re.isok = true;

            try
            {
                string Key = "hostlist_" + hotel_code;
                string ReturnString = "";
                List<Dictionary<string, object>> FinallyResult = new List<Dictionary<string, object>>();
                string Url = ReadConfig.Instance.GetCRICS_URL();
                if (!_memoryCache.TryGetValue(Key, out FinallyResult))
                {

                    var options = new RestClientOptions(Url);
                    var client = new RestClient(options);

                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("code", hotel_code);
                    dic.Add("creatDate", createDate);
                    string str = JsonConvert.SerializeObject(dic);
                    //var request = new RestRequest("/api/GetHostList");
                    var request = new RestRequest("/api/GetHostListWithGroupId");
                    request.AddParameter("jsonData", str);

                    //RoomNumber
                    // The cancellation token comes from the caller. You can still make a call without it.
                    string? hostlist = client.Get(request).Content;



                    var hostINFO = JsonConvert.DeserializeObject<MessageData>(hostlist);


                    var result = hostINFO.Result;

                    List<Dictionary<string, object>> diclist = new List<Dictionary<string, object>>();
                    foreach (var hotel in result)
                    {
                        Dictionary<string, object> dicaaa = new Dictionary<string, object>();
                        var ID = hotel["ID"];
                        var RoomNumber = hotel["RoomNumber"];
                        var GroupId = hotel["GroupId"];
                        //var HostID = hotel["HotelID"];
                        var MAC = hotel["MAC"];
                        var HostNumber = hotel["HostNumber"];
                        var Status = hotel["Status"];
                        var SOS_Status = hotel["SOS_Status"];
                        var RoomTypeID = hotel["RoomTypeID"];
                        var RoomTypeName = hotel["RoomTypeName"];
                        var jixing = hotel["MachineType"];
                        var config_v = hotel["ConfigurationVersion"];
                        var current_v = hotel["Version"];
                        var LauncherVersion = hotel["LauncherVersion"];


                        dicaaa.Add("id", ID);
                        dicaaa.Add("groupid",GroupId);
                        dicaaa.Add("roomno", RoomNumber);
                        dicaaa.Add("hostnumber", HostNumber);
                        dicaaa.Add("mac", MAC);
                        dicaaa.Add("status", Status);
                        dicaaa.Add("sos_status", SOS_Status);
                        dicaaa.Add("roomtypeid", RoomTypeID);
                        dicaaa.Add("roomtypename", RoomTypeName);

                        dicaaa.Add("MachineType", jixing);
                        dicaaa.Add("ConfigurationVersion", config_v);
                        dicaaa.Add("Version", current_v);
                        dicaaa.Add("LauncherVersion", LauncherVersion);
                        diclist.Add(dicaaa);
                    }

                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                        .SetAbsoluteExpiration(TimeSpan.FromMinutes(5));

                    _memoryCache.Set(Key, diclist, cacheEntryOptions);
                    FinallyResult = diclist;
                }
                re.response = FinallyResult;
            }
            catch (Exception ex)
            {
                re.isok = false;
                re.message = ex.Message;
            }
            return re;
        }


        [HttpPost()]
        public ReturnInfo GetHotelIdByCode([FromForm] string hotel_code)
        {
            ReturnInfo re = new ReturnInfo();
            re.isok = true;
            try
            {
                string Key = "GetHotelIdByCode_" + hotel_code;
                string ReturnString = "";
                List<Dictionary<string, object>> FinallyResult = new List<Dictionary<string, object>>();
                string Url = ReadConfig.Instance.GetCRICS_URL();
                if (!_memoryCache.TryGetValue(Key, out FinallyResult))
                {
                    var options = new RestClientOptions(Url);
                    var client = new RestClient(options);

                    var request = new RestRequest("/api/GetHotelIdByCode");
                    request.AddParameter("code", hotel_code);
                    request.AddParameter("key", "i_love_blw^_^");

                    string? hostlist = client.Post(request).Content;

                    _memoryCache.Set(Key, hostlist);
                    //var hostINFO = JsonConvert.DeserializeObject<Dictionary<string, string>>(hostlist);
                    //string id = hostINFO["id"];
                    //DateTime dt = DateTime.Parse(hostINFO["createdDate"]);
                    //string sss= dt.ToString("yyyy-MM-dd");

                    re.isok = true;
                    re.response = hostlist;
                }
                else
                {
                    re.isok = true;
                    re.response = ReturnString;
                }
            }
            catch (Exception ex)
            {
                re.isok = false;
                re.response = ex.Message;
            }
            return re;
        }


        //data=[{"HotelCode":"","RoomNumber":""}]&add_remove=add
        [HttpPost()]
        public async Task<ReturnInfo> Monitor_Host_Handle([FromForm] string data, [FromForm] string add_remove)
        {
            ReturnInfo re = new ReturnInfo();
            re.isok = true;

            try
            {

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("data", data);
                dic.Add("add_remove", add_remove);
                string str = Send_Http_Request_Params("api/Monitor_Host_Handle", dic);
                re.response = str;

                var q = JsonConvert.DeserializeObject<List<Monitor_Host>>(data);

                string debug_log_report_url = ReadConfig.Instance.MQTTAgentUrl;
                string debug_log_report_mqtt_topic = "blw/logmonitor/delete/report";

                var client1 = new RestClient(debug_log_report_url);
                var request1 = new RestRequest("/", Method.Post);


                if (add_remove.Equals("remove"))
                {
                    //using var q1 = new LowmachinelogContext();
                    foreach (var item in q)
                    {
                        var hhh = dbContext.StatisticsTotals.Where(A => A.Mac.Equals(item.MAC)).ToList();
                        if (hhh != null)
                        {
                            dbContext.StatisticsTotals.RemoveRange(hhh);
                            await dbContext.SaveChangesAsync();
                        }

                        //注意方法是POST
                        //两个参数名字必须是 topic 和payload ，区分大小写的
                        string str111 = JsonConvert.SerializeObject(item);
                        request1.AddParameter("topic", debug_log_report_mqtt_topic);
                        request1.AddParameter("payload", str111);
                        await client1.ExecuteAsync(request1);
                    }
                }

                //using (var db = new LiteDatabase(@"MyData.db"))
                //{
                //    var col = db.GetCollection<LiteDB_Monitor_Host>("LiteDB_Monitor_Host");

                //    foreach (var item in q)
                //    {
                //        //string KKK = DataPush.TongJiKey + item.MAC;
                //        //_memoryCache.Remove(KKK);
                //        BsonValue v = new BsonValue();
                //        var qqq = Query.EQ("MAC", item.MAC);
                //        col.DeleteMany(qqq);

                //        string str111 = JsonConvert.SerializeObject(item);
                //        //注意方法是POST
                //        //两个参数名字必须是 topic 和payload ，区分大小写的
                //        request1.AddParameter("topic", debug_log_report_mqtt_topic);
                //        request1.AddParameter("payload", str111);
                //        client1.ExecuteAsync(request1);
                //    }
                //}


                //foreach (var item in q)
                //{
                //    string KKK = DataPush.TongJiKey + item.MAC;
                //    _memoryCache.Remove(KKK);
                //}

                //using (var abc = new LowmachinelogContext())
                //{

                //    if (add_remove.Equals("add"))
                //    {

                //        //abc.StatisticsTotals.Add();
                //    }
                //    else if (add_remove.Equals("remove"))
                //    {

                //        //abc.StatisticsTotals.Where();
                //        abc.StatisticsTotals.RemoveRange();
                //    }
                //}

            }
            catch (Exception ex)
            {
                re.isok = false;
                re.message = ex.Message;
            }
            return re;

        }


        [HttpPost()]
        public ReturnInfo GetAll_MonitorHost()
        {
            ReturnInfo i = new ReturnInfo();
            i.isok = true;
            try
            {
                Monitor_Host_Wrap c = GetMonitorDataList();
                i.response = c;
            }
            catch (Exception ex)
            {
                i.isok = false;
                i.message = ex.Message;
            }
            return i;

        }

        //返回的是Monitor_Host 列表
        [HttpPost()]
        public ReturnInfo GetSpe_MonitorHost(Dictionary<string, string> data)
        {
            ReturnInfo i = new ReturnInfo();
            i.isok = true;
            try
            {
                string hotelcode = data["hotelcode"].ToString();
                Monitor_Host_Wrap c = GetMonitorDataList();
                if (!string.IsNullOrEmpty(hotelcode))
                {
                    c.Data = c.Data.Where(A => A.HotelCode.Equals(hotelcode)).ToList();
                }
                i.response = c;
            }
            catch (Exception ex)
            {
                i.isok = false;
                i.message = ex.Message;
            }
            return i;

        }




        public async Task<ReturnInfo> Monitor_IOT_Handle([FromForm] string data, [FromForm] string add_remove)
        {
            ReturnInfo re = new ReturnInfo();
            re.isok = true;

            try
            {

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("data", data);
                dic.Add("add_remove", add_remove);
                string str = Send_Http_Request_Params("api/IOT_Monitor_Host_Handle", dic);
                re.response = str;
            }
            catch (Exception ex)
            {
                re.isok = false;
                re.message = ex.Message;
            }
            return re;

        }



        //返回的是Monitor_Host 列表
        [HttpPost()]
        public ReturnInfo GetAll_MonitorIOT()
        {
            ReturnInfo i = new ReturnInfo();
            i.isok = true;
            try
            {
                List<IOT_Monitor_Host> c = IOT_GetAll_MonitorHost();
                i.response = c;
            }
            catch (Exception ex)
            {
                i.isok = false;
                i.message = ex.Message;
            }
            return i;

        }

        public List<IOT_Monitor_Host> IOT_GetAll_MonitorHost()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            string str = Send_Http_Request_Params("api/IOT_GetAll_MonitorHost", dic);
            var bnm = JsonConvert.DeserializeObject<List<IOT_Monitor_Host>>(str);


            return bnm;
        }


        /// <summary>
        /// 获取监控列表
        /// </summary>
        /// <returns></returns>
        public Monitor_Host_Wrap GetMonitorDataList()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            string str = Send_Http_Request_Params("api/GetAll_MonitorHost", dic);
            var bnm = JsonConvert.DeserializeObject<List<Monitor_Host>>(str);

            ConcurrentBag<Monitor_Host_EX> ll = new ConcurrentBag<Monitor_Host_EX>();
            Monitor_Host_Wrap c = new Monitor_Host_Wrap();




            Parallel.ForEach(bnm, (item) =>
            {
                //using var a = new LowmachinelogContext();
                Monitor_Host_EX ex = new Monitor_Host_EX();
                ex.HotelCode = item.HotelCode;
                ex.HostID = item.HostID;
                ex.Key_HostNumber = item.Key_HostNumber;
                ex.RoomNumber = item.RoomNumber;
                ex.MAC = item.MAC;
                ex.CreateDateTime = item.CreateDateTime;

                ll.Add(ex);
            });


            c.Data = ll.OrderBy(A => A.CreateDateTime).OrderBy(A => A.HotelCode).OrderBy(A => A.RoomNumber).ToList();
            c.CommandList = TypeList.Instance.list;

            _memoryCache.Set(JianKongLieBiao, c.Data);
            return c;
        }

        public static string JianKongLieBiao = "jiankongliebiao";

        [HttpPost()]
        public ReturnInfo BingTu([FromForm] string QueryData)
        {

            ReturnInfo info = new ReturnInfo();
            try
            {

                List<DevMonitorlog> lg = new List<DevMonitorlog>();
                LogQuery? q = JsonConvert.DeserializeObject<LogQuery>(QueryData);
                string? st = q?.Start_Time;
                string? et = q?.End_Time;

                int PageSize = q.PageSize;
                int PageIndex = q.PageIndex;

                List<string> c11 = q.CommandType;

                int AAA = (PageIndex - 1) * PageSize;
                DateTime sst = DateTime.Parse(st);
                DateTime eet = DateTime.Parse(et);
                if (eet < sst)
                {
                    info.isok = false;
                    info.message = "结束时间不能大于开始时间";
                    return info;
                }
                var qqqq = q?.Data;


                var h11 = qqqq.Select(x => x.HotelCode);
                var r11 = qqqq.Select(x => x.RoomNumber);
                var m11 = qqqq.Select(x => x.MAC);


                string h22 = string.Join(",", h11.Select(name => $"'{name.Replace("'", "''")}'"));
                string r22 = string.Join(",", r11.Select(name => $"'{name.Replace("'", "''")}'"));
                string m22 = string.Join(",", m11.Select(name => $"'{name.Replace("'", "''")}'"));
                string c22 = string.Join(",", c11.Select(name => $"'{name.Replace("'", "''")}'"));

                //using var a = new LowmachinelogContext();


                string sss111 = $@"select count(CommandType) Count,CommandType,SendOrReceive from dev_monitorlog
                                 where HotelCode in ({h22}) and RoomNo in ({r22}) and MAC in ({m22}) and CommandType in ({c22})
                                 GROUP BY CommandType,SendOrReceive;";

                var qqq = dbContext.Database.SqlQueryRaw<JieGuo>(sss111);
                var list = qqq.ToList<JieGuo>();

                var RX = list.Where(x => x.SendOrReceive.Equals(ConstKey.Receive_RX));
                var TX = list.Where(x => x.SendOrReceive.Equals(ConstKey.Send_TX));

                TuBiao t = new TuBiao();
                List<TRX> rx = RX.Select(A =>
                {
                    TRX ttt = new TRX();
                    ttt.name = A.CommandType;
                    ttt.value = A.Count;
                    return ttt;
                }).ToList<TRX>();

                List<TRX> tx = TX.Select(A =>
                {
                    TRX ttt = new TRX();
                    ttt.name = A.CommandType;
                    ttt.value = A.Count;
                    return ttt;
                }).ToList<TRX>();

                t.RX = rx;
                t.TX = tx;


                string stra = $@"select CreateTime,CommandType,SendOrReceive from dev_monitorlog
                                 where HotelCode in ({h22}) and RoomNo in ({r22}) and MAC in ({m22}) and CommandType in ({c22})
                                 and CreateTime BETWEEN '{st}' and  '{et}';";
                var q1 = dbContext.Database.SqlQueryRaw<_JieGuo>(stra);
                var list1 = q1.ToList<_JieGuo>();


                List<List<JieGuo>> qu = new List<List<JieGuo>>();

                for (DateTime i = sst.AddHours(1); i <= eet.AddHours(1); i = i.AddHours(1))
                {

                    Console.WriteLine(i.ToString());
                    var list2 = list1.Where(A =>
                    {
                        DateTime dtc = DateTime.Parse(A.CreateTime);
                        if (dtc <= i && dtc >= i.AddHours(-1))
                        {
                            return true;
                        }
                        return false;
                    }).ToList();

                    List<JieGuo> list3 = new List<JieGuo>();
                    if (list2.Count > 0)
                    {

                        var g1 = list2.GroupBy(A => new { CommandType = A.CommandType, SendOrReceive = A.SendOrReceive });
                        foreach (var item in g1)
                        {
                            JieGuo jjj = new JieGuo();
                            jjj.Count = item.Count();
                            jjj.CommandType = item.Key.CommandType;
                            jjj.SendOrReceive = item.Key.SendOrReceive;
                            list3.Add(jjj);
                        }
                    }
                    else
                    {
                        JieGuo j1 = new JieGuo() { Count = 0, SendOrReceive = ConstKey.Send_TX };
                        JieGuo j2 = new JieGuo() { Count = 0, SendOrReceive = ConstKey.Receive_RX };
                        list3.Add(j1);
                        list3.Add(j2);
                    }
                    qu.Add(list3);
                }


                List<int> RX_list = new List<int>();
                List<int> TX_list = new List<int>();
                List<int> Total_list = new List<int>();
                foreach (var item in qu)
                {
                    var v1 = item.Where(AAA => AAA.SendOrReceive.Equals(ConstKey.Receive_RX));
                    var c1 = v1.Sum(FFF => FFF.Count);
                    RX_list.Add(c1);

                    var v2 = item.Where(AAA => AAA.SendOrReceive.Equals(ConstKey.Send_TX));
                    var c2 = v2.Sum(FFF => FFF.Count);
                    TX_list.Add(c2);

                    Total_list.Add(c1 + c2);
                }

                //list_LLA.Add(RX_list);
                //list_LLA.Add(RX_list);
                //list_LLA.Add(RX_list);



                t.TX_EVERY_Hour = TX_list;
                t.RX_EVERY_Hour = RX_list;
                t.RTX_EVERY_Hour = Total_list;


                info.isok = true;
                info.response = t;
            }
            catch (Exception ex)
            {
                info.isok = false;
                info.message = ex.Message;
                throw;
            }
            return info;
        }

        public static string Send_Http_Request_Params(string Url, Dictionary<string, string> Params)
        {
            string BaseUrl = ReadConfig.Instance.GetCRICS_URL();
            var options = new RestClientOptions(BaseUrl);
            var client = new RestClient(options);

            var request = new RestRequest(Url);

            foreach (var item in Params)
            {
                request.AddParameter(item.Key, item.Value);
            }
            //RoomNumber
            // The cancellation token comes from the caller. You can still make a call without it.
            string? hostlist = client.Post(request).Content;
            return hostlist;
        }

        [HttpPost()]
        public void TestLog()
        {
            _logger.Info("aaaaaaaaaaaaaaaa");
        }
        [HttpGet()]
        public ReturnInfo GetAll_WebApiMethod()
        {
            ReturnInfo i = new ReturnInfo();
            i.isok = true;
            try
            {
                var result = StaticData.scope.GetVariable("methodlists");
                i.response = result;
            }
            catch (Exception ex)
            {
                i.isok = false;
                i.message = ex.Message;
            }
            return i;
        }

    }
    public class MessageData
    {
        public string? IsSuccess { get; set; }
        public List<Dictionary<string, object>> Result { get; set; }
    }
    public class LogQuery
    {
        public List<QueryData> Data { get; set; }
        public string Start_Time { get; set; }
        public string End_Time { get; set; }
        public int PageSize { get; set; }
        public int PageIndex { get; set; }
        public List<string> CommandType { get; set; }
    }
    public class LogQueryAnnlysis
    {
        public List<QueryData> Data { get; set; }
        public string Start_Time { get; set; }
        public string End_Time { get; set; }
    }

    public class WebAPILogQuery
    {
        public List<QueryWebAPIData> Data { get; set; }
        public string Start_Time { get; set; }
        public string End_Time { get; set; }
        public int PageSize { get; set; }
        public int PageIndex { get; set; }
    }

    public class QueryData
    {
        public string HotelCode { get; set; }
        public string Key_HostNumber { get; set; }

        public string RoomNumber { get; set; }
        public string MAC { get; set; }

    }
    public class QueryWebAPIData
    {
        public string HotelCode { get; set; }
        public string IP { get; set; }
        public string MethodName { get; set; }
    }

    public class WebAPIAnalysis_M
    {
        public string MethodName { get; set; }
        public int TotalInvokeCount { get; set; }
    }
    public class WebAPIAnalysis_IP
    {

        public string IP { get; set; }
        public int TotalIP_InvokeCount { get; set; }
    }
    public class WebAPIAnalysis_Code
    {
        public string HotelCode { get; set; }
        public int TotalHotelCode_InvokeCount { get; set; }
    }

    public class WebAPIAnalysis_EveryHour
    {
        public string Hour { get; set; }
        public int TotalEveryHour_InvokeCount { get; set; }
    }

    public class WebAPIAnalysis_FinallyData
    {
        public string MethodName { get; set; }
        public int TotalInvokeCount { get; set; }

        public List<WebAPIAnalysis_IP> IPInvokeData { get; set; }
        public List<WebAPIAnalysis_Code> CodeInvokeData { get; set; }
        //public List<WebAPIAnalysis_EveryHour> EveryHourData { get; set; }
    }

}
