#region << 版 本 注 释 >>

/*--------------------------------------------------------------------
* 版权所有 (c) 2026 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：Mr.Wen's MacBook Pro
* 命名空间：Sln.IntelliBelt.Business
* 唯一标识：7202420B-69F4-4CF0-B5BE-045D8F4EE1F5
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2026-04-25 10:37:44
* 版本：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.Core;
using TouchSocket.Sockets;

namespace Sln.IntelliBelt.Business;

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

    /// <summary>
    /// 服务端下发控制指令，入参：终端地址、对象类别、指令
    /// </summary>
    /// <param name="msg"></param>
    public async void SendSetBuffer(ReaderCommand readerCommand)
    {
        
        try
        {
            byte[] terminalAddrBytes = _stringChange.HexStrTorbytes(readerCommand.terminalAddr);
            byte objType = Convert.ToByte(readerCommand.objType);
            byte[] contentBytes = _stringChange.HexStrTorbytes(readerCommand.content);

            ResponsePack responsePack = new ResponsePack()
            {
                terminalAddr = terminalAddrBytes,
                identCode = 0x32,
                objType = objType,
                contentLen = Convert.ToByte(contentBytes.Length),
                content = contentBytes,
            };

            var messagePack = base.GetMessagePack(ref responsePack);

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

            base.GetObjectTypeStr(requestInfo.objType, out string objTypeStr);

            //控制指令码
            List<byte> setByteLists = new List<byte>()
            {
                0x42,   //功率设置
                0x53,   //蜂鸣器设置
                0xBF,   //心跳设置
                0x5F    //保存设置
            };

            if (setByteLists.Contains(requestInfo.body[3]))
            {
                if (requestInfo.body[4] == 0x00)
                {
                    _logger.Info($"{objTypeStr}设置：{(requestInfo.body[4] == 0x00 ? "成功" : "失败")}");
                    readerCommand.content = requestInfo.body[4] == 0x00 ? "成功" : "失败";
                }
            }
            else
            {
                readerCommand.content = _stringChange.bytesToHexStr(requestInfo.body,requestInfo.body.Length);

                if (requestInfo.body[3] == 0x72)    //获取读写器功率
                {
                    _readerBufferHandler.ReaderPowerAnalysis(requestInfo,ref readerCommand);
                }else if (requestInfo.body[3] == 0x70)  //固件版本号
                {
                    _readerBufferHandler.ReaderVersionAnalysis(requestInfo,ref readerCommand);
                }else if (requestInfo.body[3] == 0x90)  //设备温度
                {
                    _readerBufferHandler.ReaderTempAnalysis(requestInfo,ref readerCommand);
                }
            }
            
            
        }
        catch (Exception e)
        {
            _logger.Info($"设置指令下发异常：{e.Message}");
            
            readerCommand.content = $"下发异常:{e.Message}";
        }
        
        _webSocket.PushMsg(JsonConvert.SerializeObject(readerCommand,Formatting.Indented));
    }

    public override void BufferAnalysis(TcpSessionClient client, BufferRequestInfo requestInfo, long bodyLength)
    {
        try
        {
            _logger.Info($"{client.Id}链接收到终端{requestInfo.terminalAddr}返回的设置信息：{requestInfo.content}");

            if ((int)requestInfo.body[0] == 1)
            {
                base.GetObjectTypeStr(requestInfo.objType, out string objTypeStr);
                _logger.Info($"{objTypeStr}设置：{(requestInfo.content == "01" ? "成功" : "失败")}");
            }
        }
        catch (Exception e)
        {
            throw new InvalidOperationException($"终端设置返回信息处理异常:{e.Message}");
        }
    }

    public override void ResponseHandle(TcpSessionClient client, BufferRequestInfo requestInfo)
    {
        
    }
}