using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.Entity.Protocol.BCR;
using WCS.Entity.Protocol.Station;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.Worlds;
using WCS.WorkEngineering.Worlds.Logs;
using DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    ///  一楼入库工位处理系统
    /// </summary>
    [BelongTo(typeof(MainWorld))]
    [Description("一楼入库工位处理系统")]
    public class 一楼入库工位处理系统 : DeviceSystem<Station>
    {
        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        private List<BCR> BCRS = new List<BCR>();

        public 一楼入库工位处理系统()
        {
            BCRS = Device.All.Where(v => v.HasProtocol<IBCR81>()).Select(v => new BCR(v, World)).ToList();
        }

        public override void Do(Station obj)
        {
            obj.StorageStationIsForbid();
            //判断凭证号是否一致
            if (obj.Data.VoucherNo != obj.Data2.VoucherNo) throw new KnownException($"凭证号不一致,DB520-{obj.Data.VoucherNo}-DB521{obj.Data2.VoucherNo}", LogLevelEnum.High);
            //设备是否停止运行
            if (obj.Data3.Status.HasFlag(StatusEunm.Run)) throw new KnownException("设备运行中", LogLevelEnum.Low);
            if (!obj.Data3.Status.HasFlag(StatusEunm.PH_Status)) throw new KnownException("没有光电", LogLevelEnum.Low);
            if (obj.Data2.TaskNumber != 0) throw new KnownException("有任务", LogLevelEnum.Low);
            if (obj.Data2.Request != 1) throw new KnownException("没有请求", LogLevelEnum.Low);

            WCS_TaskInfo task = null;
            SqlSugarHelper.Do(db =>
           {
               //获取RFID
               var barcode = BCRS.GetBCRCode(obj.Entity.Code);
               //跟据RFID获取对应的任务
               task = db.Default.Queryable<WCS_TaskInfo>().First(v => v.BarCode == barcode) ?? throw new KnownException($"未找到RFID-{barcode}对应WCS任务", LogLevelEnum.High);
               if (task.Status != Entity.TaskStatus.AGVExecution) throw new KnownException($"任务-{task.ID}状态不是AGV执行中，请检查异常原因", LogLevelEnum.High);

               if (!obj.Data3.Status.HasFlag(StatusEunm.ManualStorage)) //不是手动入库
               {
                   //判断AGV任务目标地址是否是当前地址
                   var agv = db.Default.Queryable<WCS_AgvTaskInfo>().SplitTable(v => v.Take(2)).First(v => v.ID == task.AgvTaskID) ?? throw new KnownException($"任务{task.ID}未找到对应AGV任务", LogLevelEnum.Mid);
                   if (agv.Position != obj.Entity.Code) throw new KnownException($"任务{task.ID}对应AGV任务目标地址不是当前站台", LogLevelEnum.Mid);
               }


               //获取称重
               var dev91 = Device.All.Where(v => v.Code == obj.Entity.Code).Select(v => new Device<IStation91>(v, this.World)).FirstOrDefault();
               task.Weight = dev91.Data.Weight;
               WmsApi.WcsUploadInfo(task.ID, (decimal)task.Weight, task.BarCode);

               task.Status = Entity.TaskStatus.ConveyorExecution;
               db.Default.Updateable(task).AddQueue();
               task.AddWCS_TASK_DTL(db, obj.Entity.Code, "SRM", $"状态更新为{Entity.TaskStatus.ConveyorExecution},等待分配货位后堆垛机进行取货");
               db.Default.SaveQueues();
           });
            if (task == null) throw new KnownException("数据更新错误", LogLevelEnum.High);
            obj.Data.TaskNumber = task.ID;
        }

        public override bool Select(Device dev)
        {
            //return dev.Code == "1013";
            return dev.HasFlag(DeviceFlags.一楼入库口);
        }
    }
}
