using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HBLConsole.Abstract;
using BPA.Message;
using HBLConsole.Model;
using HBLConsole.Service;
using BPA.Message.Enum;
using HBLConsole.GVL;
using BPA.Utility;
using Newtonsoft.Json;
using HBLConsole.Communication;

namespace HBLConsole.Business.MessageServer
{
    public class Base : AbstractMessageServer
    {
        public override void AddOrder<T>(T orderInfo)
        {
            if (orderInfo == null) return;
            if (orderInfo is MorkOrderPush morkOrderpush)
            {
                OrderData order = Json<MorkOrderPushPar>.Data.morkOrderPushes.Find(par => par.OrderPush?.SuborderId == morkOrderpush.SuborderId);
                if (order == null)//防止重复订单
                {
                    Json<MorkOrderPushPar>.Data.morkOrderPushes.Add(new OrderData()
                    {
                        OrderStatus = ORDER_STATUS.WAIT,
                        IsSelected = true,
                        OrderPush = morkOrderpush
                    });
                    ActionOperate.GetInstance.Send("AddOrder",morkOrderpush);
                    ActionOperate.GetInstance.Send("DataParse", morkOrderpush);
                }
            }
        }

        /// <summary>
        /// 接收来自MQTT 推送的物料信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="batchingInfo"></param>
        public override void GetBatchingInfo<T>(T batchingInfo)
        {
            if (batchingInfo == null) return;
            if (batchingInfo is OrderMaterialDelivery BatchingInfos)
            {
                Json<BatchingInfoPar>.Data.orderMaterialDelivery = BatchingInfos;
                MessageLog.GetInstance.Show("收到推送的物料信息");
            }
        }

        /// <summary>
        /// 通过接口获取物料信息
        /// </summary>
        /// <param name="ClientId"></param>
        public override void GetBatchingInfo(int ClientId)
        {
            string result = string.Empty;
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int PushType = i;//0:主料   1：辅料
                    var jsondata = new { ClientId, PushType };
                    string header = $"[{InternetInfo.StockServer}/GetItemInfo]_[{DateTime.Now.Ticks}]".AESEncrypt();
                    string url = $"{InternetInfo.ApiAddress}{InternetInfo.StockServer}/GetItemInfo";
                    //string url = $"http://192.168.0.62:7000{InternetInfo.StockServer}/GetItemInfo";
                    result = APIHelper.GetInstance.HttpRequest(url, header, jsondata, RequestType.POST);

                    if (PushType == 1)
                    {
                        Json<BatchingInfoPar>.Data.recipeBoms = JsonConvert.DeserializeObject<RecipeBoms>(result);
                        WritePlcData();
                    }
                    else if (PushType == 0)
                    {
                        Json<BatchingInfoPar>.Data.orderMaterialDelivery = JsonConvert.DeserializeObject<OrderMaterialDelivery>(result);

                    }
                }
                catch (Exception ex)
                {
                    MessageLog.GetInstance.Show(ex.ToString());
                }
            }

            MessageLog.GetInstance.Show("【物料信息】");
            Json<BatchingInfoPar>.Data.orderMaterialDelivery?.BatchingInfo?.ForEach(x =>
            {
                MessageLog.GetInstance.Show($"{x.BatchingLoc}号位置：{x.BatchingCount}");
            });
        }

        /// <summary>
        /// 接收MQTT 推送过来的辅料信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="recipeBomInfo"></param>
        public override void GetRecipeBom<T>(T recipeBomInfo)
        {
            if (recipeBomInfo == null) return;
            if (recipeBomInfo is RecipeBoms recipeBom)
            {
                Json<BatchingInfoPar>.Data.recipeBoms = recipeBom;
                MessageLog.GetInstance.Show("接收到辅料信息");
            }
            WritePlcData();
        }

        /// <summary>
        /// 写配方数据到PLC
        /// </summary>
        private void WritePlcData()
        {
            return;
            //写配方数据到PLC
            List<ushort> recipeBoms = new List<ushort>();
            foreach (var item in Json<BatchingInfoPar>.Data.recipeBoms.RecipeIds)
            {
                foreach (var rec in item.Recipes)
                {
                    recipeBoms.Add((ushort)rec);
                }
            }
            if (recipeBoms.Count > 0)
            {
                if (ModbusTcpHelper.GetInstance.Write(1100, WriteType.HoldingRegisters, recipeBoms.ToArray()))
                {
                    MessageLog.GetInstance.Show("成功写入配方数据");
                }
            }
        }

        /// <summary>
        /// 订单状态改变
        /// </summary>
        /// <param name="subOrderId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public override bool OrderStatusChange(string subOrderId, ORDER_STATUS status)
        {
            string result = string.Empty;
            OrderStatusChange orderStatusChange = new OrderStatusChange() { CookingStatus = status, SuborderId = subOrderId };
            try
            {
                string header = $"[{InternetInfo.OrderServer}/order/robotstatuschange]_[{DateTime.Now.Ticks}]".AESEncrypt();
                string url = $"{InternetInfo.ApiAddress}{InternetInfo.OrderServer}/order/robotstatuschange";
                result = APIHelper.GetInstance.HttpRequest(url, header, orderStatusChange, RequestType.POST);
            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.Show(ex.ToString());
            }
            var res = JsonConvert.DeserializeObject<OrderStatusRsp>(result);
            return res == null ? false: res.isSuccess;
        }
        public class OrderStatusRsp
        {
            /// <summary>
            /// 子订单ID
            /// </summary>
            public string SuborderId { get; set; }
            /// <summary>
            /// 订单状态
            /// </summary>
            public int Result { get; set; } = 0;
            public bool isSuccess { get; set; }
            public bool data { get; set; }
            public string msg { get; set; }

        }
    }
}
