using Check.Main.Camera;
using Check.Main.Common;
using Check.Main.Infer;
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;
using WeifenLuo.WinFormsUI.Docking;
namespace Check.Main.UI
{
    public partial class FormControlPanel : DockContent
    {
        private bool _isDeviceReady = false; // 新的状态:设备是否已准备好
        private bool _isDetecting = false;  // 新的状态:是否正在检测中
        // 用于跟踪设备运行状态的私有标志
        private bool _isDeviceRunning = false;
        public FormControlPanel()
        {
            InitializeComponent();
             
            ConfigurationManager.OnConfigurationChanged += HandleConfigurationChanged;
            UpdateUI();
        }
        /// 
        /// 处理全局配置在其他地方(如 FrmConfig)被更改的事件
        /// 
        private void HandleConfigurationChanged()
        {
            // 这是一个安全措施。如果设备正在运行时配置发生了变化,
            // 最安全的做法是停止设备,以防止出现不可预知的行为。
            if (_isDeviceRunning)
            {
                // 使用 Invoke 确保UI更新在正确的线程上执行
                this.Invoke((Action)(() =>
                {
                    ThreadSafeLogger.Log("相机配置已在运行时发生更改,设备将自动停止。请重新启动设备以应用新配置。");
                    //MessageBox.Show("相机配置已在运行时发生更改,设备将自动停止。请重新启动设备以应用新配置。",
                    //                "配置变更", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 触发与点击“关闭设备”按钮相同的逻辑
                    btnStartDevice_Click(this, EventArgs.Empty);
                }));
            }
        }
        //点击“ 启动设备”  按钮
        private void btnStartDevice_Click(object sender, EventArgs e)
        {
            if (_isDeviceReady)//_isDeviceRunning
            {
                // --- 关闭流程 ---
                ThreadSafeLogger.Log("用户点击“关闭设备”,开始完整关闭流程...");
                // 如果正在检测,先停止它
                if (_isDetecting)
                {
                    btnStartCheck_Click(this, EventArgs.Empty); // 调用停止检测的逻辑
                }
                var mainForm = this.DockPanel.FindForm() as FrmMain;
                CameraManager.Shutdown();
                _isDeviceReady = false;
                //// 1. 停止硬触发模拟器
                //CameraManager.StopHardwareTriggerSimulator();
                //// 2. 如果检测正在运行,则停止
                //if (DetectionCoordinator.IsDetectionRunning)
                //{
                //    DetectionCoordinator.StopDetection();
                //    UpdateDetectionButtonUI();
                //}
                // 3. 执行完整的系统关闭(包括相机硬件和检测协调器)
                //CameraManager.Shutdown();
                //YoloModelManager.Shutdown();
                //_isDeviceRunning = false;
            }
            else
            {
                // --- 启动流程 ---
                ThreadSafeLogger.Log("用户点击“启动设备”,开始新的启动流程...");
                // 1. 从单一数据源获取完整的配置对象
                var config = ConfigurationManager.GetCurrentConfig(); 
                // 2. 验证相机配置的有效性
                if (config.CameraSettings == null || !config.CameraSettings.Any(c => c.IsEnabled))
                {
                    ThreadSafeLogger.Log("没有已启用的相机配置,启动中止。");
                    return;
                }
                // 3. 获取主窗体引用
                var mainForm = this.DockPanel.FindForm() as FrmMain;
                if (mainForm == null)
                {
                    ThreadSafeLogger.Log("无法找到主窗体,启动中止。");
                    return;
                }
                // 4. 执行新的启动流程:
                //    第一步:初始化系统。这会准备好相机硬件、UI窗口和所有后台处理线程。
                CameraManager.PrepareAll(config, mainForm);
                _isDeviceReady = true;
                //YoloModelManager.Initialize(config.ModelSettings);
                //CameraManager.Initialize(config, mainForm);
                ////    第二步:命令所有相机开始采集图像。
                //CameraManager.StartAll();
                //// 5. 如果有任何相机配置为软触发模式,我们启动模拟器来模拟触发信号
                //if (config.CameraSettings.Any(c => c.IsEnabled && c.TriggerMode == TriggerModeType.Software))
                //{
                //    ThreadSafeLogger.Log("检测到软触发相机,启动触发模拟器。");
                //    CameraManager.TriggerInterval = 100; // 根据需要设置间隔
                //    CameraManager.StartHardwareTriggerSimulator();
                //}
                //_isDeviceRunning = true;
            }
            UpdateUI();//UpdateDeviceButtonUI();
        }
        //点击 “开始检测” 按钮
        private void btnStartCheck_Click(object sender, EventArgs e)
        {
            if (_isDetecting)
            {
                // --- 停止检测 ---
                ThreadSafeLogger.Log("用户点击“停止检测”,暂停数据流...");
                // 停止硬触发模拟器
                //CameraManager.StopHardwareTriggerSimulator();
                // 停止相机采集
                CameraManager.StopAll();
                // 停止统计
                DetectionCoordinator.StopDetection();
                _isDetecting = false;
            }
            else
            {
                // --- 开始检测 ---
                ThreadSafeLogger.Log("用户点击“开始检测”,启动数据流...");
                // 命令相机开始采集
                CameraManager.StartAll();
                // 启动硬触发模拟器(如果需要)
                var config = ConfigurationManager.GetCurrentConfig();
                if (config.CameraSettings.Any(c => c.IsEnabled && c.TriggerMode == TriggerModeType.Hardware))
                {
                    ThreadSafeLogger.Log("相机设置为硬件触发模式,将由 PLC 输出脉冲信号控制拍照。");
                    //CameraManager.TriggerInterval = 100;
                   // CameraManager.StartHardwareTriggerSimulator();
                }
                // 开始统计
                DetectionCoordinator.StartDetection();
                _isDetecting = true;
            }
            UpdateUI();
            //if (!_isDeviceRunning && !DetectionCoordinator.IsDetectionRunning)
            //{
            //    ThreadSafeLogger.Log("设备未启动,无法开始检测。");
            //    return;
            //}
            //// 现在调用 DetectionCoordinator 中的方法
            //if (DetectionCoordinator.IsDetectionRunning)
            //{
            //    DetectionCoordinator.StopDetection();
            //}
            //else
            //{
            //    DetectionCoordinator.StartDetection();
            //}
            //UpdateDetectionButtonUI();
        }
        #region UI 更新辅助方法
        /// 
        /// 根据设备运行状态更新“设备”按钮的UI(文本和颜色)。
        /// 
        private void UpdateDeviceButtonUI()
        {
            if (_isDeviceRunning)
            {
                btnStartDevice.Text = "关闭设备";
                btnStartDevice.BackColor = Color.Salmon;
            }
            else
            {
                btnStartDevice.Text = "启动设备";
                btnStartDevice.BackColor = SystemColors.Control;
            }
        }
        // 统一的UI更新方法
        private void UpdateUI()
        {
            // --- 更新“设备”按钮 ---
            if (_isDeviceReady)
            {
                btnStartDevice.Text = "关闭设备";
                btnStartDevice.BackColor = Color.Salmon;
                btnStartCheck.Enabled = true; // 设备就绪后,检测按钮才可用
            }
            else
            {
                btnStartDevice.Text = "启动设备";
                btnStartDevice.BackColor = SystemColors.Control;
                btnStartCheck.Enabled = false; // 设备未就绪,检测按钮不可用
            }
            // --- 更新“检测”按钮 ---
            if (_isDetecting)
            {
                btnStartCheck.Text = "停止检测";
                btnStartCheck.BackColor = Color.LightGreen;
                btnStartDevice.Enabled = false; // 正在检测时,不允许关闭设备
            }
            else
            {
                btnStartCheck.Text = "开始检测";
                btnStartCheck.BackColor = SystemColors.Control;
                if (_isDeviceReady) btnStartDevice.Enabled = true; // 停止检测后,允许关闭设备
            }
        }
        /// 
        /// 根据检测运行状态更新“检测”按钮的UI(文本和颜色)。
        /// 
        private void UpdateDetectionButtonUI()
        {
            //if (CameraManager.IsDetectionRunning)
            //{
            //    btnStartCheck.Text = "停止检测";
            //    btnStartCheck.BackColor = Color.LightGreen;
            //}
            //else
            //{
            //    btnStartCheck.Text = "启动检测";
            //    btnStartCheck.BackColor = SystemColors.Control;
            //}
            if (DetectionCoordinator.IsDetectionRunning)
            {
                btnStartCheck.Text = "停止检测";
                btnStartCheck.BackColor = Color.LightGreen;
            }
            else
            {
                btnStartCheck.Text = "启动检测";
                btnStartCheck.BackColor = SystemColors.Control;
            }
        }
        #endregion
    }
}