#region << 版 本 注 释 >>

/*--------------------------------------------------------------------
* 版权所有 (c) 2026 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：Mr.Wen's MacBook Pro
* 命名空间：Sln.IntelliBelt.Business
* 唯一标识：35A6CB22-720D-4A7D-91D7-FF4D8A71B2A5
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2026-04-24 16:08:18
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/

#endregion << 版 本 注 释 >>

using Sln.IntelliBelt.Business.@base;
using Sln.IntelliBelt.Common;
using Sln.IntelliBelt.Config;
using Sln.IntelliBelt.Serilog;
using Sln.IntelliBelt.Socket.Adapter;
using Sln.IntelliBelt.WebSocket;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace Sln.IntelliBelt.Business;

public class ReaderStatusHandler:BaseBusiness
{
    public ReaderStatusHandler(SerilogHelper logger, AppConfig appConfig, StringChange stringChange,WebSocketHelper webSocket) : base(logger, appConfig, stringChange,webSocket)
    {
    }

    public override void BufferAnalysis(TcpSessionClient client, BufferRequestInfo requestInfo, long bodyLength)
    {
        _logger.Info($"{client.Id}链接收到终端{requestInfo.terminalAddr}上报的状态信息：{requestInfo.content}");

        try
        {
            for (int i = 0; i < requestInfo.contentLen; i++)
            {
                int res = (int)requestInfo.body[i];
                _logger.Info($"{i + 1}#读写器状态:{(res == 1 ? "在线" : "离线")}");
            }
            base.GetJsonStr(client.Id, requestInfo,out string jsonStr);
            _webSocket.PushMsg(jsonStr);

            if (client.Id != _appConfig.terminalCode)
            {
                _logger.Info($"更新连接 Id:{client.Id}==>{_appConfig.terminalCode}");
                client.ResetIdAsync(_appConfig.terminalCode).Wait();
            }
            
            //this.ResponseHandle(client, requestInfo);
        }
        catch (Exception e)
        {
            _logger.Info($"终端状态信息处理异常");
        }
    }

    public override void ResponseHandle(TcpSessionClient client, BufferRequestInfo requestInfo)
    {
        //throw new NotImplementedException();
        ResponsePack responsePack = new ResponsePack()
        {
            terminalAddr = _stringChange.HexStrTorbytes(requestInfo.terminalAddr),
            identCode = Convert.ToByte(requestInfo.identCode),
            contentLen = 0x01,
            content = new byte[] { 0x01 }
        };

        var messagePack = base.GetMessagePack(ref responsePack);
        _logger.Info($"返回终端状态信息:{_stringChange.bytesToHexStr(messagePack,messagePack.Length)}");
        
        client.SendAsync(messagePack);
    }
}