using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading.Tasks;
using BPASmartClient.Device;
using BPA.Message.Enum;
using BPA.Message;
using BPASmartClient.Helper;
using BPASmartClient.Model.咖啡机.Enum;
using BPASmartClient.Model;
using BPASmartClient.EventBus;
using static BPASmartClient.EventBus.EventBus;
using BPASmartClient.Model.PLC;
using BPASmartClient.Model.单片机;

namespace BPASmartClient.MorkTJuicer
{
    /*
     * 冰淇淋咖啡机组合套装
     * 物料位置：
     * 1：冰淇料
     * 2：冰淇淋杯
     * 5：咖啡
     * 6：咖啡杯
     * 9: 茶
     * 10: 茶杯
     */
    public class Control_MORKJC : BaseDevice
    {
        GVL_MORKJC mORKD = new GVL_MORKJC();
        //物料存放位置
        private Dictionary<string, PolymerBatching> batchings = new Dictionary<string, PolymerBatching>();
        //容器位置
        private string holderLoc;
        //主料位置
        private string mainMaterialLoc;
        //子订单ID
        private string subOrderId;

        private bool enableFunny = false;
        private DateTime lastRecvdOrder = DateTime.Now;
        private bool working = false;
        /// <summary>
        /// 果汁机做法，true:热饮，false:冷饮
        /// </summary>
        private bool GuMake = false;

        private void OrderChange(string subid, ORDER_STATUS oRDER_STATUS)
        {
            EventBus.EventBus.GetInstance().Publish(new OrderStatusChangedEvent() { Status = oRDER_STATUS, SubOrderId = subid, deviceClientType = DeviceType });
        }

        //private SerialPortClient commProxy;
        public void ConnectOk()
        {

        }
        ConcurrentQueue<MorkOrderPush> morkOrderPushes = new ConcurrentQueue<MorkOrderPush>();
        public void Init()
        {
            //构建所有商品物料信息
            batchings = PolymerBatching.BuildAll();
            Main();
            ReadData();
            ThreadManage.GetInstance().StartLong(new Action(() =>
            {
                while (morkOrderPushes.Count > 0)
                {
                    while (enableFunny) { Thread.Sleep(10); }
                    DeviceProcessLogShow("当前非自嗨模式，允许开工");
                    working = true;
                    if (morkOrderPushes.TryDequeue(out MorkOrderPush order))
                    {
                        DeviceProcessLogShow($"开始制作订单[{order.SortNum}]");
                        //商品类型
                        GOODS_TYPE currentGoodsType = GOODS_TYPE.NEITHER;
                        //子订单ID
                        subOrderId = order.SuborderId;
                        //遍历物料
                        foreach (var item in order.GoodBatchings)
                        {
                            var res = Json<BatchingInfoPar>.Data.orderMaterialDelivery.BatchingInfo.FirstOrDefault(p => p.BatchingId == item.BatchingId);
                            if (res != null)
                            {
                                //获取主料和容器位置
                                switch (batchings[res.BatchingLoc].BatchingClass)
                                {
                                    case BATCHING_CLASS.HOLDER:
                                        holderLoc = res.BatchingLoc;
                                        break;
                                    case BATCHING_CLASS.MAIN_MATERIAL:
                                        // mainMaterialLoc ="1";
                                        mainMaterialLoc = res.BatchingLoc;
                                        //验证商品是咖啡还是冰淇淋
                                        if (ValidateGoodsByBatching(res.BatchingLoc) != GOODS_TYPE.NEITHER)
                                        {
                                            //获取当前物料所属商品类型
                                            currentGoodsType = ValidateGoodsByBatching(res.BatchingLoc);
                                        }
                                        break;
                                }
                            }
                        }
                        //根据商品类型执行具体制作流程
                        switch (currentGoodsType)
                        {
                            case GOODS_TYPE.JUICE:
                                GuMake = order.MakeID == "2";
                                DoJuicer();
                                break;
                            case GOODS_TYPE.NEITHER:
                                DeviceProcessLogShow("未知的商品类型");
                                break;
                        }
                    }
                    working = false;
                    lastRecvdOrder = DateTime.Now;
                }
                Thread.Sleep(1000);
            }), "订单制作");
        }

        public void Main()
        {
            //开始心跳刷新，根据咖啡机及冰淇淋机来判断
            //ThreadManage.GetInstance().StartLong(new Action(() =>
            //{
            //    Thread.Sleep(100);
            //}), "MORK-IC心跳刷新");
        }

        public void DataParse<T>(T order)
        {
            if (order is MorkOrderPush morkOrderPush)
            {
                morkOrderPushes.Enqueue(morkOrderPush);
            }
        }

        /// <summary>
        ///  
        /// </summary>
        /// <param name="batchingLoc">物料位置</param>
        private GOODS_TYPE ValidateGoodsByBatching(string batchingLoc)
        {
            if (batchings.ContainsKey(batchingLoc))
                return batchings[batchingLoc].GoodsType;
            return GOODS_TYPE.NEITHER;
        }

        private AutoResetEvent are = new AutoResetEvent(false);

        private T GetStatus<T>(string key)
        {
            if (peripheralStatus.ContainsKey(key))
            {
                if (peripheralStatus[key] != null)
                {
                    return (T)(peripheralStatus[key]);
                }
            }
            return default;
        }

        private void Wait(int value)
        {
            while (!((GetStatus<int>("Get_RobotAO1") == value) && GetStatus<int>("GetProgramStatus") == 0))//判断文件是否已经执行结束 且 文件末端变量值==文件名
            {
                Thread.Sleep(5);
            }
        }
        int[] devStatusBy = new int[2] { 0, 0 };
        /// <summary>
        /// 果汁机控制信号
        /// </summary>
        private byte JuicerNum;
        /// <summary>
        /// 做果汁
        /// </summary>
        private void DoJuicer()
        {
            #region 接果汁流程
            OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COOKING);
            try
            {
                int JuicerNum1 = int.Parse(mainMaterialLoc);
                switch (JuicerNum1)
                {
                    case 52:
                        if (GuMake)
                        {
                            JuicerNum = 0x00;
                        }
                        else
                        {
                            JuicerNum = 0x01;
                        }
                        break;
                    case 53:
                        if (GuMake)
                        {
                            JuicerNum = 0x02;
                        }
                        else
                        {
                            JuicerNum = 0x03;
                        }
                        break;
                    case 54:
                        if (GuMake)
                        {
                            JuicerNum = 0x04;
                        }
                        else
                        {
                            JuicerNum = 0x05;
                        }
                        break;
                    case 55:
                        if (GuMake)
                        {
                            JuicerNum = 0x06;
                        }
                        else
                        {
                            JuicerNum = 0x07;
                        }
                        break;
                    default:
                        JuicerNum = 0x00;
                        break;
                }
                var devStatus = GetStatus<int[]>("GetDeviceStatus");
                var devStatus1 = Convert.ToString(devStatus[0], 2);
                var devStatus2 = devStatus[1];

                if (devStatus1.IndexOf("0") == 1 && devStatus2 == 0)
                {
                    new WriteJuicer() { Value = JuicerNum }.Publish();

                    Thread.Sleep(100);
                    devStatusBy = GetStatus<int[]>("GetDeviceStatus");
                    while (!(devStatusBy[1] == 0))
                    {
                        Thread.Sleep(100);
                        devStatusBy = GetStatus<int[]>("GetDeviceStatus");
                        while (devStatusBy.Length != 2)
                        {
                            Thread.Sleep(100);
                            devStatusBy = GetStatus<int[]>("GetDeviceStatus");
                        }
                    }
                    devStatusBy = GetStatus<int[]>("GetDeviceStatus");
                    Thread.Sleep(5000);
                    OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COMPLETED_TAKE);
                }
            }
            catch (Exception ex)
            {
                DeviceProcessLogShow("获取果汁机状态失败");
            }
            #endregion
        }

        public override DeviceClientType DeviceType => throw new NotImplementedException();


        private T McuRead<T>(string tagName, object par)
        {
            new ReadMcu() { DeviceId = DeviceId, TagName = tagName, ReadPar = par };
            if (peripheralStatus.ContainsKey(tagName))
            {
                if (peripheralStatus[tagName] != null)
                {
                    return (T)peripheralStatus[tagName];
                }
            }
            return default;
        }

        public void SimOrder<T>(T simOrder)
        {

        }
        public override void DoMain()
        {

        }

        public override void Stop()
        {

        }

        public override void ReadData()
        {

        }

        public override void MainTask()
        {

        }

        public override void ResetProgram()
        {

        }
        public override void SimOrder()
        {
        }
    }
}
