using Fleck;
using Newtonsoft.Json.Linq;
using SlnMesnac.Model.dto;
using SlnMesnac.Plc;
using SlnMesnac.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：T14-GEN3-7895
* 命名空间：SlnMesnac.Business
* 唯一标识：2a743b18-b6e9-499e-87b5-15ad4a2041b6
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2024-12-04 9:10:44
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Business
{
    public class WebSocketBusiness
    {
        private List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();

        private readonly RealTemperatureInfo _realTemperatureInfo;

        public readonly PlcAbsractFactory _plc;

        public WebSocketBusiness(RealTemperatureInfo realTemperatureInfo, PlcAbsractFactory plc)
        {
            _plc = plc;
            _realTemperatureInfo = realTemperatureInfo;

            this.Init();
        }

        public void Encapsulation(bool isAlarm ,base_alarm_info alarmInfo,record_busbar_alarm busbarAlarm,int source = 1)
        {
            if(_realTemperatureInfo != null)
            {
                JObject jsonObject = new JObject
                {
                    ["Uuid"] = System.Guid.NewGuid().ToString(),
                    ["DeviceInfo"] = new JObject
                    {
                        ["deviceStatus"] = _plc.readInt32ByAddress("VD1508"),
                        ["runSpeed"] = _plc.readFloatByAddress("VD2022"),
                        ["liftStatus"] = 1,
                        ["cabinetCode"] = _plc.readInt32ByAddress("VD1100"),
                        ["realAddr"] = string.Empty,
                    },
                    ["TemParam"] = new JObject
                    {
                        ["tempMax"] = _realTemperatureInfo.fMaxTemperature,
                        ["tempMin"] = _realTemperatureInfo.fMinTemperature,
                        ["tempAvg"] = _realTemperatureInfo.fAverageTemperature,
                        ["tempDiff"] = _realTemperatureInfo.fTemperatureDiff
                    },
                    ["AlarmInfo"] = new JObject
                    {
                        ["isAlarm"] = isAlarm ? 1 : 0,
                        ["alarmAddr"] = busbarAlarm != null ? busbarAlarm.cabinetCode : null,
                        ["alarmType"] = alarmInfo != null ? alarmInfo.alarmType : null,
                        ["alarmAlias"] = alarmInfo != null ? alarmInfo.alarmAlias : null,
                        ["alarmContent"] = alarmInfo != null ? alarmInfo.alarmContent : null,
                        ["alarmSource"] = source,
                        ["isFlag"] = 0,
                        ["alarmTime"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                    }
                };

                // 将 JObject 转换为 JSON 字符串
                string jsonString = jsonObject.ToString();

                this.sendMessage(jsonString);
            }
        }

        public void Init()
        {
            var server = new Fleck.WebSocketServer($"ws://0.0.0.0:7181");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    var data = socket.ConnectionInfo;
                    Console.WriteLine("WebSocket Open!");
                    allSockets.Add(socket);
                };

                socket.OnClose = () =>
                {
                    Console.WriteLine("WebSocket Close!");
                    allSockets.Remove(socket);
                };

                socket.OnMessage = message =>
                {
                    //ReceivedMessageRequestInfoEvent?.Invoke(socket, message);
                };
            });
        }

        public void sendMessage(string message)
        {
            try
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(message);
                    Console.WriteLine("WebSocket接口上传数据:" + message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("WebSocket上传数据异常", ex);
            }
        }
    }
}
