#region << 版 本 注 释 >>

/*--------------------------------------------------------------------
* 版权所有 (c) 2026 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：Mr.Wen's MacBook Pro
* 命名空间：Sln.IntelliBelt.Business
* 唯一标识：C4882642-153C-4A66-9D71-9753ACA8EB03
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2026-04-26 11:03:35
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/

#endregion << 版 本 注 释 >>

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sln.IntelliBelt.Business.@base;
using Sln.IntelliBelt.Common;
using Sln.IntelliBelt.Config;
using Sln.IntelliBelt.Model;
using Sln.IntelliBelt.Serilog;
using Sln.IntelliBelt.Socket;
using Sln.IntelliBelt.Socket.Adapter;
using Sln.IntelliBelt.WebSocket;
using TouchSocket.Sockets;

namespace Sln.IntelliBelt.Business;

public class ReaderBufferHandler:BaseBusiness
{
    private readonly TcpServer _tcpServer;
    
    public ReaderBufferHandler(SerilogHelper logger, AppConfig appConfig, StringChange stringChange, WebSocketHelper webSocket, TcpServer tcpServer) : base(logger, appConfig, stringChange, webSocket)
    {
        _tcpServer = tcpServer;
    }

    public override void BufferAnalysis(TcpSessionClient client, BufferRequestInfo requestInfo, long bodyLength)
    {
        base.GetObjectTypeStr(requestInfo.objType,out string objTypeStr);
        _logger.Info($"{client.Id}链接收到终端{requestInfo.terminalAddr}上报的{objTypeStr}数据：{requestInfo.content}");
        base.GetJsonStr(client.Id,requestInfo,out string jsonStr);
        _webSocket.PushMsg(jsonStr);
    }

    public override void ResponseHandle(TcpSessionClient client, BufferRequestInfo requestInfo)
    {
        //throw new NotImplementedException();
    }
    
    /// <summary>
    /// 监控平台启动时获取设备参数信息
    /// </summary>
    /// <param name="msg"></param>
    public void GetReaderParams(ReaderCommand readerCommand)
    {
        try
        {
            byte[] terminalAddrBytes = _stringChange.HexStrTorbytes(readerCommand.terminalAddr);
            byte objType = Convert.ToByte(readerCommand.objType);

            List<byte[]> buffers = new List<byte[]>()
            {
                new byte[] { 0xAA, 0x55, 0x01, 0x70, 0x02,0x73, 0x0D }, //固件版本
                new Byte[] {0xAA,0x55,0x00,0x72,0x72,0x0D}, //功率
                new byte[] {0xAA,0x55,0x00,0x90,0x90,0x0D}  //温度
            };

            buffers.ForEach(x =>
            {
                BufferRequestInfo info = GetReaderParam(readerCommand.clientId, terminalAddrBytes,objType,x).Result;

                if (info.body.Length > 3)
                {
                    if (info.body[3] == 0x70)
                    {
                        this.ReaderVersionAnalysis(info,ref readerCommand);
                    }else if (info.body[3] == 0x72)
                    {
                        this.ReaderPowerAnalysis(info,ref readerCommand);
                    }else if (info.body[3] == 0x90)
                    {
                        this.ReaderTempAnalysis(info,ref readerCommand);
                    }
                }
                
                Thread.Sleep(1000);
            
            });

            readerCommand.content = $"获取设备参数成功";
        }
        catch (Exception e)
        {
            _logger.Info($"获取设备参数异常：{e.Message}");
            
            readerCommand.content  = $"获取设备参数异常:{e.Message}";
        }

        _webSocket.PushMsg(JsonConvert.SerializeObject(readerCommand,Formatting.Indented));
    }
    
    public async Task<BufferRequestInfo> GetReaderParam(string clientId,byte[] terminalAddrBytes,byte objType,byte[] buffer)
    {
        
        try
        {
            ResponsePack responsePack = new ResponsePack()
            {
                terminalAddr = terminalAddrBytes,
                identCode = 0x32,
                objType = objType,
                contentLen = (byte)buffer.Length,
                content = buffer
            };

            var messagePack = base.GetMessagePack(ref responsePack);

            var requestInfo = await _tcpServer.SendMsgToClient(clientId, messagePack);

            if (requestInfo == null)
            {
                throw new ArgumentNullException($"requestInfo为空");
            }

            return requestInfo;
        }
        catch (Exception e)
        {
            throw new InvalidOperationException($"{e.Message}");
        }
    }
    
    /// <summary>
    /// 天线功率解析
    /// </summary>
    /// <param name="requestInfo"></param>
    /// <param name="jsonStr"></param>
    public void ReaderPowerAnalysis(BufferRequestInfo requestInfo,ref ReaderCommand readerCommand)
    {
        int len = Convert.ToInt32(requestInfo.body[2]);

        var buffers = requestInfo.body.Skip(5).Take(len).ToArray();
        readerCommand.paramInfo.antPowers = new List<AntPowerInfo>();
        for (int i = 0; i < len; i=i+5)
        {
            AntPowerInfo antPowerInfo = new AntPowerInfo();
            var buf = buffers.Skip(i).Take(5).ToArray();
            antPowerInfo.ant = buf[0];
            byte[] readPowerBytes = buf.Skip(1).Take(2).ToArray();
            antPowerInfo.readPower= Convert.ToInt32(_stringChange.bytesToHexStr(readPowerBytes,readPowerBytes.Length), 16) / 100;
                    
            byte[] writePowerBytes = buf.Skip(3).Take(2).ToArray();
            antPowerInfo.writePower= Convert.ToInt32(_stringChange.bytesToHexStr(writePowerBytes,writePowerBytes.Length), 16)  / 100;
                        
            _logger.Info($"{antPowerInfo.ant}#天线,读取功率:{antPowerInfo.readPower};写入功率:{antPowerInfo.writePower}");
                        
            readerCommand.paramInfo.antPowers.Add(antPowerInfo);
        }
    }

    /// <summary>
    /// 固件版本解析
    /// </summary>
    /// <param name="requestInfo"></param>
    /// <param name="jsonStr"></param>
    public void ReaderVersionAnalysis(BufferRequestInfo requestInfo,ref ReaderCommand readerCommand)
    {
        int bobyLen = requestInfo.body[2];
        
        var buffer = requestInfo.body.Skip(5).Take(bobyLen).ToArray();

        readerCommand.paramInfo.readerVersion = _stringChange.ToAsciiString(buffer);
    }
    
    /// <summary>
    /// 设备温度解析
    /// </summary>
    /// <param name="requestInfo"></param>
    /// <param name="jsonStr"></param>
    public void ReaderTempAnalysis(BufferRequestInfo requestInfo,ref ReaderCommand readerCommand)
    {
        readerCommand.paramInfo.readerTemp= requestInfo.body[5];
        _logger.Info($"设备温度:{readerCommand.paramInfo.readerTemp}");
    }
}