using CCDCount.DLL;
using CCDCount.MODEL.ConfigModel;
using LogClass;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CCDCount.Forms
{
    public partial class IdentifyCameraForm : Form
    {
        #region 变量
        private List<CameraConfig> camerasConfig = null;
        private bool IsShow = false;
        #endregion

        #region 实例
        //主线程实例队列
        public List<MainThreadClass> LsMainThread = null;
        private MainThreadClass NowLoadMianThread = null;
        #endregion

        #region 窗体事件
        public IdentifyCameraForm(List<CameraConfig> CamerasConfigValue, List<MainThreadClass> lsMainThread)
        {
            InitializeComponent();
            camerasConfig = CamerasConfigValue;
            this.WindowState = FormWindowState.Maximized;
            LsMainThread = lsMainThread;
            StartShowImageThread();
            UpdateTapPage();
        }


        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabCameraControl.SelectedTab != null)
            {
                string currentTabName = tabCameraControl.SelectedTab.Name.Split('_')[1];
                if (LsMainThread.Count == 0)
                {
                    LOG.error(string.Format("{0}：主识别线程均未创建成功", "IdentifyCameraForm-tabControl1_SelectedIndexChanged"));
                    MessageBox.Show("主识别线程创建失败");
                    return;
                }
                // 实际使用时替换为业务逻辑
                NowLoadMianThread = LsMainThread.Where(o => o.ThisCameraSN == currentTabName).First();
                LOG.log(string.Format("{0}：当前加载的为{1}号相机", "IdentifyCameraForm-tabControl1_SelectedIndexChanged", NowLoadMianThread.ThisCamerNo));
            }
        }

        /// <summary>
        /// 界面关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IdentifyCameraForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            stopShowImageThread();
            this.Dispose();
            base.OnClosing(e);
        }
        #endregion

        #region 公共方法
        #endregion

        #region 私有方法

        /// <summary>
        /// 更新标签页
        /// </summary>
        private void UpdateTapPage()
        {
            if (camerasConfig != null)
            {
                tabCameraControl.TabPages.Clear();
                foreach (var item in camerasConfig)
                {
                    TabPage tabPage = new TabPage();
                    tabPage.Text = item.CameraName == string.Empty?item.DeviceName:item.CameraName;
                    tabPage.Name = string.Format("CameratabPage_{0}", item.CameraSNNum);
                    tabCameraControl.TabPages.Add(tabPage);

                    //var labelvalue = FindControlsBFS(this, o => o.Name == item.CameraName);
                }
                tabControl1_SelectedIndexChanged(this, null);
            }
        }

        /// <summary>
        /// 控件广度优先搜索
        /// </summary>
        /// <param name="root"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        private Control FindControlsBFS(Control root, Func<Control, bool> condition)
        {
            var results = new List<Control>();
            var queue = new Queue<Control>();
            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                var current = queue.Dequeue();
                if (condition(current)) results.Add(current);

                foreach (Control child in current.Controls)
                {
                    queue.Enqueue(child);
                }
            }
            if (results.Count == 0) return null;
            return results.First();
        }

        private void StartShowImageThread()
        {
            IsShow = true;
            Bitmap image = null;
            Stopwatch renderSW = new Stopwatch();
            const int targetMsPerFrame = 100; // 20FPS=50ms
            Task.Run(() =>
            {
                while (IsShow)
                {
                    renderSW.Restart();
                    if (NowLoadMianThread == null)
                    {
                        LOG.log(string.Format("{0}：当前加载相机空", "IdentifyCameraForm-StartShowImageThread"));
                        Thread.Sleep(100);
                        continue;
                    }
                    if (NowLoadMianThread.CameraStatic)
                    {
                        NowLoadMianThread.GetShowImage(2048, out image);
                    }
                    else
                    {
                        if(image.Size!=new Size(1,1))
                            image = new Bitmap(1, 1);
                        Thread.Sleep(100);
                        LOG.log(string.Format("{0}-{1}号相机线程启动异常", "IdentifyCameraForm-StartShowImageThread:", NowLoadMianThread.ThisCamerNo));
                    }
                    if (image == null)
                    {
                        LOG.log(string.Format("{0}：获取图片失败", "IdentifyCameraForm-StartShowImageThread"));
                        continue;
                    }
                    UpdatepictureBox1(image);
                    //进行精准20帧控制
                    int elapsed = (int)renderSW.ElapsedMilliseconds;
                    if (elapsed < targetMsPerFrame)
                    {
                        Thread.Sleep(targetMsPerFrame - elapsed);
                    }
                }
            });
        }

        private void stopShowImageThread()
        {
            IsShow = false; 
        }

        private void UpdatepictureBox1(Bitmap image)
        {
            LOG.log(string.Format("{0}：{1}号相机线程，更新显示图片", "IdentifyCameraForm-UpdatepictureBox1", NowLoadMianThread.ThisCamerNo), 0);
            if (ImageShowBox.InvokeRequired)
            {
                try
                {
                    ImageShowBox.Invoke(new Action<Bitmap>(UpdatepictureBox1), image);
                }
                catch (Exception ex)
                {
                    LOG.log(string.Format("{0}：{1}号相机线程，更新显示图片失败，{2}",
                        "IdentifyCameraForm-UpdatepictureBox1", NowLoadMianThread.ThisCamerNo,ex.Message.ToString()));
                }
            }
            else
            {
                ImageShowBox.Image = image;
            }
        }
        #endregion
    }
}
