using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using DH.Commons.Enums;
using DH.Commons.Base;


namespace XKRS.UI.Device.Winform
{
    public partial class CtrlVisionRunBase : UserControl
    {

        private DateTime LastDisplayTime = DateTime.MinValue;


        //public CtrlVisionRunBase()
        //{
        //    InitializeComponent();
        //}

        //private object OnUpdateBatchNO(ISubscriber arg1, object arg2, object arg3)
        //{
        //    //获取BatchNO
        //    if (arg2 is string batchNo)
        //    {
        //        ML.BatchNO = string.IsNullOrEmpty(batchNo) ? "OFFline_" + DateTime.Now.ToString("yyyyMMdd") : batchNo;
        //    }
        //    return null;
        //}

        public CtrlVisionRunBase(VisionEngineBase device)
        {
            InitializeComponent();

            Device = device;
            InitialLayout();

            this.Load += (s, e) =>
              {
                  ML.OnDetectionDone -= ML_OnDetectionDone;
                  ML.OnDetectionDone += ML_OnDetectionDone;
              };

           // PubSubCenter.GetInstance().RemoveSubscribers(PubSubCenterMessageType.UpdateBatchNO.ToString());
           // PubSubCenter.GetInstance().Subscribe(PubSubCenterMessageType.UpdateBatchNO.ToString(), OnUpdateBatchNO);
        }




        private async void ML_OnDetectionDone(string detectionId, Bitmap image, List<IShapeElement> detectionResults)
        {

            await Task.Run(() =>
            {
                if (!this.IsHandleCreated)
                    return;

                this.Invoke(new Action(() =>
                {
                    if (this.IsDisposed)
                        return;
                    var display = displayList.FirstOrDefault(u => u.DetectionId == detectionId);
                    if (display != null)
                    {
                        display.RefreshDetectionResult(image, detectionResults);
                    }
                }));
            });
        }

        public VisionEngineBase Device { get; set; }

        protected VisionEngineBase ML
        {
            get => Device as VisionEngineBase;
        }
        
        //VisionEngineInitialConfigBase IConfig => ML?.InitialConfig as VisionEngineInitialConfigBase;

        //VisionEngineOperationConfigBase OpConfig = new VisionEngineOperationConfigBase();

        //private void btnExecuteOpConfig_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        PubSubCenter.GetInstance().Publish(PubSubCenterMessageType.RequestBatchNO.ToString(), null, null);
        //        var msg = ML.RunWrap(OpConfig);

        //        if (msg.Result != 1)
        //        {
        //            MessageBox.Show(msg.Message);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.GetExceptionMessage());
        //    }
        //}

        #region Layout
        int rows = 1;
        int cols = 1;

        public int Rows
        {
            get => rows;
            set
            {
                if (value <= 1)
                {
                    rows = 1;
                }
                else
                {
                    rows = value;
                }
            }
        }

        public int Cols
        {
            get => cols;
            set
            {
                if (value <= 1)
                {
                    cols = 1;
                }
                else
                {
                    cols = value;
                }
            }
        }

        List<CtrlVisionDisplay> displayList = null;

        private void InitialLayout()
        {
            if (ML.DetectionConfigs.Count == 0)
            {
                return;
            }

            var locations = ML.DetectionConfigs.Select(u => u.ShowLocation).ToList();

            if (locations.Count > 0)
            {
                Rows = (int)locations.Max(u => u.Y);
                Cols = (int)locations.Max(u => u.X);
            }


            tableDisplay.ColumnCount = Cols;
            tableDisplay.RowCount = Rows;

            tableDisplay.ColumnStyles.Clear();
            for (int i = 0; i < Cols; i++)
            {
                ColumnStyle colStyle = new ColumnStyle();
                colStyle.SizeType = SizeType.Percent;
                colStyle.Width = 1.0f / (float)Cols;

                tableDisplay.ColumnStyles.Add(colStyle);
            }

            tableDisplay.RowStyles.Clear();
            for (int i = 0; i < Rows; i++)
            {
                RowStyle rowStyle = new RowStyle();
                rowStyle.SizeType = SizeType.Percent;
                rowStyle.Height = 1.0f / (float)Rows;

                tableDisplay.RowStyles.Add(rowStyle);
            }

            tableDisplay.Controls.Clear();
            displayList = new List<CtrlVisionDisplay>();
           
            ML.DetectionConfigs.ForEach(d =>
            {
                //if (!d.IsShowInUI)
                //    return;

                CtrlVisionDisplay display = new CtrlVisionDisplay();
                display.DetectionId = d.Id;
                display.DetectionName = d.Name;
                display.RowIndex = (int)d.ShowLocation.Y - 1;
                display.ColIndex = (int)d.ShowLocation.X - 1;
                //display.RowIndex = (int)count%row;
                //display.ColIndex = (int)count / row;

                display.Dock = DockStyle.Fill;

                display.OnShowOpConfigMenuStateChanged -= Display_OnShowOpConfigMenuStateChanged;
                display.OnShowOpConfigMenuStateChanged += Display_OnShowOpConfigMenuStateChanged;

                displayList.Add(display);
                tableDisplay.Controls.Add(display);
                tableDisplay.SetCellPosition(display, new TableLayoutPanelCellPosition(display.ColIndex, display.RowIndex));
            });

            splitCMain.Panel2Collapsed = true;

           // propOpConfig.SelectedObject = OpConfig;
        }

        private void Display_OnShowOpConfigMenuStateChanged(bool isVisible)
        {
            IsShowOpConfig = isVisible;
        }

        public bool IsShowOpConfig
        {
            get => !splitCMain.Panel2Collapsed;
            set
            {
                if (splitCMain.Panel2Collapsed == value)
                {
                    splitCMain.Panel2Collapsed = !value;

                    displayList.ForEach(d => d.IsShowOpConfig = value);
                }
            }
        }
        #endregion

        //private void btnBatchRun_Click(object sender, EventArgs e)
        //{
        //    FrmMLBatchRun frmMLBatchRun = new FrmMLBatchRun(Device);

        //    frmMLBatchRun.MdiParent = (this.Parent as DeviceRunFrmBase).MdiParent;
        //    frmMLBatchRun.DockPanel = (this.Parent as DeviceRunFrmBase).DockPanel;
        //    frmMLBatchRun.DockState = DockState.Document;
        //    frmMLBatchRun.Text = $"{Device.Name}_批量检测";

        //    frmMLBatchRun.Show();
        //}
    }
}