using CommunityToolkit.Mvvm.Input;
using GalaSoft.MvvmLight;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto.taskType;
using SlnMesnac.WPF.Model;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace SlnMesnac.WPF.ViewModel
{
    public partial class IndexViewModel : ViewModelBase
    {
        private ISqlSugarClient sqlSugarClient;
        private readonly ILogger<IndexViewModel> _logger;

        public IndexViewModel()
        {
            sqlSugarClient = App.ServiceProvider.GetService<ISqlSugarClient>()!;
            _logger = App.ServiceProvider.GetService<ILogger<IndexViewModel>>()!;
            InitData();
        }

        [RelayCommand]
        public void DeleteTask(int? id)
        {
            try
            {
                var result = MessageBox.Show("是否确认删除计划!", "确认", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    WcsTask? wcsTask = sqlSugarClient.Queryable<WcsTask>().Where(x => x.Id == id).First();
                    if (wcsTask != null && (wcsTask.TaskType == StaticTaskType.MoveLocationTask || wcsTask.TaskType == StaticTaskType.SupplyEmptyPalletTask || wcsTask.TaskType == StaticTaskType.TransferMaterialBoxTask))
                    {
                        if (wcsTask.TaskStatus >= 2)
                        {
                            //举着箱子去异常库位
                            wcsTask.IsDelete = 2;
                        }
                        else
                        { //删除任务
                            wcsTask.IsDelete = 1;
                        }
                    }
                    else
                    {
                        wcsTask.IsDelete = 1;
                    }
                    sqlSugarClient.Updateable(wcsTask).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void InitData()
        {
            Task.Run(async () =>
           {
               while (true)
               {
                   GetTaskList();
                   await RefreChartAsync();
                   await LoadAgvDataAsync();
                   //PrintMessageToListBox("测试消息" + Guid.NewGuid());
                   await Task.Delay(5000);
               }
           });
        }

        #region 参数定义

        private ObservableCollection<dynamic> listItems = new ObservableCollection<dynamic>();

        /// <summary>
        /// AGV状态信息列表
        /// </summary>
        private ObservableCollection<AgvInfo> agvList = new ObservableCollection<AgvInfo>();

        public ObservableCollection<AgvInfo> AgvList
        {
            get { return agvList; }
            set
            {
                agvList = value;
                RaisePropertyChanged(() => AgvList);
            }
        }

        /// <summary>
        /// 任务列表
        /// </summary>
        private ObservableCollection<WcsTask> wcsTaskItems = new ObservableCollection<WcsTask>();

        public ObservableCollection<WcsTask> WcsTaskItems
        {
            get { return wcsTaskItems; }
            set
            {
                wcsTaskItems = value;
                RaisePropertyChanged(() => WcsTaskItems);
            }
        }

        /// <summary>
        /// 日志LisBox数据模板
        /// </summary>
        private IEnumerable logInfoListBox;

        public IEnumerable LogInfoListBox
        {
            get { return logInfoListBox; }
            set { logInfoListBox = value; RaisePropertyChanged(() => LogInfoListBox); }
        }

        #region 日产量柱状图X轴日期

        /// <summary>
        /// 日产量柱状图X轴日期
        /// </summary>
        private List<string> productionHourList = new List<string>();

        public List<string> ProductionHourList
        {
            get { return productionHourList; }
            set { productionHourList = value; }
        }

        #endregion 日产量柱状图X轴日期

        #region 型号统计柱状图

        /// <summary>
        /// 型号统计柱状图
        /// </summary>
        private SeriesCollection achievement = new SeriesCollection();

        public SeriesCollection Achievement
        {
            get { return achievement; }
            set { achievement = value; }
        }

        #endregion 型号统计柱状图

        #endregion 参数定义

        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <returns></returns>
        private void GetTaskList()
        {
            List<WcsTask> tasks = sqlSugarClient.Queryable<WcsTask>().ToList();
            Application.Current.Dispatcher.Invoke(() =>
           {
               WcsTaskItems.Clear();
               if (tasks != null && tasks.Count > 0)
               {
                   foreach (var task in tasks)
                   {
                       WcsTaskItems.Add(task);
                   }
               }
           });
        }

        /// <summary>
        /// 系统运行日志输出
        /// </summary>
        /// <param name="message"></param>
        private void PrintMessageToListBox(string message)
        {
            try
            {
                string formattedMessage = $"{DateTime.Now.ToString("HH:mm:ss.ss")} ==> {message}";
                lock (listItems)
                {
                    listItems.Add(formattedMessage);
                    while (listItems.Count > 120)
                    {
                        listItems.RemoveAt(0);
                    }
                    var orderedList = listItems.OrderByDescending(x => x).ToList();  // 排序后转为 List
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        LogInfoListBox = orderedList;  // 更新 UI
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"日志数据绑定异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 加载AGV数据
        /// </summary>
        private async Task LoadAgvDataAsync()
        {
            try
            {
                List<WcsAgvStatus> agvList = await sqlSugarClient.Queryable<WcsAgvStatus>().OrderBy(x => x.RobotCode).ToListAsync();
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    AgvList.Clear();
                    foreach (WcsAgvStatus agv in agvList)
                    {
                        AgvInfo? agvPage = AgvList.FirstOrDefault(x => x.Name == agv.RobotCode);
                        if (agvPage != null)
                        {
                            agvPage.Battery = agv.Battery;
                            agvPage.IsOnline = bool.Parse(agv.Online);
                            agvPage.Status = agv.StatusDetail;
                            agvPage.ImageSource = GetPicturePathByStatus(agv.Status);
                        }
                        else
                        {
                            AgvList.Add(new AgvInfo
                            {
                                Name = agv.RobotCode,
                                Battery = agv.Battery,
                                IsOnline = bool.Parse(agv.Online),
                                Status = agv.StatusDetail,
                                ImageSource = GetPicturePathByStatus(agv.Status)
                            });
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }

        private string GetPicturePathByStatus(string status)
        {
            List<string> okStrings = new List<string>() { "1", "2", "4", "6", "7", "8", "63", "67", "68", "69", "70", "151", "200", "201", "202", "203", "246", "247", "248" };
            if (okStrings.Contains(status))
            {
                return "/Templates/image/agv-green.png";
            }
            else
            {
                return "/Templates/image/agv-red.png";
            }
        }

        private async Task RefreChartAsync()
        {
            try
            {
                // 查询所有任务记录
                List<WcsTaskLog> list = await sqlSugarClient.Queryable<WcsTaskLog>().Where(x => x.CreatedTime >= DateTime.Now.AddHours(-8)).ToListAsync();
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    ProductionHourList.Clear();
                    // 生成最近八小时的小时列表
                    for (int i = 7; i >= 0; i--)
                    {
                        DateTime hour = DateTime.Now.AddHours(-i);
                        ProductionHourList.Add($"{hour.Hour}:00");
                    }
                });
                // 初始化每小时任务量字典
                Dictionary<string, int> hourProductionCount = new Dictionary<string, int>();
                foreach (var hour in ProductionHourList)
                {
                    hourProductionCount[hour] = 0;
                }

                // 统计每小时任务量
                foreach (var task in list)
                {
                    string hourKey = $"{task.CreatedTime.Hour}:00";
                    if (hourProductionCount.ContainsKey(hourKey))
                    {
                        hourProductionCount[hourKey]++;
                    }
                }

                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    Achievement.Clear();
                    ChartValues<ObservablePoint> achievement = new ChartValues<ObservablePoint>();
                    int i = 0;
                    foreach (var kvp in hourProductionCount)
                    {
                        achievement.Add(new ObservablePoint(i++, kvp.Value));
                    }

                    var column = new ColumnSeries();
                    column.DataLabels = true;
                    column.Title = "agv任务量";
                    column.Values = achievement;
                    column.Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#1edaf2"));
                    column.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#1edaf2"));
                    Achievement.Add(column);
                });
            }
            catch (Exception ex)
            {
                _logger.LogError($"产量统计图表异常:{ex.Message}");
            }
        }
    }
}