using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using SlnMesnac.Business.@base;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;
using SlnMesnac.Repository.service;
using SlnMesnac.Repository;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Task = System.Threading.Tasks.Task;
using SlnMesnac.WPF.Page.IndexPage;
using System.Windows.Documents;
using SlnMesnac.TouchSocket;
using HslCommunication.Enthernet;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：T14-GEN3-7895
* 命名空间：SlnMesnac.WPF.ViewModel.IndexPage
* 唯一标识：ffdc8ddd-928f-4910-b6ac-d6d6426c39d0
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2024-09-05 15:05:57
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.WPF.ViewModel.IndexPage
{
    public partial class IndexContentViewModel: ObservableObject
    {
        private ILogger<IndexContentViewModel> _logger;
        private ILogger<BaseTaskInfoBusiness> _taskBusinessLogger;
        private IAirportTaskService _taskservice;
        private IAGVStateService _agvstateService;
        private BaseTaskInfoBusiness _taskInfoBusiness;
        private DispatcherTimer _timer;
        private TcpServer _tcpServer;

        public IndexContentViewModel()
        {

            LogMessages = new ObservableCollection<string>();
            _taskBusinessLogger = App.ServiceProvider.GetService<ILogger<BaseTaskInfoBusiness>>();
            _taskservice = App.ServiceProvider.GetService<IAirportTaskService>();
            _agvstateService = App.ServiceProvider.GetService<IAGVStateService>();
            _tcpServer = App.ServiceProvider.GetService<TcpServer>();

            _taskInfoBusiness = BaseTaskInfoBusiness.GetInstance(_taskBusinessLogger, _taskservice, _agvstateService, _tcpServer);
            _taskInfoBusiness._RefreshLogMessageAction += RefreshLogMessage;
            _taskInfoBusiness._Taskaction += task =>
            {
                if (task != null)
                {
                    var x = TaskItems.ToList().Find(x => x.conveyorno == task.conveyorno);
                    if (x != null)
                    {
                        x.id = task.id;
                        x.taskno = task.taskno;
                        x.flightno = task.flightno;
                        x.manipulatorno = task.manipulatorno;
                        x.agvno = task.agvno;
                        x.taskstate = task.taskstate;
                        TaskItems = new ObservableCollection<AirportTask>(TaskItems);
                        
                    }
                }
            };
            this.Init();
        }

        private void LoadTaskInfo()
        {
            try
            {
                List<AirportTask> AirportTaskItem = _taskservice.GetTaskInfos();
                TaskItems = new ObservableCollection<AirportTask>(AirportTaskItem);
            }
            catch (Exception ex)
            {

            }
        }

        private void Init()
        {
            #region 测试数据

            LoadTaskInfo();

            // TaskItems = new ObservableCollection<AirportTask>
            // {
            //     new AirportTask { TaskCode = "1", StationName = "1#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "2", StationName = "2#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "3", StationName = "3#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "4", StationName = "4#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "5", StationName = "5#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "6", StationName = "6#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            // };

            //RefreshLogMessage($"1#站台任务下发站台任务下发站台任务下发站台任务下发站台任务下发站台任务下发");
            //RefreshLogMessage($"2#站台任务下发");
            //RefreshLogMessage($"3#站台任务下发");
            //RefreshLogMessage($"4#站台任务下发");
            //RefreshLogMessage($"5#站台任务下发");
            //RefreshLogMessage($"6#站台任务下发");
            //RefreshLogMessage($"7#站台任务下发");
            //RefreshLogMessage($"2#站台任务下发");
            //RefreshLogMessage($"3#站台任务下发");
            //RefreshLogMessage($"4#站台任务下发");
            //RefreshLogMessage($"5#站台任务下发");
            //RefreshLogMessage($"6#站台任务下发");
            //RefreshLogMessage($"7#站台任务下发");

            FlightItems = new ObservableCollection<FlightItem>
            {
                new FlightItem { flightNumber = "航班号：CZ3021", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
                new FlightItem { flightNumber = "航班号：CZ3022", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
                new FlightItem { flightNumber = "航班号：CZ3023", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
                new FlightItem { flightNumber = "航班号：CZ3024", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
                new FlightItem { flightNumber = "航班号：CZ3025", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
                new FlightItem { flightNumber = "航班号：CZ3026", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
                new FlightItem { flightNumber = "航班号：CZ3027", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
            };
            #endregion

            #region 更新时间显示
            _currentDateTime = DateTime.Now;
            _timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1) // 每秒更新一次
            };
            _timer.Tick += (s, e) =>
            {
                CurrentDateTime = DateTime.Now;
            };
            _timer.Start();
            #endregion

            
        }

        public async void RefreshTaskItems(AirportTask airportTask)
        {
            try
            {
                await Task.Run(async () =>
                {
                    foreach (var VARIABLE in TaskItems)
                    {
                        if (VARIABLE.agvno == airportTask.conveyorno)
                        {
                            VARIABLE.taskstate = airportTask.taskstate;
                            VARIABLE.agvno = airportTask.agvno;
                            VARIABLE.totalcount = airportTask.totalcount;
                            VARIABLE.loadcount = airportTask.loadcount;
                        }
                    }
                });
            }
            catch (Exception ex)
            {

            }
        }
        #region 参数定义
        /// <summary>
        /// 任务列表
        /// </summary>
        private ObservableCollection<AirportTask> _taskItems = new ObservableCollection<AirportTask>();
        public ObservableCollection<AirportTask> TaskItems
        {
            get => _taskItems;
            set => SetProperty(ref _taskItems, value);
        }
        /// <summary>
        /// 日志信息
        /// </summary>
        private ObservableCollection<string> _logMessages = new ObservableCollection<string>();

        public ObservableCollection<string> LogMessages
        {
            get => _logMessages;
            set => SetProperty(ref _logMessages, value);
        }
        /// <summary>
        /// 日期时间
        /// </summary>
        private DateTime _currentDateTime;
        public DateTime CurrentDateTime
        {
            get => _currentDateTime;
            set
            {
                if (_currentDateTime != value)
                {
                    SetProperty(ref _currentDateTime, value);
                }
            }
        }
        /// <summary>
        /// 航班信息
        /// </summary>
        private ObservableCollection<FlightItem> _flightItems = new ObservableCollection<FlightItem>();
        public ObservableCollection<FlightItem> FlightItems
        {
            get => _flightItems;
            set => SetProperty(ref _flightItems, value);
        }
        #endregion

        /// <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 > 120)
                    {
                        LogMessages.RemoveAt(0);
                    }
                    var orderedList = LogMessages.OrderByDescending(x => x);  // 排序后转为 List
                    LogMessages = new ObservableCollection<string>(orderedList);
                }));
            }
            catch (Exception ex)
            {

            }
            
        }
        /// <summary>
        /// 系统运行日志输出
        /// </summary>
        /// <param name="message"></param>
        private async void PrintMessageToListBox(string message)
        {
            await Task.Run(() =>
            {
                try
                {
                    string formattedMessage = $"{DateTime.Now.ToString("HH:mm:ss.ss")} ==> {message}";

                    lock (LogMessages)
                    {
                        LogMessages.Add(formattedMessage);

                        while (LogMessages.Count > 120)
                        {
                            LogMessages.RemoveAt(0);
                        }

                        var orderedList = LogMessages.OrderByDescending(x => x).ToList();  // 排序后转为 List

                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"日志数据绑定异常:{ex.Message}");
                }
            });
        }
        /// <summary>
        /// 添加任务
        /// </summary>
        [RelayCommand]
        private void AddTask()
        {
            //生成任务号
            //输入航班号
            //任务状态默认等待
            AddTaskContent AddTaskContent = new AddTaskContent();
            AddTaskContent._Taskaction = task =>
            {
                if (task != null)
                {
                    var x = TaskItems.ToList().Find(x => x.conveyorno == task.conveyorno);
                    if (x != null)
                    {
                        x.id = task.id;
                        x.taskno = task.taskno;
                        x.flightno = task.flightno;
                        x.manipulatorno = task.manipulatorno;
                        x.agvno = task.agvno;
                        x.taskstate = task.taskstate;
                        TaskItems = new ObservableCollection<AirportTask>(TaskItems);
                    }
                    else
                    {
                        TaskItems.Add(task);
                    }
                }
            };
            AddTaskContent.ShowDialog();
            if ((bool)AddTaskContent.DialogResult)
            {
                RefreshLogMessage("任务添加成功!");
            }

                
        }

        /// <summary>
        /// 处理任务
        /// </summary>
        /// <param name="taskCode"></param>
        [RelayCommand]
        private void HandleTask(AirportTask taskCode)
        {
            var info = taskCode;
            if (info != null)
            {

                DetailTaskContent DetailTaskContent = new DetailTaskContent();
                DetailTaskContent.AirportTask = taskCode;
                DetailTaskContent.ShowDialog();
            }
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="taskCode"></param>
        [RelayCommand]
        private void DeleteTask(AirportTask task)
        {
            if (task.taskstate != "等待")
            {
                MessageBox.Show("任务已下发,不允许删除!");
            }
            else
            {
                if (MessageBox.Show("请确认是否删除该任务?", "Confirm Message", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    //根据任务号删除任务
                    TaskItems.Remove(task);
                    //清表
                    _taskservice.DeleteTaskAsync(task);
                    //TaskItems = new ObservableCollection<AirportTask>(TaskItems);
                    LoadTaskInfo();
                }

            }
        }

        /// <summary>
        /// 手动呼叫
        /// </summary>
        [RelayCommand]
        private void ManualCall()
        {
            MessageBox.Show("手动呼叫");
        }

        /// <summary>
        /// 手动终止
        /// </summary>
        [RelayCommand]
        private void ManualTerminate()
        {
            MessageBox.Show("手动终止");
        }

        /// <summary>
        /// 复位
        /// </summary>
        [RelayCommand]
        private void Reset()
        {
            MessageBox.Show("复位");
        }
    }

}

