using Microsoft.Extensions.DependencyInjection;
using SlnMesnac.Config;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SlnMesnac.Common
{
    public sealed class GunHelper
    {

        #region 单例实现
        private static readonly GunHelper lazy = new GunHelper();
        public static GunHelper Instance
        {
            get
            {
                return lazy;
            }
        }
        #endregion

        #region 变量定义
        private static SerialPort serialPort = new SerialPort();

        #endregion 

        /// <summary>
        /// 扫码委托
        /// </summary>
        /// <param name="materialCodeStr"></param>
        /// <param name="ip"></param>
        public delegate void RefreshMaterialCodeStr(string code);
        public static event RefreshMaterialCodeStr RefreshMaterialCodeStrEvent;

    

        private DebugConfig config = DebugConfig.Instance;

        //初始化串口并启动接收数据
        public  void InstanceSerialPort()
        {
            try
            {
                //端口名  注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字
                serialPort.PortName = config.Port;// portName;
                                           //波特率 霍尼威尔扫码枪115200,普通9600
                serialPort.BaudRate = 0x2580;
                //奇偶校验
                serialPort.Parity = Parity.None;
                //停止位
                serialPort.StopBits = StopBits.One;
                //数据位
                serialPort.DataBits = 0x8;
                //忽略null字节
                serialPort.DiscardNull = true;

                //接收事件
                serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);

                //开启串口
                serialPort.Open();
               
               
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }

     

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
    
            string result = "";
            int bytesToRead = serialPort.BytesToRead;
            byte[] buf = new byte[bytesToRead];
            serialPort.Read(buf, 0x0, bytesToRead);
           
            for (int i = 0x0; i < buf.Length; i++)
            {
                int num = (int)buf[i];
                result =result+num.ToString("X2");
            }
            Console.WriteLine(result);
        }

        /// <summary>
        /// 发送数据方法
        /// OK-校验成功关闭灯光，NG-校验失败闪烁红灯
        /// </summary>
        /// <param name="data"></param>
        public  void SendData(string data)
        {
            try
            {
                if (serialPort.IsOpen)
                {
                   
                    if (data == "NG")
                    {
                        byte[] buffer = GetBytesByCommand("CloseRed");
                        serialPort.Write(buffer, 0x0, 0x4);
                        byte[] buffer1 = GetBytesByCommand("OpenRed");
                        serialPort.Write(buffer1, 0x0, 0x4);
                    }
                    else if (data == "OK")
                    {
                        byte[] buffer = GetBytesByCommand("CloseRed");
                        serialPort.Write(buffer, 0x0, 0x4);
                        byte[] buffer1 = GetBytesByCommand("OpenGreen");
                        serialPort.Write(buffer1, 0x0, 0x4);
                    }
                    else if(data == "Exit")
                    {
                        byte[] buffer = GetBytesByCommand("CloseRed");
                        serialPort.Write(buffer, 0x0, 0x4);
                    }
                   
                }
                else
                {
                    Console.WriteLine("串口未打开，请先初始化串口并打开连接。");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发送数据时发生错误：{ex.Message}");
            }

        }
      
        /// <summary>
        /// 蜂鸣报警灯常用指令
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        private byte[] GetBytesByCommand(string command)
        {
            byte[] buffer = null;
            switch (command)
            {
                // 打开红灯闪烁+蜂鸣
                 case "OpenRed": buffer = new byte[] { 0xA0, 0x07, 0x02, 0xA9 }; break;
                // 打开红灯闪烁
                //case "OpenRed": buffer = new byte[] { 0xA0, 0x03, 0x02, 0xA5 }; break;
                // 全部关闭
                case "CloseRed": buffer = new byte[] { 0xA0, 0x00, 0x00, 0xA0 }; break;
                
                //// 打开绿灯
                case "OpenGreen": buffer = new byte[] { 0xA0, 0x02, 0x01, 0xA3 }; break;
             
                default:return null;
            }
            return buffer;

        }

    }
}
