using CCDCount.DLL;
using CCDCount.DLL.Tools;
using CCDCount.MODEL.ConfigModel;
using CCDCount.MODEL.ShuLiClass;
using LogClass;
using MvCameraControl;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace CCDCount.Forms
{
    public partial class MainForm : Form
    {
        #region 变量
        //菜单栏状态，true为展开，false为收起
        bool meunStatic = false;
        //当前显示窗体
        Form showFrom = null;
        List<(CameraConfig CameraConfigValue, ShuLiConfigClass ShuLiConfigValue)> Configs =
            new List<(CameraConfig CameraConfigValue, ShuLiConfigClass ShuLiConfigValue)>();
        #endregion

        #region 实例
        //主线程实例队列
        public List<MainThreadClass> LsMainThread = new List<MainThreadClass>();
        public ModbusTcpClient modbusTcpClient = new ModbusTcpClient();

        #endregion

        #region 窗体事件
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            //modbusTcpClient.Connect("192.168.1.88");
            modbusTcpClient.Connect("127.0.0.1");
            if (File.Exists(".\\Config\\CCDCountConfig.xml"))
            {
                Configs = XmlStorage.DeserializeFromXml<List<(CameraConfig CameraConfigValue, ShuLiConfigClass ShuLiConfigValue)>>(".\\Config\\CCDCountConfig.xml");
            }
            SDKSystem.Initialize();
            FormKongjianInit();
            RunAllCameraIdentify();
        }

        /// <summary>
        /// 菜单切换按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuSwitchBtn_Click(object sender, EventArgs e)
        {
            if (meunStatic)
            {
                MenuSwitchBtn.Image = ScaleImage(Properties.Resources.进入__白_, 32, 32);
                HistoryFormBtn.Image = ScaleImage(Properties.Resources.数据_白, 32, 32);
                HistoryFormBtn.Text = "";
                IdentifyFormBtn.Image = ScaleImage(Properties.Resources.相机小_白, 32, 32);
                IdentifyFormBtn.Text = "";
                SettingFromBtn.Image = ScaleImage(Properties.Resources.设置_白, 32, 32);
                SettingFromBtn.Text = "";
                menupanel.Width = 70;
                meunStatic = false;
            }
            else
            {
                MenuSwitchBtn.Image = ScaleImage(Properties.Resources.返回__白_, 32, 32);
                IdentifyFormBtn.Image = null;
                IdentifyFormBtn.Text = "识 别 界 面";
                HistoryFormBtn.Image = null;
                HistoryFormBtn.Text = "数 据 界 面";
                SettingFromBtn.Image = null;
                SettingFromBtn.Text = "参 数 设 置";
                menupanel.Width = 200;
                meunStatic = true;
            }
        }

        /// <summary>
        /// 识别界面按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IdentifyFormBtn_Click(object sender, EventArgs e)
        {
            LoadFormContent(new IdentifyCameraForm(Configs.Select(o=>o.CameraConfigValue).ToList(),LsMainThread));
        }

        private void HistoryFormBtn_Click(object sender, EventArgs e)
        {
            LoadFormContent(new DataShowForm(LsMainThread));
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            LoadFormContent(showFrom);
        }

        // <summary>
        /// 窗体关闭事件
        /// </summary>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SDKSystem.Finalize();
            StopAllCameraIdentify();
            this.Dispose();
            if(showFrom != null) showFrom.Dispose();
            Environment.Exit(0);
        }

        private void SettingFromBtn_Click(object sender, EventArgs e)
        {
            LoadFormContent(new SettingForm(LsMainThread));
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            HistoryFormBtn_Click(this, EventArgs.Empty);
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 图像缩放方法（保持宽高比）
        /// </summary>
        /// <param name="image">图像</param>
        /// <param name="maxWidth">目标宽度</param>
        /// <param name="maxHeight">目标高度</param>
        /// <returns></returns>
        private Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            using (var graphics = Graphics.FromImage(newImage))
            {
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            return newImage;
        }

        /// <summary>
        /// 窗体控件初始化
        /// </summary>
        private void FormKongjianInit()
        {
            IdentifyFormBtn.Image = ScaleImage(Properties.Resources.相机小_白, 32, 32);
            IdentifyFormBtn.Text = "";
            HistoryFormBtn.Image = ScaleImage(Properties.Resources.数据_白, 32, 32);
            HistoryFormBtn.Text = "";
            MenuSwitchBtn.Image = ScaleImage(Properties.Resources.进入__白_, 32, 32);
            menupanel.Width = 70;
            SettingFromBtn.Image = ScaleImage(Properties.Resources.设置_白, 32, 32);
            SettingFromBtn.Text = "";
            //this.FormBorderStyle = FormBorderStyle.None;
            // 全屏显示
            this.WindowState = FormWindowState.Maximized;
            // 窗口置顶
            //this.TopMost = true;
        }

        /// <summary>
        /// 加载目标窗体内容到当前窗体
        /// </summary>
        /// <param name="targetForm">要加载的窗体实例</param>
        private void LoadFormContent(Form targetForm)
        {
            if (targetForm == null)
                return;
            if (showFrom == targetForm) { }
            else if (showFrom != null)
            {
                showFrom.Close();
            }
            showFrom = targetForm;
            targetForm.TopLevel = false; // 关键设置
            targetForm.FormBorderStyle = FormBorderStyle.None;
            targetForm.Dock = DockStyle.Fill; // 新增关键设置
            Mainpanel.Controls.Clear();
            Mainpanel.Controls.Add(targetForm);
            targetForm.Show();
        }

        /// <summary>
        /// 启动所有相机识别
        /// </summary>
        private void RunAllCameraIdentify()
        {
            if(Configs.Count == 0)
            {
                MessageBox.Show("尚未添加相机，请前往配置页面配置相机");
                return;
            }
            foreach (var item in Configs.Select(o => o.ShuLiConfigValue).ToList())
            {
                LsMainThread.Add(new MainThreadClass(item, Configs.Select(o => o.CameraConfigValue).ToList().Where(o=>o.CameraSNNum == item.CameraSN).First()));
            }
            for(int i = 0; i < LsMainThread.Count; i++)
            {
                //判断是否添加线程
                if (!LsMainThread[i].IsOpenLoadThread)
                    return;
                LsMainThread[i].SetModbusClient(modbusTcpClient);
                //启动单相机实例的全部线程
                if(!LsMainThread[i].StartMianThread(Configs.Select(o => o.CameraConfigValue).ToList().Where(o=>o.CameraSNNum == LsMainThread[i].ThisCameraSN).First()))
                {
                    LOG.error(LsMainThread[i].ThisCameraDevice+ "_"+ LsMainThread[i].ThisCameraSN + "启动失败");
                    MessageBox.Show(LsMainThread[i].ThisCameraDevice + "_" + LsMainThread[i].ThisCameraSN + "启动失败");
                    return;
                }
            }
        }

        /// <summary>
        /// 停止所有相机识别
        /// </summary>
        private void StopAllCameraIdentify()
        {
            foreach (var item in LsMainThread)
            {
                item.StopMianThread();
            }
        }

        #endregion
    }
}
