using Model;
using Permission;
using PlcUiControl;
using PlcUiForm;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XmlToTreeView;
using YangjieTester.IO监控;
using YangjieTester.主界面;
using YangjieTester.元件目标设置;
using YangjieTester.工站操作;
using YangjieTester.常用设置;
using YangjieTester.数据管控;
using YangjieTester.机台日志表现;
using YangjieTester.点检视图;
using YangjieTester.用户管理;
using YangjieTester.设备状态;
namespace YangjieTester
{
    [FormDescriptionAttribute("程序主界面")]
    public partial class MainForm :PlcBaseForm
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 获取包含入口点的程序集
            Assembly assembly = Assembly.GetExecutingAssembly();

            // 获取程序集版本
            string assemblyVersion = assembly.GetName().Version.ToString();
            lblSoftVersion.Text = " ver:" + assemblyVersion;
            plcUiButton1_Click(btn主界面, null);

            SetConnectionStatus(this.PlcComProtocol.IsConnected);

            this.ProtocollReadOK += MainForm_ProtocollReadOK;
            this.ProtocollReadOverTime += MainForm_ProtocollReadOverTime;

            AppEx.RootFormNeedClose += AppEx_RootFormNeedClose;

            BackgroundService.Instance.AlarmMonitor.OnDatasEqualTarget += AlarmMonitor_OnDatasEqualTarget;
            BackgroundService.Instance.AlarmMonitor.OnAllDataCleared += AlarmMonitor_OnAllDataCleared;

            BackgroundService.Instance.TipsMonitor.OnDatasEqualTarget += TipsMonitor_OnDatasEqualTarget;
            BackgroundService.Instance.TipsMonitor.OnAllDataCleared += TipsMonitor_OnAllDataCleared;


            lblUserName.Text = AppSession.CurrentUser.PermissionLevel +"：" +AppSession.CurrentUser.Username;
            PermissionManager.OnPermissionLevelChanged += PermissionManager_OnPermissionLevelChanged;
            //await Task.Delay(3000);
            //AlarmMonitor_OnDatasEqualTarget(null,new List<PlcComponent.MonitorRule>() { new PlcComponent.MonitorRule() { Message="TestAlarm"} });

            //await Task.Delay(3000);
            //TipsMonitor_OnDatasEqualTarget(null, new List<PlcComponent.MonitorRule>() { new PlcComponent.MonitorRule() { Message = "TestTips" } });
        }

        private void PermissionManager_OnPermissionLevelChanged(PermissionLevel obj)
        {
            lblUserName.Text = AppSession.CurrentUser.PermissionLevel + "：" + AppSession.CurrentUser.Username;
        }

        MessageForm alarmMessageForm = null, tipssMessageForm = null;
        string alarmMessageInfo, tipsMessageInfo;


        private void AlarmMonitor_OnDatasEqualTarget(object arg1, List<PlcComponent.MonitorRule> arg2)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => AlarmMonitor_OnDatasEqualTarget(arg1, arg2)));
            }
            else
            {
                var msg = arg2.Select(m => m.Message).ToList();
                var info = string.Join(Environment.NewLine, msg);

                if(alarmMessageInfo!=info)
                {
                    alarmMessageInfo = info;

                    if (alarmMessageForm == null || alarmMessageForm.IsDisposed)
                    {
                        alarmMessageForm = new MessageForm("设备报警", alarmMessageInfo, Color.Red);
                        alarmMessageForm.Deactivate += (s, e) => { alarmMessageForm.Close(); };
                        //alarmMessageForm.TopMost = true;
                        alarmMessageForm.Show();
                    }
                    else
                    {
                        alarmMessageForm.Info = alarmMessageInfo;
                    }
                }
            }
        }
        private void AlarmMonitor_OnAllDataCleared(object obj)
        {
            if (alarmMessageForm != null && !alarmMessageForm.IsDisposed)
            {
                alarmMessageForm.Close();
                alarmMessageInfo = null;
            }
        }
        private void TipsMonitor_OnDatasEqualTarget(object arg1, List<PlcComponent.MonitorRule> arg2)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => TipsMonitor_OnDatasEqualTarget(arg1, arg2)));
            }
            else
            {
                var msg = arg2.Select(m => m.Message).ToList();
                var info = string.Join(Environment.NewLine, msg);

                if (tipsMessageInfo != info)
                {
                    tipsMessageInfo = info;

                    if (tipssMessageForm == null || tipssMessageForm.IsDisposed)
                    {
                        tipssMessageForm = new MessageForm("提示", tipsMessageInfo, Color.Orange);
                        tipssMessageForm.Deactivate += (s, e) => { tipssMessageForm.Close(); };
                        //tipssMessageForm.TopMost = true;
                        tipssMessageForm.Show();
                    }
                    else
                    {
                        tipssMessageForm.Info = tipsMessageInfo;
                    }
                }
            }
        }
        private void TipsMonitor_OnAllDataCleared(object obj)
        {
            if (tipssMessageForm != null && !tipssMessageForm.IsDisposed)
            {
                tipssMessageForm.Close();
                tipsMessageInfo = null;
            }
        }
        private void AppEx_RootFormNeedClose(object sender, EventArgs e)
        {
            Close();
        }

        void SetConnectionStatus(bool PlcConnected)
        {
            if(PlcConnected)
            {
                lblPlcConnection.Text = $"PLC连接正常";
                lblPlcConnection.ForeColor = Color.Black;
            }
            else
            {
                lblPlcConnection.Text = $"PLC未连接";
                lblPlcConnection.ForeColor = Color.Red;
            }
        }
        private void MainForm_ProtocollReadOK()
        {
            lblPlcConnection.Text = $"PLC读取正常";
            lblPlcConnection.ForeColor = Color.Black;
        }

        private void MainForm_ProtocollReadOverTime()
        {
            lblPlcConnection.Text = $"PLC读超时，尝试自动重连";
            lblPlcConnection.ForeColor = Color.Red;
        }

        private void plcUiButton1_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new HomeForm());
        }

        private void plcUiButton2_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new StationOpMainForm());
        }

        private void plcUiButton3_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new DataControlForm());
        }

        private void plcUiButton4_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new CellTargetSettingForm());
        }

        private void plcUiButton5_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new CommonSettingForm());
        }

        private void plcUiButton6_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new MachineStateForm());
        }

        private void plcUiButton7_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new IoMonitorForm());
        }

        private void plcUiButton8_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new MachineLogForm());
        }

        private void plcUiButton9_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new OtherForm());
        }

        private void btn最小化_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void myUiButton10_Click(object sender, EventArgs e)
        {
            FormEx.SetButtonSelected(sender);
            FormEx.ShowSubForm(FormPanel, new UserManagerForm());
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            BackgroundService.Instance.AlarmMonitor.OnDatasEqualTarget -= AlarmMonitor_OnDatasEqualTarget;
            BackgroundService.Instance.AlarmMonitor.OnAllDataCleared -= AlarmMonitor_OnAllDataCleared;

            BackgroundService.Instance.TipsMonitor.OnDatasEqualTarget -= TipsMonitor_OnDatasEqualTarget;
            BackgroundService.Instance.TipsMonitor.OnAllDataCleared -= TipsMonitor_OnAllDataCleared;
        }
    }
}
