using Microsoft.OpenApi.Extensions;
using ServiceCenter.Logs;
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 DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;
using TaskStatus = WCS.Entity.TaskStatus;

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

        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.入库站点是否被禁止();
            obj.入库站点是否满足执行条件();

            WCS_TaskInfo task = null; //处理完成的任务
            SqlSugarHelper.Do(_db =>
             {
                 var db = _db.Default;
                 WCS_TaskInfo taskInfo = null; //需要处理的任务

                 #region 初始化空轮入库任务检索

                 //判断当前站台是否有多条待执行状态的初始化空轮入库任务
                 if (db.Queryable<WCS_TaskInfo>().Count(v => v.Type == TaskType.EmptyInit && v.Status == TaskStatus.WaitingToExecute && v.SrmStation == obj.Entity.Code) > 1)
                 {
                     throw new KnownException($"{obj.Entity.Code}站台存在多个空轮初始化入库任务,请取消RFID不是站台实物的任务", LogLevelEnum.Mid);
                 }
                 taskInfo = db.Queryable<WCS_TaskInfo>().First(v => v.Type == TaskType.EmptyInit && v.Status == TaskStatus.WaitingToExecute && v.SrmStation == obj.Entity.Code);

                 #endregion 初始化空轮入库任务检索

                 #region 非空轮初始化入库任务

                 if (taskInfo == null)
                 {
                     taskInfo = db.Queryable<WCS_TaskInfo>().First(v => v.ID == obj.Data.TaskNumber && v.Type == TaskType.EnterDepot && v.SrmStation == obj.Entity.Code);
                     if (taskInfo == null) throw new KnownException($"未找到任务[{obj.Data.TaskNumber}],或该任务不是入库任务", LogLevelEnum.Mid);
                     if (taskInfo.Status != Entity.TaskStatus.AGVExecution)
                     {
                         if (!db.Queryable<WCS_TaskDtl>().SplitTable(v => v.Take(2)).Any(v => v.ParentTaskCode == taskInfo.ID && v.Desc.Contains("等待分配货位后堆垛机进行取货"))) return;
                         else throw new KnownException($"任务:{taskInfo.ID}不是AGV执行状态，请检查异常原因", LogLevelEnum.High);

                     }
                 }

                 #endregion 非空轮初始化入库任务

                 if (obj.Entity.Code == "1025" || obj.Entity.Code == "1127")//获取称重
                 {
                     var dev91 = Device.All.Where(v => v.Code == obj.Entity.Code).Select(v => new Device<IStation91>(v, this.World)).FirstOrDefault();
                     taskInfo.Weight = dev91.Data.Weight;
                     if (taskInfo.Weight < 140) throw new KnownException($"称重结果错误:{taskInfo.Weight}", LogLevelEnum.Mid);
                     //上抛重量
                     try { WmsApi.WcsUploadInfo(taskInfo.ID, (decimal)taskInfo.Weight, taskInfo.BarCode); } catch (Exception ex) { World.Log(ex.Message, LogLevelEnum.Mid); }
                 }

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

        public override bool Select(Device dev)
        {
            return dev.Code is "1025" or "1023" or "1021" or "1127";
        }
    }
}
