using ServiceCenter.Logs;
using ServiceCenter.Redis;
using System.Collections.Concurrent;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity.Protocol.DataStructure;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.Worlds;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    ///  数据采集系统
    /// </summary>
   // [BelongTo(typeof(DataCollectionWorld))]
    [Description("数据采集系统")]
    public class DataCollectionSysyem : DeviceSystem<SRM>
    {
        public static DeviceDataPack pack = new DeviceDataPack();

        public DataCollectionSysyem()
        {
        }

        /// <summary>
        ///  所有设备数据
        ///  Key 是不同设备所使用的类型 例如DeviceDataCollection<SRMData>
        ///  value 不同设备的具体数据
        /// </summary>
        public static ConcurrentDictionary<string, DeviceData> AllDatas = new ConcurrentDictionary<string, DeviceData>();

        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        public override bool Select(Device dev)
        {
            return dev.Code == "SRM1";
        }

        public override void Do(SRM obj)
        {
            try
            {
                var gs = AllDatas.GroupBy(v => v.Value.GetType());

                DeviceDataPack pack = new DeviceDataPack();
                pack.Frame = DateTime.Now;
                foreach (var g in gs)
                {
                    var value = g.Select(v => v.Value).ToArray();
                    var etype = g.Key;
                    var type = typeof(DeviceDataCollection<>).MakeGenericType(etype);
                    var coll = Activator.CreateInstance(type, DateTime.Now, value);
                    var p = pack.GetType().GetProperties().First(v => v.PropertyType == type);
                    p.SetValue(pack, coll);
                }

                RedisHub.Monitor.RPush("Packs", pack);
                RedisHub.Monitor.Set(nameof(DeviceDataPack), pack);
                if (RedisHub.Monitor.LLen("Packs") > 500000)
                {
                    RedisHub.Monitor.LTrim("Packs", 5000, -1);
                }
            }
            catch (Exception e)
            {
                throw new KnownException($"数据采集错误:{e.StackTrace}", LogLevelEnum.Low);
            }
        }
    }

    /// <summary>
    ///  设备报警
    /// </summary>
    public class EquipmentAlarm
    {
        /// <summary>
        ///  设备号
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        ///  内容
        /// </summary>
        public string Msg { get; set; }

        /// <summary>
        ///  时间
        /// </summary>
        public DateTime Time { get; set; }
    }
}
