using BPA.Message.IOT;
using HBLConsole.Communication;
using HBLConsole.GVL;
using HBLConsole.Interface;
using HBLConsole.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HBLConsole.Business
{
    public class IotReport
    {
        #region 单例模式
        private volatile static IotReport _Instance;
        public static IotReport GetInstance => _Instance ?? (_Instance = new IotReport());
        private IotReport()
        {
            IOTDev.GetInstance().Set(InternetInfo.ProductKey, InternetInfo.DeviceName, InternetInfo.DeviceSecret);
            iSLinks = IOTDev.GetInstance().CreateLinks();
            //订阅设备控制主题
            IOTDev.GetInstance().IOT_Subscribe("/" + InternetInfo.ProductKey + "/" + InternetInfo.DeviceName + "/user/SetDevice");
            IOTDev.actionIOT += actionIOTHandler;//消息数据回调
            if (iSLinks) MessageLog.GetInstance.Show($"设备{InternetInfo.DeviceName}阿里云连接成功.");
            else MessageLog.GetInstance.Show($"设备{InternetInfo.DeviceName}阿里云连接失败.不能上报业务信息");

            string NameSpace = $"HBLConsole.{GeneralConfig.DeviceType}";
            control = (IControl)(Assembly.Load(NameSpace).GetType($"{NameSpace}.Control_{GeneralConfig.DeviceType}"))?.GetProperty("Instance").GetValue(null);
        }
        #endregion

        #region 变量
        /// <summary>
        /// 是否连接成功
        /// </summary>
        public bool iSLinks = false;
        /// <summary>
        /// 大屏上报Model
        /// </summary>
        public IOTDevSXModel iOTDevSXModel = new IOTDevSXModel() { SBMC = InternetInfo.DeviceName, SBMS = InternetInfo.DeviceMS };
        /// <summary>
        /// 当前控制的设备控件
        /// </summary>
        public IControl control;

        #endregion

        /// <summary>
        /// 关闭IOT连接
        /// </summary>
        public void Close()
        {
            IOTDev.GetInstance().Disconnect();
        }
        /// <summary>
        /// 获取属性状态
        /// </summary>
        public T GetTypeValue<T>(string str)
        {
            return (T)control.GetT().GetType().GetProperty(str).GetValue(control.GetT(), null);
        }

        /// <summary>
        /// 设置上报数据
        /// </summary>
        public void SetData()
        {
            #region 上报数据整理
            #region 基本数据
            //设置基本属性与状态
            iOTDevSXModel.SetJBSX(new DevSX
            {
                data = new List<DevSXBase>
                        {
                            new DevSXBase { SXMC="设备硬件",SXLX="机器人",SXStatus=ModbusTcpHelper.GetInstance.Connected
                            ,SXYCMS=ModbusTcpHelper.GetInstance.Connected?"":DateTime.Now+" 异常,机器人未连接,疑似未连接网络...."},
                            new DevSXBase { SXMC="设备软件",SXLX="上位机",SXStatus=true }
                        }
            });
            #endregion

            #region 扩展数据
            bool IsAllowRun = GetTypeValue<bool>("AllowRun");
            bool TemperatureReached = GetTypeValue<bool>("TemperatureReached");
            bool MissingBowl = GetTypeValue<bool>("MissingBowl");
            bool MissingBowlSignal2 = GetTypeValue<bool>("MissingBowlSignal2");
            bool IsNoodles = GetTypeValue<bool>("IsNoodles");//转台
            bool AllowFallNoodle = GetTypeValue<bool>("AllowFallNoodle");//是否允许到面
            bool[] CookNoodlesComplete = GetTypeValue<bool[]>("CookNoodlesComplete");//煮面完成上升信号
            bool isCookNoodles= CookNoodlesComplete.ToList().Find(o=>o);
            //设置扩展属性与状态,连接上机器人后才会处罚
            if (IsAllowRun)
            {
                iOTDevSXModel.SetKZSX(new DevSX
                {
                    data = new List<DevSXBase>
                    {
                        new DevSXBase { SXMC="设备硬件",SXLX="煮面炉",SXStatus= !TemperatureReached ,
                        SXYCMS=!TemperatureReached?"":DateTime.Now+" 异常,煮面炉温度不够,疑似正在加热或者未工作...."},
                        new DevSXBase { SXMC="设备硬件",SXLX="装小碗结构",SXStatus=MissingBowl ,
                        SXYCMS=MissingBowl?"":DateTime.Now+" 异常,缺小碗...."},
                        new DevSXBase { SXMC="设备硬件",SXLX="装大碗结构",SXStatus=MissingBowlSignal2 ,
                        SXYCMS=MissingBowlSignal2?"":DateTime.Now+" 异常,缺大碗...."},
                        new DevSXBase { SXMC="设备硬件",SXLX="取面转台",SXStatus=IsNoodles ,
                        SXYCMS=IsNoodles?"":DateTime.Now+" 异常,转台位置缺少物料...."},
                        new DevSXBase { SXMC="设备硬件",SXLX="配料机",SXStatus=!(!AllowFallNoodle && isCookNoodles) ,
                        SXYCMS=!((!AllowFallNoodle && isCookNoodles))?"":DateTime.Now+" 异常,配料机未配完料,疑似碗未到配料机下方或者配料机未工作...."}
                    }
                });
            }
            else {
                iOTDevSXModel.SetKZSX(new DevSX { data = new List<DevSXBase> { new DevSXBase { SXMC = "", SXLX = "" } } });
            }
            #endregion

            //设置告警消息
            #region 告警消息
            List<DevSXBase> bases = Tools.JsonToObjectTools<DevSX>(iOTDevSXModel.JBSX)?.data?.ToList().FindAll(par => par.SXStatus == false);
            if (bases != null) bases.AddRange(Tools.JsonToObjectTools<DevSX>(iOTDevSXModel.KZSX)?.data?.ToList().FindAll(par => par.SXStatus == false));
            List<AlarmModel> alarms = new List<AlarmModel>();
            bases?.ForEach(par => alarms.Add(new AlarmModel { DeviceMC = iOTDevSXModel.SBMC, DeviceSJ = DateTime.Now.ToString(), AlarmCD = "一般", DeviceZT = "未处理", DeviceMS = par.SXYCMS }));
            iOTDevSXModel.SetGJXX(new AlarmMessage { data = alarms });
            #endregion

            bool InitComplete = GetTypeValue<bool>("InitComplete");
            bool RobotTakeNoodle = GetTypeValue<bool>("RobotTakeNoodle");
            bool RobotOutMeal = GetTypeValue<bool>("RobotOutMeal");
            iOTDevSXModel.SetLCSB(new ProcessMessage
            {
                data = new List<ProcessModel>
                {
                    new ProcessModel { ProcessName="开机",IsMark=IsAllowRun,ProcessMS=IsAllowRun?"机器人开机成功":"" },
                    new ProcessModel { ProcessName="初始化",IsMark=InitComplete,ProcessMS=InitComplete?"机器人正在初始化成功":"" },
                    new ProcessModel { ProcessName="取面",IsMark=RobotTakeNoodle,ProcessMS=RobotTakeNoodle?"机器人正在取面过程中....":""},
                    new ProcessModel { ProcessName="出餐",IsMark=AllowFallNoodle,ProcessMS=AllowFallNoodle?"机器人正在出餐过程中....":"" }
                }
            });
            #endregion

        }

        /// <summary>
        /// 初始化上报流程
        /// </summary>
        public void Init()
        {
            ThreadOperate.GetInstance.StartLong(new Action(() =>
            {
                if (iSLinks && GeneralConfig.DeviceType.ToString() == "MORKS")
                {
                    SetData();
                    IOTDev.GetInstance().IOT_Publish(IOTDev.PubTopic, iOTDevSXModel.Tojson());
                }
                Thread.Sleep(5000);
            }), "设备IOT上报云端");
        }

        private void actionIOTHandler(string topic, string message)
        {
            
        }
    }
}
