using Model;
using PlcComponent;
using PlcUiControl;
using PlcUiForm;
using StandardLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YangjieTester
{
    public partial class Form主界面 : PlcBaseForm
    {
        public Form主界面()
        {
            InitializeComponent();
            BackgroundService.Instance.AlarmMonitor.OnDatasEqualTarget += AlarmMonitor_OnDatasEqualTarget;
            BackgroundService.Instance.AlarmMonitor.OnAllDataCleared += AlarmMonitor_OnAllDataCleared;

            //BackgroundService.Instance.AlarmMonitor.OnAllDataRefreshed += AlarmMonitor_OnAllDataRefreshed;

            BackgroundService.Instance.TipsMonitor.OnDatasEqualTarget += TipsMonitor_OnDatasEqualTarget;
            BackgroundService.Instance.TipsMonitor.OnAllDataCleared += TipsMonitor_OnAllDataCleared;
        }
        int count;
        private void AlarmMonitor_OnAllDataRefreshed(object arg1, List<PlcComponent.MonitorRule> arg2)
        {
            count++;
            panelAlarm.Text = count.ToString();
        }

        private void Form主界面_Load(object sender, EventArgs e)
        {
            FormEx.ShowSubForm(uiPanel1, new RunDataForm());
        }
        private void btn工站时间监控_Click(object sender, EventArgs e)
        {
            FormEx.ShowSubForm(uiPanel1, new SpeedMonitorForm());
        }

        private void btn跑马灯_Click(object sender, EventArgs e)
        {
            FormEx.ShowSubForm(uiPanel1, new FlashLightForm());
        }

        private void btn生产数据_Click(object sender, EventArgs e)
        {
            FormEx.ShowSubForm(uiPanel1, new RunDataForm());
        }
        private void btnAlarmLog_Click(object sender, EventArgs e)
        {
            FormEx.ShowSubForm(uiPanel1, new HistoryDataForm());
        }
        private void btn吸嘴故障计数监控_Click(object sender, EventArgs e)
        {
            FormEx.ShowSubForm(uiPanel1, new NozzleLifeCountForm());
        }

        private void os确认系统退出_Button1MouseDown(object sender, EventArgs e)
        {
            //FormEx.NeedCloseApp();
            var timer = new Timer() { Interval = 200 };
            timer.Tick += (s, e1) => { timer.Stop(); AppEx.NeedCloseApp(); /*Application.Exit();*/ };
            timer.Start();
        }

        bool haveAlarmHappened;

        private void AlarmMonitor_OnDatasEqualTarget(object arg1, List<PlcComponent.MonitorRule> arg2)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => AlarmMonitor_OnDatasEqualTarget(arg1, arg2)));
            }
            else
            {
                var monitor = (PlcComponent.PlcDataMonitor)arg1;

                haveAlarmHappened = true;
                panelAlarm.Style = Sunny.UI.UIStyle.Red;

                var msg = arg2.Select(m => m.Message).ToList();

                txtAlarm.Text = string.Join(Environment.NewLine, msg);
            }
        }
        private void AlarmMonitor_OnAllDataCleared(object obj)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => AlarmMonitor_OnAllDataCleared(obj)));
            }
            else
            {
                if (haveAlarmHappened)
                {
                    haveAlarmHappened = false;
                    panelAlarm.Style = Sunny.UI.UIStyle.Green;
                    txtAlarm.Text = string.Empty;
                }
            }
        }

        bool haveTipsShown;
        private void TipsMonitor_OnDatasEqualTarget(object arg1, List<PlcComponent.MonitorRule> arg2)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => TipsMonitor_OnDatasEqualTarget(arg1, arg2)));
            }
            else
            {
                var monitor = (PlcComponent.PlcDataMonitor)arg1;

                haveTipsShown = true;
                panelTips.Style = Sunny.UI.UIStyle.LayuiOrange;

                var msg = arg2.Select(m => m.Message).ToList();
                txtTips.Text = string.Join(Environment.NewLine, msg);
            }
        }
        private void TipsMonitor_OnAllDataCleared(object obj)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => TipsMonitor_OnAllDataCleared(obj)));
            }
            else
            {
                if (haveTipsShown)
                {
                    haveTipsShown = false;
                    panelTips.Style = Sunny.UI.UIStyle.Inherited;
                    txtTips.Text = string.Empty;
                }
            }
        }


        private void Form主界面_FormClosing(object sender, FormClosingEventArgs e)
        {
            BackgroundService.Instance.AlarmMonitor.OnDatasEqualTarget -= AlarmMonitor_OnDatasEqualTarget;
            BackgroundService.Instance.AlarmMonitor.OnAllDataCleared -= AlarmMonitor_OnAllDataCleared;

            //BackgroundService.Instance.AlarmMonitor.OnAllDataRefreshed -= AlarmMonitor_OnAllDataRefreshed;

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

        private void btn工站时间监控_Click_1(object sender, EventArgs e)
        {
            new SpeedMonitorForm().ShowDialog();
        }

        private void btn测试模式选择_Click(object sender, EventArgs e)
        {
            new TestModeSettingForm().ShowDialog();
        }

        private void btn吸嘴良率统计_Click(object sender, EventArgs e)
        {
            new NozzleNGCountForm().ShowDialog();
        }

        private void btnNG停止设置_Click(object sender, EventArgs e)
        {
            new TestNGStopSettingForm().ShowDialog();
        }

        private void btn胶膜载带设置_Click(object sender, EventArgs e)
        {
            new TapeSettingForm().ShowDialog();
        }

        private void btn首件打样设置_Click(object sender, EventArgs e)
        {
            new FirstTestSettingForm().ShowDialog();
        }


        private void btn开启批次_OptionSelect(object sender, DialogResult dialogResult)
        {

        }
        private void btn结束批次_OptionSelect(object sender, DialogResult dialogResult)
        {

        }
        private void bnt当前批次报告_Click(object sender, EventArgs e)
        {
            var batch = BatchService.GetLatestBatch(out string error);

            if (batch == null)
            {
                MessageBox.Show(error, "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (batch.Finished)
            {
                MessageBox.Show("当前批次已完成，请到批次记录查询", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else//此时的batch仅有开始时间，开始人员信息有意义。
            {
                new BatchReportForm(batch).ShowDialog();
            }
        }

        private void myUiButton1_Click(object sender, EventArgs e)
        {
            new NozzleLifeCountForm().ShowDialog();
        }

        private void btn视觉仿真设置_Click(object sender, EventArgs e)
        {
            new VisionModeSettingForm().ShowDialog();
        }

        private void btn消耗品寿命设定_Click(object sender, EventArgs e)
        {
            new ConsumablesSettingForm().ShowDialog();
        }
        private void btn开启批次_BeforeWrite(object sender, CancelEventArgs e)
        {
            //if(AppSession.MachineState.IsBatchOn)
            //{
            //    MessageBox.Show("批次执行中，请先结束批次","提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    e.Cancel = true;
            //}

            if (AppSession.MachineState.Status != Status.Ready && AppSession.MachineState.Status != Status.Paused)
            {
                MessageBox.Show("设备不在就绪或暂停状态，不能新建批次", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
            else
            {
                var kb = new FullKeyboardForm() { Caption = "批次号" };
                var dr = kb.ShowDialog();
                if (dr != DialogResult.OK)
                {
                    e.Cancel = true;//不让PLC进行清零动作。
                }
                else
                {
                    var b = BatchService.CreateBatchLog(kb.Value, AppSession.CurrentUser, out string err);
                    if (!b)
                    {
                        MessageBox.Show(err, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        e.Cancel = true;
                        return;
                    }
                    else
                    {
                        AppSession.CurrentBatch.BatchID = kb.Value;
                        AppSession.CurrentBatch.StartTime = DateTime.Now;
                        AppSession.CurrentBatch.RecipeName = null;
                        MessageBox.Show("新建批次成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
            }
        }

        private void btn结束批次_BeforeWrite(object sender, CancelEventArgs e)
        {
            if (AppSession.MachineState.Status != Status.Ready && AppSession.MachineState.Status != Status.Paused)
            {
                MessageBox.Show("设备不在就绪或暂停状态，不能结束批次", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
            else
            {
                var b = BackgroundService.Instance.RefreshInstanceFromPLC(AppSession.CurrentBatch);//刷新当前批次的数据。
                //后续增加批次中的各种报警代码计数，MTTB之类的计算。
                if (!b)
                {
                    MessageBox.Show("PLC读取失败，不能结束批次", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }
                b = BatchService.FinishLatestBatch(AppSession.CurrentBatch, AppSession.CurrentUser, out string err);
                if (!b)
                {
                    MessageBox.Show(err, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }
                else
                {
                    AppSession.CurrentBatch.EndTime = DateTime.Now;
                    MessageBox.Show("批次结束成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }
}
