using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GalaSoft.MvvmLight;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Models;
using SlnMesnac.Config;
using SlnMesnac.Repository;
using SlnMesnac.Rfid;
using SlnMesnac.TouchSocket;
using SlnMesnac.WPF.Attribute;
using SlnMesnac.WPF.Model;
using SlnMesnac.WPF.Page.IndexPage;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using Task = System.Threading.Tasks.Task;

namespace SlnMesnac.WPF.ViewModel.IndexPage
{
    [RegisterAsSingletonAttribute]
    public partial class MiddleWareViewModel : ViewModelBase
    {
        private ILogger<MiddleWareViewModel> _logger;

        private ISqlSugarClient? sqlSugarClient;
        //容器里面的读写器集合
        public List<RfidAbsractFactory> rfidList;
        private AppConfig appConfig;
        private ApiServer apiServer;
        private MeshttpClient meshttpClient;
        public MiddleWareViewModel()
        {
            appConfig = App.ServiceProvider.GetService<AppConfig>();
            sqlSugarClient = App.ServiceProvider.GetService<ISqlSugarClient>();
            rfidList = App.ServiceProvider.GetRequiredService<List<RfidAbsractFactory>>();
            apiServer = App.ServiceProvider.GetService<ApiServer>();
            meshttpClient = App.ServiceProvider.GetService<MeshttpClient>();
            MiddleWare.RefreshStateEvent += RefreshEventArgs;
            MeshttpClient.RefreshStateEvent += RefreshEventArgs;
            MeshttpClient._RefreshLogMessageAction += RefreshLogMessage;
            ApiServer.RefreshStateEvent += RefreshEventArgs;
            ApiServer._RefreshLogMessageAction += RefreshLogMessage;
            RefreshLogMessage("初始化");
            LoadDeviceInfo();
            LoadSenorInfo();
            StartCheckStatus();
        }
        /// <summary>
        /// 日志信息
        /// </summary>
        private ObservableCollection<string> _logMessages = new ObservableCollection<string>();

        public ObservableCollection<string> LogMessages
        {
            get { return _logMessages; }
            set
            {
                _logMessages = value;
                RaisePropertyChanged(() => LogMessages);
            }
        }
        /// <summary>
        /// 刷新日志
        /// </summary>
        /// <param name="msg"></param>
        public void RefreshLogMessage(string msg)
        {
            try
            {
                App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    LogMessages.Add($"{DateTime.Now}: {msg}");
                    while (LogMessages.Count > 10)
                    {
                        LogMessages.RemoveAt(0);
                    }
                    var orderedList = LogMessages.OrderByDescending(x => x);  // 排序后转为 List
                    LogMessages = new ObservableCollection<string>(orderedList);
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");

            }

        }
        public void RefreshEventArgs(string combineID, string rfid)
        {

            Senorinfo.FirstOrDefault(x => x.Combineid == combineID).Readtime = DateTime.Now.ToString("yy-MM-dd HH:mm:ss");
            if (string.IsNullOrEmpty(rfid))
            {
                rfid = "Nodata";
            }
            Senorinfo.FirstOrDefault(x => x.Combineid == combineID).Readdata = rfid;

        }
        private ObservableCollection<RfidInfo> _Deviceinfo = new ObservableCollection<RfidInfo>();
        public ObservableCollection<RfidInfo> Deviceinfo
        {
            get { return _Deviceinfo; }
            set
            {
                _Deviceinfo = value;
                RaisePropertyChanged(() => Deviceinfo);
            }
        }
        private ObservableCollection<SenorInfo> _Senorinfo = new ObservableCollection<SenorInfo>();
        public ObservableCollection<SenorInfo> Senorinfo
        {
            get { return _Senorinfo; }
            set
            {
                _Senorinfo = value;
                RaisePropertyChanged(() => Senorinfo);
            }
        }


        private void LoadDeviceInfo()
        {
            List<Base_device_info> DeviceInfos = sqlSugarClient.Queryable<Base_device_info>().Where(expression: x =>x.Collectid == appConfig.StationCode).ToList();
            App.Current.Dispatcher.Invoke(() =>
            {
                Deviceinfo.Clear();
                foreach (var item in DeviceInfos)
                {
                    RfidInfo rfid = new RfidInfo()
                    {
                        Name = item.Name,
                        Deviceid = item.Deviceid,
                        Collectid = item.Collectid,
                        Connectmode = item.Connectmode,
                        Connectstr = item.Connectstr,
                        Devicetype = item.Devicetype,
                    };
                    Deviceinfo.Add(rfid);
                }
            });
        }
        private void LoadSenorInfo()
        {
            List<Base_sensor_info> SenorInfos = sqlSugarClient.Queryable<Base_sensor_info>().ToList();
            Senorinfo.Clear();
            foreach (var item in Deviceinfo)
            {
                Base_sensor_info base_Sensor_Info = SenorInfos.Find(x => x.Deviceid == item.Deviceid);
                App.Current.Dispatcher.Invoke(() =>
                {
                    SenorInfo senorInfo = new SenorInfo()
                    {
                        Combineid = base_Sensor_Info.Combineid,
                        Name = base_Sensor_Info.Name,
                        Sensorid = base_Sensor_Info.Sensorid,
                        Sensortypeid = base_Sensor_Info.Sensortypeid,
                        Deviceid =base_Sensor_Info.Deviceid,
                        Readinterval = base_Sensor_Info.Readinterval,

                    };
                    Senorinfo.Add(senorInfo);
                });
            }
           
        }

        private List<List<RfidAbsractFactory>> SplitListIntoBatches(List<RfidAbsractFactory> sourceList, int batchSize)
        {
            var batches = new List<List<RfidAbsractFactory>>();
            for (int i = 0; i < sourceList.Count; i += batchSize)
            {
                // 截取每批的设备（最后一批可能不足10个）
                var batch = sourceList.Skip(i).Take(batchSize).ToList();
                batches.Add(batch);
            }
            return batches;
        }

        private async Task DetectDeviceBatchAsync(List<RfidAbsractFactory> batch)
        {
            // 并行检测当前批次的设备（可选，根据接口性能调整）
            var detectionTasks = batch.Select(device => DetectSingleDeviceAsync(device));
            // 等待当前批次所有设备检测完成
            await Task.WhenAll(detectionTasks);
        }
        private async Task DetectSingleDeviceAsync(RfidAbsractFactory device)
        {
            try
            {
                //device.Close();
                bool status = device.GetOnlineStatus();
                if (!status)
                {
                    status = await device.ConnectAsync(device.ip, device.port,device.ConfigKey);
                    if (!status)
                    {
                        Deviceinfo.FirstOrDefault(x => x.Connectstr == $"{device.ip}:{device.port}").IsOnline = "未连接";
                    }
                    else
                    {
                        Deviceinfo.FirstOrDefault(x => x.Connectstr == $"{device.ip}:{device.port}").IsOnline = "已连接";
                    }
                }
                else
                {
                    //更新界面状态
                    Deviceinfo.FirstOrDefault(x => x.Connectstr == $"{device.ip}:{device.port}").IsOnline = "已连接";
                }



            }
            catch (Exception ex)
            {
               
            }
        }
        private void StartCheckStatus()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    try
                    {
                        #region RFID状态
                        //RefreshLogMessage("检测设备状态");
                        var batches = SplitListIntoBatches(rfidList, 10);
                        for (int i = 0; i < batches.Count; i++)
                        {
                            var currentBatch = batches[i];
                            // 显示当前批次信息（UI线程）
                           //Console.WriteLine($"开始检测第{i + 1}批（共{currentBatch.Count}个设备）\r\n");

                            // 异步检测当前批次的设备状态（不阻塞UI）
                            await DetectDeviceBatchAsync(currentBatch);

                            // 批次之间的间隔（最后一批无需等待）
                            if (i < batches.Count - 1)
                            {
                                //Console.WriteLine( $"第{i + 1}批检测完成，共{batches.Count}批，等待{1000 / 1000}秒后检测下一批\r\n");
                                await Task.Delay(10);
                            }
                        }
                        //foreach (var rfid in rfidList)
                        //{
                        //    if (rfid.ConfigKey == "C031040701")
                        //    {
                        //    }
                        //    bool status = rfid.GetOnlineStatus();
                        //    if (!status)
                        //    {
                        //        status = await rfid.ConnectAsync(rfid.ip, rfid.port);
                        //        if (!status)
                        //        {
                        //            Deviceinfo.FirstOrDefault(x => x.Connectstr == $"{rfid.ip}:{rfid.port}").IsOnline = "未连接";
                        //        }
                        //        else
                        //        {
                        //            Deviceinfo.FirstOrDefault(x => x.Connectstr == $"{rfid.ip}:{rfid.port}").IsOnline = "已连接";
                        //        }
                        //    }
                        //    else
                        //    {
                        //        //更新界面状态
                        //        Deviceinfo.FirstOrDefault(x => x.Connectstr == $"{rfid.ip}:{rfid.port}").IsOnline = "已连接";
                        //    }
                        //}
                      
                        #endregion RFID状态
                    }
                    catch (Exception ex)
                    {
                        //_logger.Error($"监听设备状态异常:{ex.Message}");
                    }
                    await Task.Delay(1000 * 30);
                }
            });
        }

    }
}
