using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PrintBarCode.Business;
using PrintBarCode.Helper;
using PrintBarCode.Model;
using ServiceStack;
using ServiceStack.Messaging;
using SlnMesnac.Common;
using SlnMesnac.Model.domain;
using SlnMesnac.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrintBarCode
{
    public  class MessageClient
    {
        private readonly RedisHandler _redisHandler;
        private  PrintBusiness printBusiness = new PrintBusiness();
        private readonly DebugConfig debugConfig = DebugConfig.Instance;

        public   delegate  void  addLog(string message);
        public static event addLog? addLogEvent;

        /// <summary>
        /// 刷新日志信息
        /// </summary>
        /// <param name="msg"></param>
        public delegate void PrintMessageToListBox(string msg);
        public event PrintMessageToListBox? PrintMessageToListBoxEvent;



        public MessageClient(RedisHandler redisHandler)
        {
            _redisHandler = redisHandler;
         
            string ip = NetworkHelper.GetFirstLocalIPv4Address();
            debugConfig.IP = ip;

        }

        public void StartListening()
        {
            Console.WriteLine($"启动打印监听服务~~~");
            Listening();



            // 订阅当前工位的频道
            _redisHandler.SubscribeToChannel($"print_{debugConfig.IP}", OnMessageReceivedByWorkId);
            Console.WriteLine($"订阅工位 ===》print_{debugConfig.IP}  成功");
            // 订阅当前工位的频道
           
            // 开始处理队列中的未消费消息
            // ProcessMessageQueue();
            // _redisHandler.SubscribeToChannel("read_messages", OnMessageReceived);
        }

        private async void OnMessageReceivedByWorkId(string channelWork, string messageId)
        {
            try
            {

                var message =  _redisHandler.ConsumeMessageFromWorker(debugConfig.IP);
                if (!string.IsNullOrEmpty(message))
                {
                    
                    Console.WriteLine($"消息: {message}");
                }
            }
            catch (Exception ex)
            {
               Console.WriteLine("处理消息时发生错误");
            }
        }

        private void Listening()
        {
            int IsPrintBlank = 0;
            Task.Run(() =>
            {
                Thread.Sleep(1000 * 2);
                while (true)
                {
                    try
                    {
                        string channelWork = $"print_{debugConfig.IP}";
                        string jsonString = _redisHandler.ConsumeMessageFromWorker(channelWork);
                        //  string jsonString = "{\"template\":\"small\",\"printContent\":\"[{\\\"text\\\":\\\"test\\\",\\\"qrcode\\\":\\\"12001\\\"}]\"}";
                       // string jsonString = "{\"template\":\"raw\",\"printContent\":\"[{\\\"saleOrderCode\\\":\\\"\\\",\\\"materialName\\\":\\\"Mater\\\",\\\"poNo\\\":\\\"CGDD000236\\\",\\\"qrcode\\\":\\\"20241105161452RB001\\\",\\\"batchCode\\\":\\\"D20241105PCGDD000236\\\",\\\"materialSpec\\\":\\\"\\\",\\\"materialCode\\\":\\\"MES.MC.A00044\\\",\\\"barcode\\\":\\\"20241105161452RB001\\\"}]\"}";
                        if (!string.IsNullOrEmpty(jsonString))
                        {
                            IsPrintBlank = 1;
                            var result = JsonParser.ParseJson(jsonString);
                            if (result != null)
                            {
                                foreach (var item in result)
                                {
                                    if (item is RawBarCodeInfo rawBarCodeInfo)
                                    {
                                        addLogEvent?.Invoke(rawBarCodeInfo.ToJson());
                                        printBusiness.PrintRawBarCodeInfo(rawBarCodeInfo);
                                    }
                                    else if (item is ProductBarCodeInfo productBarCodeInfo)
                                    {
                                        addLogEvent?.Invoke(productBarCodeInfo.ToJson());
                                        printBusiness.PrintProductBarCodeInfo(productBarCodeInfo);
                                    }else if (item is BindBarCodeInfo bindBarCodeInfo)
                                    {
                                        addLogEvent?.Invoke(bindBarCodeInfo.ToJson());
                                        printBusiness.PrintBindBarCodeInfo(bindBarCodeInfo);
                                    }else if(item is SmallCodeInfo smallCodeInfo)
                                    {
                                        addLogEvent?.Invoke(smallCodeInfo.ToJson());
                                        printBusiness.PrintSmallBarCodeInfo(smallCodeInfo);
                                    }
                                    Thread.Sleep(1000);
                                }
                            }
                        }
                        else
                        {
                            if(IsPrintBlank == 1 && debugConfig.BlankFlag=="1")
                            {
                                printBusiness.PrintBlankPage();
                                IsPrintBlank = 0;
                            }
                        }
                        Thread.Sleep(1000 * 1);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("处理消息时发生错误");
                        IsPrintBlank = 0;
                    }
                }
            });
        }

    

   

    }
}
