//using RRQMCore.ByteManager;
using ProjectManagementSystem.Device.Function;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManagementSystem.Device.CasunBox
{
    public class BoxCommunicationCom : BoxCommunicationBase
    {
        private SerialPort m_comDevice;
        private BoxDataHandlingAdapterCom m_boxDataHandlingAdapter = new BoxDataHandlingAdapterCom();
        public string ComPortName { get; set; }
        public int ComBaudRate { get; set; }

        public BoxCommunicationCom(string portName, int baudRate)
        {
            ComPortName = portName;
            ComBaudRate = baudRate;

            m_boxDataHandlingAdapter.OnReceived = Received;
        }

        public override void Start()
        {
            if(Init())
            {
                LogMsg($"串口{ComPortName}已打开");
                base.Start();
            }
            else
            {
                LogMsg($"串口{ComPortName}打开失败");
            }
        }

        public override void Stop()
        {
            try
            {
                m_comDevice.DataReceived -= M_comDevice_DataReceived;
                m_comDevice.Close();
                m_comDevice.Dispose();
            }
            catch (Exception ex)
            {
                LogMsg("关闭串口异常", ex);
            }
        }

        public bool Init()
        {
            m_comDevice = new SerialPort
            {
                PortName = ComPortName,
                BaudRate = ComBaudRate,
                Parity = Parity.None,
                DataBits = 8,
                StopBits = StopBits.One,
            };

            try
            {
                m_comDevice.Open();
                m_comDevice.DataReceived += M_comDevice_DataReceived;
                return m_comDevice.IsOpen;
            }
            catch (Exception ex)
            {
                LogMsg("打开串口异常", ex);
            }

            return false;
        }

        private void Received(byte[] data)
        {
            RecivedData(data, d =>
            {
                d.Name = ComPortName;
                LogMsg($"{ComPortName}接收数据: {Tools.Byte2HexString(data)} 校验{d.CheckXOR}");
            });
        }

        private void M_comDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //System.Threading.Thread.Sleep(20);
            byte[] buffer = new byte[m_comDevice.BytesToRead];
            m_comDevice.Read(buffer, 0, buffer.Length);
            m_boxDataHandlingAdapter.PreviewReceivedData(buffer);
        }

        public override void SendCommand(BoxCommandBase command)
        {
            byte[] data = command.Serialization();
            try
            {
                if(!m_comDevice.IsOpen)
                {
                    LogMsg($"{ComPortName}未打开，尝试重新打开...");
                    Stop();
                    Init();
                }

                m_comDevice.Write(data, 0, data.Length);
                LogMsg($"{ComPortName}发送数据: {Tools.Byte2HexString(data)}");
            }
            catch (Exception ex)
            {
                LogMsg($"{ComPortName}发送数据异常: {Tools.Byte2HexString(data)}", ex);
            }
        }
    }
}

