using System;
using System.Collections.Generic;
using System.Linq;

namespace MesWork
{
    /// <summary>
    /// 扫码枪管理器 — 管理最多2把扫码枪的生命周期和事件分发
    /// </summary>
    public static class BarcodeManager
    {
        /// <summary>
        /// 扫码枪实例字典，key = opName
        /// </summary>
        public static Dictionary<string, BarcodeScanner> Scanners { get; } = new Dictionary<string, BarcodeScanner>(StringComparer.OrdinalIgnoreCase);

        /// <summary>
        /// 是否启用扫码枪功能
        /// </summary>
        public static bool IsEnabled => MesWorkForm.IsUseBarcode == 1;

        /// <summary>
        /// 扫码事件回调（由外部设置，通常指向 MIS_Funtion 的处理方法）
        /// </summary>
        public static Action<string, string> OnBarcodeScanned;

        /// <summary>
        /// 初始化扫码枪（读取配置并创建实例）
        /// </summary>
        public static void Init()
        {
            if (!IsEnabled) return;

            int baudRate = MesWorkForm.BarcodeBaudRate;

            InitScanner(MesWorkForm.Station1OpName, MesWorkForm.Station1BarCOM, baudRate);
            InitScanner(MesWorkForm.Station2OpName, MesWorkForm.Station2BarCOM, baudRate);
        }

        private static void InitScanner(string opName, string comPort, int baudRate)
        {
            opName = opName?.Trim();
            comPort = comPort?.Trim();
            if (string.IsNullOrEmpty(opName) || string.IsNullOrEmpty(comPort))
            {
                return;
            }

            var scanner = new BarcodeScanner(opName, baudRate);
            scanner.BarcodeReceived += HandleBarcodeReceived;
            scanner.Log += HandleLog;
            Scanners[opName] = scanner;
            scanner.Connect(comPort);
        }

        /// <summary>
        /// 统一扫码事件处理
        /// </summary>
        private static void HandleBarcodeReceived(string opName, string barcode)
        {
            OnBarcodeScanned?.Invoke(opName, barcode);
        }

        /// <summary>
        /// 扫码枪日志 → 系统日志 + 称重页面
        /// </summary>
        private static void HandleLog(string message)
        {
            MesWorkForm.WriteLog_Info("BarcodeScanner", message);
            MesWorkForm.WeighingPage?.AppendLog(message);
        }

        /// <summary>
        /// 手动发送条码（模拟扫码触发）
        /// </summary>
        public static void ManualSend(string opName, string barcode)
        {
            // 直接走事件回调，和自动扫码一样的路径
            if (!string.IsNullOrWhiteSpace(barcode))
                HandleBarcodeReceived(opName, barcode.Trim());
        }

        /// <summary>
        /// 释放所有扫码枪
        /// </summary>
        public static void Shutdown()
        {
            foreach (var scanner in Scanners.Values)
            {
                try { scanner.Dispose(); } catch { }
            }
            Scanners.Clear();
        }

        /// <summary>
        /// 获取所有可用COM口
        /// </summary>
        public static string[] GetAvailablePorts()
        {
            try { return System.IO.Ports.SerialPort.GetPortNames(); }
            catch { return new string[0]; }
        }
    }
}
