using BPASmartClient.EventBus;
using BPASmartClient.Helper;
using BPASmartClient.KLMCoffee.Protocal;
using BPASmartClient.Message;
using BPASmartClient.Model;
using BPASmartClient.Model.咖啡机.Enum;
using BPASmartClient.Peripheral;
using BPASmartClient.SerialPort;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static BPASmartClient.EventBus.EventBus;

namespace BPASmartClient.KLMCoffee
{
    /// <summary>
    /// 伽乐美咖啡机
    /// </summary>
    public class CoffeeMachine :BasePeripheral
    {
        //通讯代理
        SerialPortClient commProxy = null;
        //数据仓库
        private DataStorage<byte> dataStorage = new DataStorage<byte>();
        //是否下发指令，主线程等待
        private bool free = false;
        //状态询问指令
        private byte[] cmdAsk;
        //串口COM口
        public string PortName { get; set; }
        //串口波特率
        public string BaudRate { get; set; }
        //心跳时间
        private DateTime lastRefreshTime = DateTime.MinValue;
        //是否在线
        public bool OnLine { get { return DateTime.Now.Subtract(lastRefreshTime).TotalSeconds <= 3; } }
        //命令
        public K95Command command = new K95Command();

        public CoffeeMachine()
        {
            cmdAsk = new K95Command().ReturnsStatusInquire();
        }

        /// <summary>
        /// 主线程开始运行
        /// </summary>
        public override void Start()
        {
            try
            {
                commProxy.Start();
                IsConnected = true;
                free = false;
                MainLoop();
            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
            }
        }

        /// <summary>
        /// 停止运行
        /// </summary>
        public override void Stop()
        {
            try
            {
                commProxy.Stop();
                IsConnected = false;
                free = true;
            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
            }
        }

        /// <summary>
        /// 主循环，循环询问状态
        /// </summary>
        private void MainLoop()
        {
            ThreadManage.GetInstance().StartLong(new Action(() =>
            {
                if (!free)
                {
                    commProxy.SendData(cmdAsk);
                }
                Thread.Sleep(200);
            }),"咖啡机询问线程");

            ThreadManage.GetInstance().StartLong(new Action(() =>
            {
                ResolveMsg();
            }),"咖啡机解析线程");
        }

        private void ResolveMsg()
        {
            List<byte> temp = new List<byte>();
            //一系列解包
            while (dataStorage.GetSize() > 0)
            {
                byte item = dataStorage.GetData();
                List<byte> data = new List<byte>() { item };
                if (Encoding.ASCII.GetString(data.ToArray()) == ":")
                {
                    temp.Add(item);
                    while (dataStorage.GetSize() < 32) { Thread.Sleep(5); }

                    while (temp.Count < 32)
                    {
                        temp.Add(dataStorage.GetData());
                    }
                    List<byte> vs = new List<byte>() { temp[temp.Count - 4],temp[temp.Count - 3],temp[temp.Count - 2],temp[temp.Count - 1] };

                    //帧尾
                    if (Encoding.ASCII.GetString(vs.ToArray()).ToLower() == "\\r\\n" || Encoding.ASCII.GetString(vs.ToArray()).ToLower() == "\r\n")
                    {
                        var package = Encoding.ASCII.GetString(temp.ToArray());
                        ProcessMsg(package);
                    }
                    temp.Clear();
                }
                continue;
            }
            Thread.Sleep(5);
        }

        public void ProcessMsg(string data)
        {
            try
            {
                SystemStatusModel systemStatus = new K95Command().StateResolution(data);
                if (systemStatus != null)
                {
                    status["Status"] = systemStatus.temStatus;
                    status["drinkType"] = systemStatus.drinkType;
                    status["AppStatus"] = systemStatus.taskIndex;
                    status["progress"] = systemStatus.progress;
                    status["Warning"] = systemStatus.faultMessage.dataFault();
                    status["Keep"] = systemStatus.upkeepMessage;
                    if (systemStatus.faultMessage.IsFault() || systemStatus.upkeepMessage.IsUpkeep())
                        IsWork=false;
                    else
                        IsWork=true;    
                }

            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
            }
        }

        protected override void InitStatus()
        {
            status["Status"] = K95SysTemStatus.空闲状态;
            status["drinkType"] = DrinkType.意式;
            status["AppStatus"] = TaskIndex.无任务;
            status["progress"] = 0;
            status["Warning"] = new FaultMessage(0x00,0x00).dataFault();
            status["Keep"] = new UpkeepMessage(0x00).dataFault();

        }

        public override void Init()
        {
            commProxy = new SerialPortClient(PortName,(BaudRates)Enum.Parse(typeof(BaudRates),BaudRate));
            commProxy.SetDataStorage(dataStorage);

            //伽乐美咖啡机制作
            EventBus.EventBus.GetInstance().Subscribe<KLMCoffee_MakeCoffeeEvent>(DeviceId,delegate (IEvent @event,EventCallBackHandle callBack)
            {
                try
                {
                    free = true;
                    Thread.Sleep(200);
                    byte[] data=command.ReturnsCommandData(K95CommandEnum.配方咖啡制作.GetString(),new RecipeModel().Packe(((KLMCoffee_MakeCoffeeEvent)@event).DrinkCode));
                    commProxy.SendData(data);
                    Thread.Sleep(200);
                    free = false;
                }
                catch (Exception ex)
                {
                    MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
                }
            });

            //伽乐美咖啡机取消制作咖啡
            EventBus.EventBus.GetInstance().Subscribe<KLMCoffee_CancelMakeCoffeeEvent>(DeviceId,delegate (IEvent @event,EventCallBackHandle callBack)
            {
                try
                {
                    free = true;
                    Thread.Sleep(200);
                    byte[] data = command.ReturnsCancelMake();
                    commProxy.SendData(data);
                    Thread.Sleep(200);
                    free = false;
                }
                catch (Exception ex)
                {
                    MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
                }
            });

            //伽乐美咖啡机清洗冲泡器
            EventBus.EventBus.GetInstance().Subscribe<KLMCoffee_WashCPJEvent>(DeviceId,delegate (IEvent @event,EventCallBackHandle callBack)
            {
                try
                {
                    free = true;
                    Thread.Sleep(200);
                    byte[] data = command.ReturnsWashCPJ();
                    commProxy.SendData(data);
                    Thread.Sleep(200);
                    free = false;
                }
                catch (Exception ex)
                {
                    MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
                }
            });

            //伽乐美咖啡机放杯确认
            EventBus.EventBus.GetInstance().Subscribe<KLMCoffee_CupIsOKEvent>(DeviceId,delegate (IEvent @event,EventCallBackHandle callBack)
            {
                try
                {
                    free = true;
                    Thread.Sleep(200);
                    byte[] data = command.ReturnsCupIsOK();
                    commProxy.SendData(data);
                    Thread.Sleep(200);
                    free = false;
                }
                catch (Exception ex)
                {
                    MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
                }
            });


            //伽乐美咖啡机清洗奶沫器
            EventBus.EventBus.GetInstance().Subscribe<KLMCoffee_WashNMJEvent>(DeviceId,delegate (IEvent @event,EventCallBackHandle callBack)
            {
                try
                {
                    free = true;
                    Thread.Sleep(200);
                    byte[] data = command.ReturnsWashNMJ();
                    commProxy.SendData(data);
                    Thread.Sleep(200);
                    free = false;
                }
                catch (Exception ex)
                {
                    MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
                }
            });


            //伽乐美咖啡机清洗奶沫器确认
            EventBus.EventBus.GetInstance().Subscribe<KLMCoffee_WashNMJIsOKEvent>(DeviceId,delegate (IEvent @event,EventCallBackHandle callBack)
            {
                try
                {
                    free = true;
                    Thread.Sleep(200);
                    byte[] data = command.ReturnsWashNMJIsOK();
                    commProxy.SendData(data);
                    Thread.Sleep(200);
                    free = false;
                }
                catch (Exception ex)
                {
                    MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述：[{ex.Message}]");
                }
            });
            InitStatus();
        }


    }
}
