namespace MesWork
{
    using DC_A95;
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Threading;
    using System.Windows.Forms;

    /// <summary>
    /// 主窗体 - 称重数据采集分析管理系统
    /// </summary>
    public partial class MesWorkForm
    {
        public static int Curr_AID = 0;

        /// <summary>
        /// 当前活跃的导航Panel
        /// </summary>
        private Panel _activeNavPanel = null;

        public MesWorkForm()
        {
            if (!TryAutoLogin())
            {
                Frm_Login frm_Login = new Frm_Login();
                if (frm_Login.ShowDialog() != DialogResult.OK)
                {
                    Process.GetCurrentProcess().Kill();
                    return;
                }
            }

            OnStart();

            InitializeComponent();
            InsertWeighingAnalysisNav();
            CheckForIllegalCrossThreadCalls = false;
            IsMdiContainer = false;

            // 加载窗口图标
            LoadWindowIcon();

            // 设置用户名
            lbl_UserName.Text = $"操作员：{MesWorkForm.Curr_UserName}";

            // 标题追加工位号
            if (!string.IsNullOrEmpty(Curr_Station))
                Text = $"称重数据采集分析管理系统 - {Curr_Station}";

            // 启动定时器
            timer_OnLine_Show.Interval = 1000;
            timer_OnLine_Show.Enabled = true;
            timer_Clock.Interval = 1000;
            timer_Clock.Enabled = true;

            // 启动SQL在线检测
            CommunicationCheckOnLine();

            // 初始化扫码枪
            if (MesWorkForm.IsUseBarcode == 1)
            {
                BarcodeManager.Init();
                BarcodeManager.OnBarcodeScanned = (opName, barcode) =>
                {
                    // 在线程池中执行业务处理（与PLC信号处理一致）
                    System.Threading.ThreadPool.QueueUserWorkItem(_ =>
                    {
                        try { Barcode_HandleScan(opName, barcode); }
                        catch { }
                    });
                };
            }

            // 默认选中"称重作业"
            SetActiveNav(pnl_NavWeighing);
        }

        private bool TryAutoLogin()
        {
            if (!B_DB_Opera.LoginState_Query(out LoginStateInfo loginState)) return false;

            Curr_LoginID = loginState.LoginID;
            Curr_UserName = loginState.UserName;
            Curr_UserPassWord = "";
            return true;
        }

        // ====================================================================
        // 导航系统
        // ====================================================================

        /// <summary>
        /// 统一导航点击事件
        /// </summary>
        private void Nav_Click(object sender, EventArgs e)
        {
            // 获取真正的导航Panel（可能点的是Label子控件）
            Panel navPanel;
            if (sender is Label lbl)
                navPanel = lbl.Parent as Panel;
            else
                navPanel = sender as Panel;

            if (navPanel == null) return;

            string navTag = navPanel.Tag?.ToString() ?? "";

            // 退出按钮特殊处理
            if (navTag.Contains("退出"))
            {
                DoClose();
                return;
            }

            // PLC监控特殊处理（弹出独立窗口）
            if (navTag.Contains("PLC"))
            {
                new OpcForm(IsDemoMesServer).Show(this);
                return;
            }

            // 日志查询 — 内嵌页面
            if (navTag.Contains("日志"))
            {
                SetActiveNav(navPanel);
                return;
            }

            // 切换选中状态和内容
            SetActiveNav(navPanel);
        }

        /// <summary>
        /// 设置当前选中的导航项，高亮+加载对应内容
        /// </summary>
        private void SetActiveNav(Panel navPanel)
        {
            // 还原之前的选中项
            if (_activeNavPanel != null)
            {
                _activeNavPanel.BackColor = Color.FromArgb(30, 58, 95);
                foreach (Control c in _activeNavPanel.Controls)
                    if (c is Label l) l.ForeColor = Color.FromArgb(148, 163, 184);
            }

            // 高亮新选中项
            _activeNavPanel = navPanel;
            _activeNavPanel.BackColor = Color.FromArgb(42, 74, 111);
            foreach (Control c in _activeNavPanel.Controls)
                if (c is Label l) l.ForeColor = Color.White;

            // 移动Active指示条
            pnl_NavActiveIndicator.Top = navPanel.Top;
            pnl_NavActiveIndicator.Visible = true;

            // 加载对应内容
            LoadContentByNav(navPanel.Tag?.ToString() ?? "");
        }

        /// <summary>
        /// 页面实例缓存（避免重复创建，保持页面状态）
        /// </summary>
        private readonly System.Collections.Generic.Dictionary<string, UserControl> _pageCache
            = new System.Collections.Generic.Dictionary<string, UserControl>();

        /// <summary>
        /// 根据导航Tag加载对应的UserControl
        /// </summary>
        private void LoadContentByNav(string navTag)
        {
            pnl_Content.Controls.Clear();

            string pageKey = "";
            UserControl uc = null;

            if (navTag.Contains("称重分析"))
            {
                pageKey = "weighing_analysis";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_WeighingAnalysis();
            }
            else if (navTag.Contains("称重"))
            {
                pageKey = "weighing";
                if (!_pageCache.ContainsKey(pageKey))
                {
                    var wp = new Pages.UC_Weighing();
                    _pageCache[pageKey] = wp;
                    MesWorkForm.WeighingPage = wp;
                }
            }
            else if (navTag.Contains("用户"))
            {
                pageKey = "user";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_UserMgmt();
            }
            else if (navTag.Contains("工件"))
            {
                pageKey = "workpiece";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_WorkpieceMgmt();
            }
            else if (navTag.Contains("工具"))
            {
                pageKey = "tool";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_ToolMgmt();
            }
            else if (navTag.Contains("报告"))
            {
                pageKey = "report";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_Report();
            }
            else if (navTag.Contains("过站"))
            {
                pageKey = "station";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_StationRecord();
            }
            else if (navTag.Contains("统计"))
            {
                pageKey = "statistics";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_Statistics();
            }
            else if (navTag.Contains("设置"))
            {
                pageKey = "settings";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_SystemSettings();
            }
            else if (navTag.Contains("日志"))
            {
                pageKey = "log";
                if (!_pageCache.ContainsKey(pageKey))
                    _pageCache[pageKey] = new Pages.UC_LogRecord();
            }

            if (!string.IsNullOrEmpty(pageKey) && _pageCache.ContainsKey(pageKey))
            {
                uc = _pageCache[pageKey];
                uc.Dock = DockStyle.Fill;
                pnl_Content.Controls.Add(uc);
            }
        }

        /// <summary>
        /// 在统计分析后插入称重分析入口，减少对设计器文件的手工改动。
        /// </summary>
        private void InsertWeighingAnalysisNav()
        {
            var pnlNav = new Panel
            {
                BackColor = Color.FromArgb(30, 58, 95),
                Cursor = Cursors.Hand,
                Location = new Point(1, 470),
                Name = "pnl_NavWeighingAnalysis",
                Size = new Size(78, 64),
                Tag = "📈\n称重分析"
            };
            var lblNav = new Label
            {
                AutoSize = false,
                Cursor = Cursors.Hand,
                Dock = DockStyle.Fill,
                Font = new Font("微软雅黑", 9F),
                ForeColor = Color.FromArgb(148, 163, 184),
                Text = "📈\n称重分析",
                TextAlign = ContentAlignment.MiddleCenter
            };

            pnlNav.Controls.Add(lblNav);
            pnlNav.Click += Nav_Click;
            lblNav.Click += Nav_Click;

            pnl_NavSettings.Top += 66; // 称重分析占用一个导航位，后续菜单整体下移。
            pnl_NavLog.Top += 66;
            pnl_NavPLC.Top += 66;
            pnl_SidebarScroll.Controls.Add(pnlNav);
            pnlNav.BringToFront();
            pnl_NavActiveIndicator.BringToFront();
        }

        // ====================================================================
        // Timer Events
        // ====================================================================

        /// <summary>
        /// 定时器：SQL在线状态刷新 + PLC信号灯等
        /// </summary>
        private void timer_OnLine_Show_Tick(object sender, EventArgs e)
        {
            // 数据库在线状态指示（只变更指示灯颜色）
            if (OnLine_Sql)
            {
                pnl_SqlIndicator.BackColor = Color.FromArgb(16, 185, 129); // 绿色
            }
            else
            {
                pnl_SqlIndicator.BackColor = Color.FromArgb(239, 68, 68); // 红色
            }
        }

        /// <summary>
        /// 定时器：时钟刷新
        /// </summary>
        private void timer_Clock_Tick(object sender, EventArgs e)
        {
            lbl_DateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        // ====================================================================
        // 窗口事件
        // ====================================================================

        private void MesWorkForm_Load(object sender, EventArgs e)
        {
            // 主界面加载完成
        }

        private void MesWorkForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
        }

        private void DoClose()
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                timer_OnLine_Show.Enabled = false;
                timer_Clock.Enabled = false;
                CloseDeviceConn();
                BarcodeManager.Shutdown();

                B_DB_Opera.SaveLog_Request(Curr_Station, Log_Type.ZK_Login, "", Log_FromAndTo.ZK, Log_FromAndTo.ZK, $"用户[{Curr_UserName}({Curr_LoginID})]退出称重系统", out long AID);
                B_DB_Opera.LoginState_Clear();
                Process.GetCurrentProcess().Kill();
            }
        }

        // ====================================================================
        // 全屏切换
        // ====================================================================

        private void btn_ToggleFullscreen_Click(object sender, EventArgs e)
        {
            if (this.FormBorderStyle == FormBorderStyle.None)
            {
                // 退出全屏 → 恢复普通最大化
                this.FormBorderStyle = FormBorderStyle.Sizable;
                this.WindowState = FormWindowState.Maximized;
                lbl_NavFullscreen.Text = "▣\n全屏";
            }
            else
            {
                // 进入全屏 → 覆盖整个屏幕（含任务栏）
                this.FormBorderStyle = FormBorderStyle.None;
                this.WindowState = FormWindowState.Normal;
                this.Bounds = Screen.PrimaryScreen.Bounds;
                lbl_NavFullscreen.Text = "▣\n窗口";
            }
        }

        // ====================================================================
        // 窗口图标加载
        // ====================================================================

        /// <summary>
        /// 加载窗口图标（多路径搜索 + exe回退）
        /// </summary>
        private void LoadWindowIcon()
        {
            IconHelper.ApplyIcon(this);
        }
    }
}
