using Aucma.Core.SheetMetal.Views;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Windows;
using System;
using log4net;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Collections.ObjectModel;
using Admin.Core.Common;
using System.IO;
using Aucma.Core.HwPLc;
using Aucma.Core.Scanner;
using System.Linq;
using System.Threading.Tasks;
using Aucma.Core.SheetMetal.Business;
using System.Threading;
using Admin.Core.IService;
using Microsoft.Extensions.DependencyInjection;
using System.Windows.Threading;
using StackExchange.Profiling.Helpers;
using Aucma.Core.SheetMetal.Config;

namespace Aucma.Core.SheetMetal.ViewModels
{
    public partial class MainWindowViewModel : ObservableObject
    {
        private AppConfig appConfig = AppConfig.Instance;
        private static readonly log4net.ILog log = LogManager.GetLogger(typeof(MainWindowViewModel));
        private ISysUserInfoServices _sysUserInfoServices;
        private IndexPageView firstPage = new IndexPageView();//首页
        private LogPageView logPage = new LogPageView();//日志
        private BomMaintenancePageView bomMaintenancePageView = new BomMaintenancePageView();//钣金设备BOM维护
        private StatisticsPageView statisticsPage = new StatisticsPageView();//统计
        private SheetMetalPlanTaskHandle _taskHandle = new SheetMetalPlanTaskHandle();
       

        #region 构造函数
        public MainWindowViewModel()
        {
            _sysUserInfoServices = App.ServiceProvider.GetService<ISysUserInfoServices>();
            UserContent = firstPage;
            init();
           
            //Task.Run(() =>
            //{
            //    //_taskHandle.InitSendPlan();
            //    _taskHandle.InitSendBackPanelPlan();
            //});
            //Task.Run(() =>
            //{
            //    _taskHandle.InitSendSidePanelPlan();
            //});

            //Task.Run( () =>
            //{
            //    _taskHandle.UpdateComplatePlan();//更新计划数
            //});

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);   //间隔1秒
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }
        #endregion

        #region 初始化班组刷新定时任务
        public void init()
        {
            TeamName = $"班组:{appConfig.TeamName}  用户:{appConfig.Account}";
            // 设备状态刷新定时器
            System.Timers.Timer timer = new System.Timers.Timer(1000 * 5);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(RefreshStatus);
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Start();
        } 
        #endregion

        //#region 刷新上班时间
        //public async Task RefreshTeamTime()
        //{
        //    while (true)
        //    {
        //        var list = await _sysUserInfoServices.GetTeamData();
        //        if (list != null && list.Count > 0)
        //        {
        //            var sysUserInfo = list.First();
        //            TeamName = $"{sysUserInfo.TeamName}({list.Min(d => d.StartTime).ToString("HH:mm")}~{list.Max(d => d.EndTime).ToString("HH:mm")})";
        //            //TeamName = $"{sysUserInfo.TeamName}";
        //        }
        //        Thread.Sleep(5000);
        //    }
        //}

        //#endregion

        #region 设备状态刷新
        /// <summary>
        /// 设备状态刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void RefreshStatus(object sender, System.Timers.ElapsedEventArgs e)
        {
            RefreshMesDb();
            RefreshPlc();
           

        }
        /// <summary>
        /// 数据库状态刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void RefreshMesDb()
        {
            MesDbState(true);
        }


        /// <summary>
        /// plc状态刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void RefreshPlc()
        {
            // 后板plc
            var obj = PlcHelper.melsecList.FirstOrDefault(d => d.EquipName.Equals("BackPanelPLC"));
            if (obj != null)
            {
                if (obj.plc.IsConnected)
                {
                    PlcState(true);
                }
                else
                {
                    PlcState(false);
                }
            }
            else
            {
                PlcState(false);
            }
            // u壳plc
            var obj2 = PlcHelper.melsecList.FirstOrDefault(d => d.EquipName.Equals("SidePanelPlc"));
            if (obj2 != null)
            {
                if (obj2.plc.IsConnected)
                {
                    Plc2State(true);
                }
                else
                {
                    Plc2State(false);
                }
            }
            else
            {
                Plc2State(false);
            }

        }
      
        #endregion

        #region 更换界面

        public System.Windows.Controls.UserControl _content;

        public System.Windows.Controls.UserControl UserContent
        {
            get => _content;
            set => SetProperty(ref _content, value);
        }

        #endregion

        #region 窗口操作
        /// <summary>
        /// 窗口操作
        /// </summary>
        [RelayCommand]
        private void FormControl(object obj)
        {
            try
            {
                string controlType = obj as string;
                switch (controlType)
                {
                   
                    // 打开软盘
                    case "TabTip":

                        OpenOsk();
                        break;
                    // 还原 或者 最大化当前窗口
                    case "Normal":
                        if (Application.Current.MainWindow.WindowState == WindowState.Normal)
                        {
                            Application.Current.MainWindow.WindowState = WindowState.Maximized;
                            break;
                        }
                        if (Application.Current.MainWindow.WindowState == WindowState.Maximized)
                        {
                            Application.Current.MainWindow.WindowState = WindowState.Normal;
                            break;
                        }
                        break;

                  
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                log.Error("窗体控制逻辑异常", ex);
            }

        }


        #region 最小化界面
        /// <summary>
        /// 关闭当前界面
        /// </summary>
        /// <param name="parameter"></param>
        [RelayCommand]
        public void MinWindow(object parameter)
        {
            var window = parameter as Window;
            if (window == null) return;
            window.WindowState = WindowState.Minimized;

        }

        #endregion


        #region 关闭当前界面
        /// <summary>
        /// 关闭当前界面
        /// </summary>
        /// <param name="parameter"></param>
        [RelayCommand]
        public void CloseWindow(object parameter)
        {
            var window = parameter as Window;
            if (window == null) return;

            if (MessageBox.Show("确定要退出系统吗?", "系统提醒", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
            {
                appConfig.TeamCode = "";
                appConfig.TeamName = "";
                appConfig.Account = "";

                window.Hide();
                //跳转到登录页
                LoginPageView login = new LoginPageView();
                login.Show();
                window.Close();
            }
        }

        #endregion



        #endregion



        #region 打开软盘
        /// <summary>
        /// 打开软盘
        /// </summary>
        public static void OpenOsk()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = @"C:\Windows\System32\osk.exe";
            proc.StartInfo.UseShellExecute = true;
            proc.StartInfo.Verb = "runas";
            proc.Start();
        }
        #endregion

        #region 界面切换
        /// <summary>
        /// 界面切换
        /// </summary>
        [RelayCommand]
        private void SwitchPages(object obj)
        {
            string page = obj as string;
            switch (page)
            {
                case "FirstPage":
                    UserContent = firstPage;
                    break;
                case "LogPage":
                    UserContent = logPage;
                    break; 
                case "StatisticsPage":
                    UserContent = statisticsPage;
                    break;
                case "BomPage":
                    UserContent = bomMaintenancePageView;
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region MES数据库状态
        /// <summary>
        /// MES数据库-文字
        /// </summary>
        public string _mesDbUIStatusWb;
        public string MesDbUIStatusWb
        {
            get => _mesDbUIStatusWb;
            set => SetProperty(ref _mesDbUIStatusWb, value);
        }
        /// <summary>
        /// MES数据库-颜色
        /// </summary>
        public string _mesDbUIColor;
        public string MesDbUIColor
        {
            get => _mesDbUIColor;
            set => SetProperty(ref _mesDbUIColor, value);
        }
        /// <summary>
        /// MES数据库-图标
        /// </summary>
        public string _mesUIIcon;
        public string MesUIIcon
        {
            get => _mesUIIcon;
            set => SetProperty(ref _mesUIIcon, value);
        }

        /// <summary>
        /// MES数据库连接状态
        /// </summary>
        /// <param name="type"></param>
        public void MesDbState(bool type)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (type)
                {
                    MesDbUIStatusWb = "MES数据库";
                    MesDbUIColor = "Green";
                    MesUIIcon = "Assets/Images/Green.png";
                }
                else
                {
                    MesDbUIStatusWb = "MES数据库";
                    MesDbUIColor = "Red";
                    MesUIIcon = "Assets/Images/Red.png";
                }
            });
        }
        #endregion

        #region 后板plc 状态
        /// <summary>
        /// UI plc 展示状态-文字
        /// </summary>
        public string _plcUIStatusWb;
        public string PlcUIStatusWb
        {
            get => _plcUIStatusWb;
            set => SetProperty(ref _plcUIStatusWb, value);
        }
        /// <summary>
        /// UI plc 展示状态-颜色
        /// </summary>
        public string _plcUIColor;
        public string PlcUIColor
        {
            get => _plcUIColor;
            set => SetProperty(ref _plcUIColor, value);
        }
        /// <summary>
        /// UI plc 展示状态-图标
        /// </summary>
        public string _plcUIIcon;
        public string PlcUIIcon
        {
            get => _plcUIIcon;
            set => SetProperty(ref _plcUIIcon, value);
        }

        /// <summary>
        /// 后板PLC连接状态-true:连接成功;false:失败
        /// </summary>
        /// <param name="type"></param>
        public void PlcState(bool type)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (type)
                {
                    PlcUIStatusWb = "后板PLC";
                    PlcUIColor = "Green";
                    PlcUIIcon = "Assets/Images/Green.png";
                }
                else
                {
                    PlcUIStatusWb = "后板PLC";
                    PlcUIColor = "Red";
                    PlcUIIcon = "Assets/Images/Red.png";
                }
            });
        }
        #endregion

        #region U壳PLC状态
        /// <summary>
        /// UI plc 展示状态-文字
        /// </summary>
        public string _plc2UIStatusWb;
        public string Plc2UIStatusWb
        {
            get => _plc2UIStatusWb;
            set => SetProperty(ref _plc2UIStatusWb, value);
        }
        /// <summary>
        /// UI plc 展示状态-颜色
        /// </summary>
        public string _plc2UIColor;
        public string Plc2UIColor
        {
            get => _plc2UIColor;
            set => SetProperty(ref _plc2UIColor, value);
        }
        /// <summary>
        /// UI plc 展示状态-图标
        /// </summary>
        public string _plc2UIIcon;
        public string Plc2UIIcon
        {
            get => _plc2UIIcon;
            set => SetProperty(ref _plc2UIIcon, value);
        }

        /// <summary>
        /// PLC连接状态-true:连接成功;false:失败
        /// </summary>
        /// <param name="type"></param>
        public void Plc2State(bool type)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (type)
                {
                    Plc2UIStatusWb = "U壳PLC";
                    Plc2UIColor = "Green";
                    Plc2UIIcon = "Assets/Images/Green.png";
                }
                else
                {
                    Plc2UIStatusWb = "U壳PLC";
                    Plc2UIColor = "Red";
                    Plc2UIIcon = "Assets/Images/Red.png";
                }
            });
        }
        #endregion

        #region 刷新时间

        public string _currentDateTime;
        public string CurrentDateTime
        {
            get => _currentDateTime;
            set => SetProperty(ref _currentDateTime, value);
        }
        #endregion

        #region 班组信息
        /// <summary>
        /// 班组信息
        /// </summary>
        public string _teamName;
        public string TeamName
        {
            get => _teamName;
            set => SetProperty(ref _teamName, value);
        }
        #endregion

        #region 定时刷新时间
        void timer_Tick(object sender, EventArgs e)
        {
            System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
            {
                CurrentDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            }));

        }
        #endregion
    }
}