using Newtonsoft.Json;
using ServiceCenter.Extensions;
using ServiceCenter.Redis;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity.Protocol.BCR;
using WCS.Entity.Protocol.DataStructure;
using WCS.Entity.Protocol.SRM;
using WCS.Entity.Protocol.Station;
using WCS.Service.Worlds;
using WCS.WorkEngineering.Extensions;

namespace WCS.Service.Systems
{
    /// <summary>
    ///  数据采集系统
    /// </summary>
    [BelongTo(typeof(DataCollectionWorld))]
    [Description("数据采集系统")]
    public class DataCollectionSysyem : DeviceSystem<SRM>
    {
        public List<Station> ConvList;
        public List<Device<IStation91>> Conv91List;
        public List<Device<IBCR81>> Bcrs;
        public List<SRM> Srms;

        public DataCollectionSysyem()
        {
            ConvList = Device.All.Where(v => v.HasProtocol(typeof(IStation523))).Select(v => new Station(v, this.World)).ToList();
            Conv91List = Device.All.Where(v => v.HasProtocol(typeof(IStation91))).Select(v => new Device<IStation91>(v, this.World)).ToList();
            Bcrs = Device.All.Where(v => v.HasProtocol(typeof(IBCR81))).Select(v => new Device<IBCR81>(v, this.World)).ToList();
            Srms = Device.All.Where(v => v.HasProtocol(typeof(ISRM520))).Select(v => new SRM(v, this.World)).ToList();
        }

        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
            {
                DeviceDataPack pack = new DeviceDataPack();

                //处理输送线
                List<StationData> DevList = new List<StationData>();
                foreach (var item in ConvList)
                {
                    var dev = new StationData()
                    {
                        Code = item.Entity.Code,
                        Frame = DateTime.Now,
                        D520 = TypeExtension.Mapper<WCS_Station520, IStation520>(item.Data),
                        D521 = TypeExtension.Mapper<WCS_Station521, IStation521>(item.Data2),
                        D523 = TypeExtension.Mapper<WCS_Station523, IStation523>(item.Data3),
                        D90 = new WCS_Station90(),
                        D91 = new WCS_Station91(),
                        D80 = new WCS_BCR80(),
                        D81 = new WCS_BCR81()
                    };
                    if (Conv91List.Any(v => v.Entity.Code == item.Entity.Code))
                    {
                        var d91 = Conv91List.First(v => v.Entity.Code == item.Entity.Code);
                        dev.D91 = TypeExtension.Mapper<WCS_Station91, IStation91>(d91.Data);
                    }
                    if (Bcrs.Any(v => v.Entity.Code == item.Entity.Code))
                    {
                        var d81 = Bcrs.First(v => v.Entity.Code == item.Entity.Code);
                        dev.D81 = TypeExtension.Mapper<WCS_BCR81, IBCR81>(d81.Data);
                    }
                    //保存报警
                    RedisHub.WMS.Set($"{nameof(EquipmentAlarm)}:{item.Entity.Code}", JsonConvert.SerializeObject(new EquipmentAlarm()
                    {
                        Code = item.Entity.Code,
                        Msg = item.Data3.Alarm.ToString(),
                        Time = DateTime.Now
                    }));

                    DevList.Add(dev);
                }
                //保存模式
                var status = ConvList.Select(v => new Tuple<string, string>(v.Entity.Code, v.Data2.Mode.ToString()));
                RedisHub.WMS.Set($"ConvStatus", JsonConvert.SerializeObject(status));
                //pack.StationDatas = new DeviceDataCollection<StationData>(DateTime.Now, DevList.ToArray());

                //处理堆垛机
                List<SRMData> srmList = new List<SRMData>();
                foreach (var item in Srms)
                {
                    var dev = new SRMData()
                    {
                        Code = item.Entity.Code,
                        Frame = DateTime.Now,
                        D520 = TypeExtension.Mapper<WCS_SRM520, ISRM520>(item.Data),
                        D521 = TypeExtension.Mapper<WCS_SRM521, ISRM521>(item.Data2),
                        D537 = TypeExtension.Mapper<WCS_SRM537, ISRM537>(item.Data3),
                    };

                    //保存报警
                    RedisHub.WMS.Set($"{nameof(EquipmentAlarm)}:{item.Entity.Code}", JsonConvert.SerializeObject(new EquipmentAlarm()
                    {
                        Code = item.Entity.Code,
                        Msg = item.Data3.Alarm.ToString(),
                        Time = DateTime.Now
                    }));
                    srmList.Add(dev);
                }
                //保存模式
                var status1 = Srms.Select(v => new Tuple<string, string>(v.Entity.Code, v.Data2.AutoStatus.ToString()));
                RedisHub.WMS.Set($"SrmStatus", JsonConvert.SerializeObject(status1));
                //pack.SRMDatas = new DeviceDataCollection<SRMData>(DateTime.Now, srmList.ToArray());
                //pack.Frame = DateTime.Now;

                ////保存到Redis
                //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 ex)
            {
                World.Log(ex.StackTrace, ServiceCenter.Logs.LogLevelEnum.Mid);
            }
        }
    }

    /// <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; }
    }
}
