using HighWayIot.Log4net;
using HighWayIot.Plc;
using HighWayIot.Winform.Business;
using HighWayIot.Winform.UserControlPages;
using HighWayIot.Winform.UserControlPages.MaterialConfigPages;
using HighWayIot.Winform.UserControlPages.ParamConfigPages;
using HighWayIot.Winform.UserControlPages.SysConfigPages;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace HighWayIot.Winform.MainForm
{
    public partial class BaseForm : Form
    {
        /// <summary>
        /// 日志实例
        /// </summary>
        private static LogHelper logger = LogHelper.Instance;

        /// <summary>
        /// 用户控件列表
        /// </summary>
        List<UserControl> UserControls = new List<UserControl>();

        /// <summary>
        /// 权限配置类
        /// </summary>
        RoleBusiness roleBusiness = new RoleBusiness();

        /// <summary>
        /// 工位RFID刷新类
        /// </summary>
        WorkStationBusiness workStationBusiness = new WorkStationBusiness();

        /// <summary>
        /// 配方排程刷新类
        /// </summary>
        RecipeSendBusiness recipeSendBusiness = new RecipeSendBusiness();

        /// <summary>
        /// 底边栏消息提示刷新
        /// </summary>
        public static Action<string> LogRefreshAction;

        /// <summary>
        /// 开炼机PLC看门狗 0：正常 1：异常 2：未连接
        /// </summary>
        public static int OpenMixMachineWatchDog = 2;

        /// <summary>
        /// 成型机PLC看门狗 0：正常 1：异常 2：未连接
        /// </summary>
        public static int MoldingMachineWatchDog = 2;

        /// <summary>
        /// 上一个开炼机看门狗状态
        /// </summary>
        public int LastOpenMixWatchDogNum = -1;

        /// <summary>
        /// 上一个成型机看门狗状态
        /// </summary>
        public int LastMoldingMachineWatchDogNum = -1;

        /// <summary>
        /// 看门狗计时器
        /// </summary>
        private System.Threading.Timer WatchDogTimer;

        public BaseForm()
        {
            InitializeComponent();
            Init();
        }

        /// <summary>
        /// 初始化类
        /// </summary>
        public void Init()
        {
            logger.Info("主页面已启动");
            TimeDisplayTimer.Start();
            NowLoginUserName.Text = RoleBusiness.LoginUserName;
            UserPanelSwitch(typeof(MonitorMainPage), "监控主页面");
            RoleControl();
            WatchDogTimer = new System.Threading.Timer(WarchDogJudge, null, 0, 2000); // 每2秒执行一次
            LogRefreshAction += (log) =>
            {
                LogInformationToolStrip.Text = log;
            };
        }

        /// <summary>
        /// 系统退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SysQuitStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogoutStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }

        /// <summary>
        /// 菜单事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StripMenuItemClick(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem item && sender != null)
            {
                ToolStripMenuItem button = item;
                switch (button.Text)
                {
                    case "角色管理":
                        UserPanelSwitch(typeof(RoleConfigPage), button.Text);
                        break;
                    case "用户管理":
                        UserPanelSwitch(typeof(UserConfigPage), button.Text);
                        break;
                    case "操作日志":
                        UserPanelSwitch(typeof(OperateConfigPage), button.Text);
                        break;
                    case "报警日志":
                        UserPanelSwitch(typeof(AlarmConfigPage), button.Text);
                        break;
                    case "监控主页面":
                        UserPanelSwitch(typeof(MonitorMainPage), button.Text);
                        break;
                    case "PLC测试页面":
                        UserPanelSwitch(typeof(TestPage), button.Text);
                        break;
                    case "班时间维护":
                        UserPanelSwitch(typeof(ShiftTimePage), button.Text);
                        break;
                    case "物料管理":
                        UserPanelSwitch(typeof(MaterialConfigPage), button.Text);
                        break;
                    case "物料类型管理":
                        UserPanelSwitch(typeof(MaterialTypeConfigPage), button.Text);
                        break;
                    case "配方管理":
                        UserPanelSwitch(typeof(RecipeConfigPage), button.Text);
                        break;
                    case "日报表":
                        UserPanelSwitch(typeof(DailyReportPage), button.Text);
                        break;
                    case "机台物料信息绑定":
                        UserPanelSwitch(typeof(EquipParamSettingPage), button.Text);
                        break;
                    case "硫化排程":
                        UserPanelSwitch(typeof(ProductionScheduling), button.Text);
                        break;
                    case "RFID参数配置":
                        UserPanelSwitch(typeof(RFIDParamSettingPage), button.Text);
                        break;
                    case "":
                        break;
                    default:
                        MessageBox.Show("找不到按钮！");
                        break;
                }
            }
        }

        /// <summary>
        /// 切换前端页面，动态创建
        /// </summary>
        /// <param name="userControlType">Usercontrol类型</param>
        /// <param name="tag">名称标签</param>
        private void UserPanelSwitch(Type userControlType, string tag)
        {
            bool flag = false;
            foreach (UserControl us in UserControls)
            {
                if (us.GetType() == userControlType)
                {
                    flag = true;
                    //如果在标签页里，切换选项卡
                    if (UserControlTabs.Contains(us) || us.Tag.ToString() == tag)
                    {
                        try
                        {
                            foreach (Control control in this.UserControlTabs.Controls)
                            {
                                if (control is TabPage page)
                                {
                                    if (page.Text == tag)
                                    {
                                        UserControlTabs.SelectedTab = page;
                                    }
                                }
                            }
                        }
                        catch (ArgumentNullException ex)
                        {
                            logger.Error("找不到相关标签页！请重启程序！", ex);
                        }
                        catch (Exception ex)
                        {
                            logger.Error("标签页未知错误！", ex);
                        }
                    }
                    //如果不在标签页里
                    else
                    {
                        TabPage tabPage = new TabPage(tag);
                        us.Parent = tabPage;

                        UserControlTabs.TabPages.Add(tabPage);
                    }
                    break;
                }
            }
            if (!flag)
            {
                try
                {
                    // 动态创建新的 UserControl 实例
                    object obj = Activator.CreateInstance(userControlType);
                    if (obj is UserControl newControl)
                    {
                        newControl.Tag = tag;
                        UserControls.Add(newControl); // 将新实例添加到列表
                        TabPage tabPage = new TabPage(tag);

                        newControl.Parent = tabPage;
                        newControl.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
                        newControl.Dock = DockStyle.Fill;
                        UserControlTabs.TabPages.Add(tabPage);
                        UserControlTabs.SelectedTab = tabPage;
                    }
                    else
                    {
                        throw new InvalidOperationException($"类型 {userControlType.Name} 不是有效的 UserControl 类型");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("无法创建用户控件实例", ex);
                    MessageBox.Show($"无法创建用户控件实例：{ex.Message}", "错误");
                }
            }
        }

        /// <summary>
        /// 关闭当前选择的子窗口按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseButton_Click(object sender, EventArgs e)
        {
            // 删除时判断是否还存在TabPage
            if (UserControlTabs.SelectedIndex > -1)
            {
                string selectedStr = UserControlTabs.SelectedTab.Text;

                //获取当前标签页的索引
                int selectedIndex = UserControlTabs.SelectedIndex;

                //使用TabControl控件的TabPages属性的Remove方法移除指定的选项卡
                UserControlTabs.TabPages.Remove(UserControlTabs.SelectedTab);

                //删除列表里的实例
                UserControls.RemoveAll(x => x.Tag.ToString() == selectedStr);

                //删除时如果标签没删干净，删完选择最后一个标签
                if (UserControlTabs.TabCount != 0)
                {
                    if (selectedIndex == 0)
                    {
                        UserControlTabs.SelectedTab = UserControlTabs.TabPages[0];
                    }
                    else
                    {
                        UserControlTabs.SelectedTab = UserControlTabs.TabPages[selectedIndex - 1];
                    }
                }
            }
        }

        /// <summary>
        /// 走不动道小时钟
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimeDisplayTimer_Tick(object sender, EventArgs e)
        {
            TimeStripLabel.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }

        /// <summary>
        /// 权限控制
        /// </summary>
        private void RoleControl()
        {
            foreach (ToolStripMenuItem i in MainMenu.Items)
            {
                TraverseMenuitem(i);
            }
        }

        /// <summary>
        /// 递归遍历MenuItem
        /// </summary>
        /// <param name="item"></param>
        private void TraverseMenuitem(ToolStripMenuItem item)
        {
            item.Enabled = roleBusiness.PageIsAccess(item.Text);
            //if(UserControls.Where(x => x.Tag == item.Text))
            foreach (ToolStripMenuItem i in item.DropDownItems)
            {
                TraverseMenuitem(i);
            }
        }

        /// <summary>
        /// PLC看门狗状态判断
        /// </summary>
        /// <param name="WatchDogPoint">看门狗点位</param>
        /// <returns></returns>
        private void WarchDogJudge(object state)
        {
            //int openMixNow, moldingNow;
            //if (PlcConnect.IsConnect1)
            //{
            //    openMixNow = PlcConnect.ReadInt161("D666");
            //    if (openMixNow == LastOpenMixWatchDogNum)
            //    {
            //        OpenMixMachineWatchDog = 0;
            //    }
            //    else
            //    {
            //        OpenMixMachineWatchDog = 1;
            //    }
            //}
            //else
            //{
            //    OpenMixMachineWatchDog = 2;
            //}

            //if (PlcConnect.IsConnect2)
            //{
            //    moldingNow = PlcConnect.ReadInt162("D666");
            //    if (moldingNow == LastMoldingMachineWatchDogNum)
            //    {
            //        MoldingMachineWatchDog = 0;
            //    }
            //    else
            //    {
            //        MoldingMachineWatchDog = 1;
            //    }
            //}
            //else
            //{
            //    MoldingMachineWatchDog = 2;
            //}
        }
    }
}
