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
    {
        private volatile static IotReport _Instance;
        public static IotReport GetInstance => _Instance ?? (_Instance = new IotReport());
        private IotReport()
        {
            iOTDevSXModel = new IOTDevSXModel();
            iOTDevSXModel.SBMC = InternetInfo.DeviceName;
            iOTDevSXModel.SBMS = InternetInfo.DeviceMS;
            iOTDevSXModel.SetKZSX(new DevSX { data = new List<DevSXBase> { new DevSXBase { SXMC = "", SXLX = "" } } });
            IOTDev.GetInstance().Set(InternetInfo.ProductKey, InternetInfo.DeviceName, InternetInfo.DeviceSecret);
            iSLinks = IOTDev.GetInstance().CreateLinks();
            if (iSLinks) MessageLog.GetInstance.Show($"设备{InternetInfo.DeviceName}阿里云连接成功.");
            else MessageLog.GetInstance.Show($"设备{InternetInfo.DeviceName}阿里云连接失败.不能上报业务信息");
            string NameSpace = $"HBLConsole.{GeneralConfig.DeviceType}";//Load 加载的是dll的名称，GetType获取的是全命名空间下的类
            Type type = Assembly.Load(NameSpace).GetType($"{NameSpace}.Control_{GeneralConfig.DeviceType}");
            control = Activator.CreateInstance(type) as IControl;
        }
        /// <summary>
        /// 是否连接成功
        /// </summary>
        public bool iSLinks = false;
        /// <summary>
        /// 大屏上报Model
        /// </summary>
        public IOTDevSXModel iOTDevSXModel = new IOTDevSXModel();
        /// <summary>
        /// 
        /// </summary>
        IControl control;

        public void Close()
        {
            IOTDev.GetInstance().Disconnect();
        }

        public T GetTypeValue<T>(string str)
        {
            return (T)control.GetT().GetType().GetProperty(str).GetValue(control.GetT(), null);
        }

        public void SetData()
        {
            #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 }
                        }
            });
            bool IsAllowRun = GetTypeValue<bool>("AllowRun");
            bool TemperatureReached = GetTypeValue<bool>("TemperatureReached");
            bool MissingBowl = GetTypeValue<bool>("MissingBowl");
            bool TurntableLowerLimit = GetTypeValue<bool>("TurntableLowerLimit");

            //设置扩展属性与状态,连接上机器人后才会处罚
            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=TurntableLowerLimit ,
                        SXYCMS=TurntableLowerLimit?"":DateTime.Now+" 异常,转台缺面...."}
                    }
                });
            }

            //设置告警消息
            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 });

            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 },
                    new ProcessModel { ProcessName="初始化",IsMark=!InitComplete },
                    new ProcessModel { ProcessName="取面",IsMark=RobotTakeNoodle,ProcessMS=RobotTakeNoodle?"机器人正在取面过程中....":""},
                    new ProcessModel { ProcessName="出餐",IsMark=RobotOutMeal,ProcessMS=RobotOutMeal?"机器人正在出餐过程中....":"" }
                }
            });
            #endregion

        }

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

        }
    }
}
