using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Linq;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto;
using System.Text.Json.Nodes;

namespace SlnMesnac.Business
{
    public class SerialPortBusiness
    {

        private static readonly object _object = new object();

        private SerialPort _serialPort;


        public delegate void RefreshSerialPortDeviceStatus(int isFlag);
        public event RefreshSerialPortDeviceStatus RefreshSerialPortDeviceStatusEvent;

        /// <summary>
        /// 刷新日志内容
        /// </summary>
        public delegate void RefreshLogMessage(string message);
        public event RefreshLogMessage RefreshLogMessageEvent;

        //public delegate void ReceivedMeterConfigInfo(ElectricMeterInfoDto electricMeterInfo, List<ElectricMeterConfigInfo> electricMeterConfigInfos);
        //public event ReceivedMeterConfigInfo ReceivedMeterConfigInfoEvent;

        public delegate void ReceivedBarcodeInfo(string barcodeInfo);
        public static event ReceivedBarcodeInfo? ReceivedBarcodeInfoEvent;

        //public delegate void ReceivedGatewayConfigInfo(GatewayInfoDto gatewayInfoDto);
        //public event ReceivedGatewayConfigInfo ReceivedGatewayConfigInfoEvent;

        /// <summary>
        /// 获取系统内的串口
        /// </summary>
        /// <param name="serialPorts"></param>
        public void GetSerialPorts(out List<string> serialPorts)
        {
            serialPorts = SerialPort.GetPortNames().ToList();
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="serialPort">串口号</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">校验位None = 0,Odd = 1, Even = 2,Mark = 3,Space = 4,</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="stopBits">停止位</param>
        public void OpenSerialPort(string serialPort, int baudRate, int parity, int dataBits, int stopBits)
        {
            if (string.IsNullOrEmpty(serialPort))
            {
                throw new ArgumentException("串口号不能为空");
            }

            _serialPort = new SerialPort(serialPort, baudRate, (System.IO.Ports.Parity)parity, dataBits, (StopBits)stopBits);
            _serialPort.DataReceived += SerialPortDataReceived;
            _serialPort.Open();

            RefreshSerialPortDeviceStatusEvent?.Invoke(1);
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        /// <exception cref="ArgumentException"></exception>
        public void CloseSerialPort()
        {
            if (_serialPort == null)
            {
                throw new ArgumentException("串口实例为空");
            }

            _serialPort.Close();

            RefreshSerialPortDeviceStatusEvent?.Invoke(2);
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="message"></param>
        /// <exception cref="ArgumentException"></exception>
        public void SendMessage(string message)
        {
            try
            {
                if (message == null)
                {
                    throw new ArgumentException("发送内容为空");
                }
                //RefreshLogMessageEvent?.Invoke($"发送指令:{message}");
                if(_serialPort != null && _serialPort.IsOpen)
                {
                    _serialPort.Write(message);
                    RefreshLogMessageEvent?.Invoke("发送成功");
                }
                else
                {
                    RefreshLogMessageEvent?.Invoke("串口未打开，无法发送数据");
                }                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        /// <summary>
        /// 串口数据接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                lock (string.Empty)
                {
                    Thread.Sleep(50);
                    SerialPort sp = (SerialPort)sender;
                    // 读取字节数据
                    int bytesToRead = _serialPort.BytesToRead;
                    byte[] buffer = new byte[bytesToRead];
                    sp.Read(buffer, 0, bytesToRead);
                    string data = System.Text.Encoding.ASCII.GetString(buffer);
                    if (!string.IsNullOrEmpty(data))
                    {
                        RefreshLogMessageEvent?.Invoke("Received data: " + data);
                        ReceivedBarcodeInfoEvent?.Invoke(data);
                        //Analys(data);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("接收数据时发生错误: " + ex.Message);
            }
        }

        ///// <summary>
        ///// 解析数据
        ///// </summary>
        ///// <param name="jsonStr"></param>
        //public void Analys(string jsonStr)
        //{
        //    try
        //    {
        //        if (jsonStr.Contains("OK"))
        //        {
        //            RefreshLogMessageEvent?.Invoke($"修改成功");
        //            return;
        //        }
        //        else if (jsonStr.Contains("Error"))
        //        {
        //            RefreshLogMessageEvent?.Invoke($"修改失败");
        //            return;
        //        }
        //        else if (jsonStr.Contains("MeterSerialNumber")) //电表信息
        //        {

        //            #region 判断JSON格式合法性，获取第一个}为结尾，避免硬件返回多余数据
        //            int lastBraceIndex = jsonStr.IndexOf('}');

        //            if (lastBraceIndex != -1)
        //            {
        //                jsonStr = jsonStr.Substring(0, lastBraceIndex + 1);

        //            }
        //            else
        //            {
        //                RefreshLogMessageEvent?.Invoke($"设备信息指令有误:{jsonStr}");
        //                return;
        //            }
        //            #endregion

        //            RefreshLogMessageEvent?.Invoke($"解析电表设备信息:{jsonStr}");
        //            if (!string.IsNullOrEmpty(jsonStr))
        //            {
        //                var jsonObject = JObject.Parse(jsonStr);

        //                ElectricMeterInfoDto electricMeterInfo = JsonConvert.DeserializeObject<ElectricMeterInfoDto>(jsonObject.ToString());

        //                AnalysMeterConfig(jsonObject, ref electricMeterInfo, out List<ElectricMeterConfigInfo> electricMeterConfigInfos);

        //                ReceivedMeterConfigInfoEvent?.Invoke(electricMeterInfo, electricMeterConfigInfos);
        //            }
        //        }else if (jsonStr.Contains("NaturalGas"))
        //        {
        //            RefreshLogMessageEvent?.Invoke($"解析网关设备信息:{jsonStr}");
        //            GatewayInfoDto gatewayInfo = JsonConvert.DeserializeObject<GatewayInfoDto>(jsonStr);
        //            ReceivedGatewayConfigInfoEvent?.Invoke(gatewayInfo);
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        RefreshLogMessageEvent?.Invoke($"解析逻辑异常:{ex.Message};原始数据:{jsonStr}");
        //    }
        //}

        ///// <summary>
        ///// 解析子表配置信息
        ///// </summary>
        ///// <param name="jsonObject"></param>
        ///// <param name="electricMeterInfo"></param>
        ///// <param name="electricMeterConfigInfos"></param>
        //private void AnalysMeterConfig(JObject jsonObject, ref ElectricMeterInfoDto electricMeterInfo, out List<ElectricMeterConfigInfo> electricMeterConfigInfos)
        //{
        //    electricMeterConfigInfos = new List<ElectricMeterConfigInfo>();
        //    foreach (var property in jsonObject.Properties())
        //    {
        //        if (electricMeterInfo.GetType().GetProperty(property.Name) == null)
        //        {
        //            string proValue = property.Value.ToObject<string>();
        //            string[] proValueArray = proValue.Split(",");

        //            if (proValueArray.Length == 4)
        //            {
        //                ElectricMeterConfigInfo electricMeterConfigInfo = new ElectricMeterConfigInfo();
        //                electricMeterConfigInfo.PointName = property.Name;
        //                electricMeterConfigInfo.InitialAddress = proValueArray[0];
        //                electricMeterConfigInfo.Length = Convert.ToInt32(proValueArray[1]);
        //                electricMeterConfigInfo.Rate = proValueArray[2];
        //                electricMeterConfigInfo.DataType = Convert.ToInt32(proValueArray[3]);
        //                electricMeterConfigInfos.Add(electricMeterConfigInfo);
        //            }
        //        }
        //    }
        //}
    }
}
