using ServiceCenter.Extensions;
using ServiceCenter.Logs;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.Entity.Protocol.Protocol.Robot;
using WCS.Entity.Protocol.Robot;
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(RingWorld))]
    [Description("环形库码垛结束")]
    public class 环形库码垛结束 : DeviceSystem<Device<IStation520, IStation521, IStation523, IRobot530, IRobot531>>
    {
        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        public override void Do(Device<IStation520, IStation521, IStation523, IRobot530, IRobot531> obj)
        {
            if (!obj.Data5.CmdType.HasFlag(RobotCmdType.End)) obj.Data4.CmdType = 0;
            if (!obj.Data3.Status.HasFlag(StationStatus.PH_Status)) return;
            if (!obj.Data5.CmdType.HasFlag(RobotCmdType.End)) return;
            if (obj.Data5.MaxQuantity != obj.Data5.Quantity || obj.Data5.Quantity == 0 || obj.Data5.MaxQuantity == 0) throw new KnownException($"码垛数量异常:最大码垛数量[{obj.Data5.MaxQuantity}]已码数量{obj.Data5.Quantity}", LogLevelEnum.High);
            WCS_TaskInfo task = null;
            //找到对应的码垛数据
            SqlSugarHelper.Do(_db =>
            {
                var db = _db.Default;
                var taskNoList = obj.Data5.GetTaskNoList().ToList();
                var tasks = db.Queryable<WCS_TaskInfo>().Where(x => taskNoList.Contains(x.ID) && x.Status == TaskStatus.ConveyorExecution).ToList();
                var deliveryTask = db.Queryable<WCS_TaskInfo>().Single(x => x.Type == TaskType.Delivery && x.AddrTo == obj.Entity.Code) ?? throw new KnownException($"未找到当前站台对应的托盘搬运任务", LogLevelEnum.High);
                var taskInfo = db.Queryable<WCS_TaskInfo>().Single(x => x.AddrFrom == obj.Entity.Code && x.Type == TaskType.EnterDepot);
                if (deliveryTask.Status != Entity.TaskStatus.RgvCompleted) throw new KnownException($"搬运任务状态异常:{deliveryTask.ID}", LogLevelEnum.High);
                if (taskInfo == null)
                {
                    //开始获取当前位置的空托盘搬运任务信息
                    var cbrCode = db.Queryable<WCS_TaskInfo>().First(x => x.Status == TaskStatus.RgvCompleted && x.AddrTo == obj.Entity.Code);
                    //开始绑盘
                    WmsApi.BingPallet(cbrCode.BarCode, tasks.Select(x => x.BarCode).ToList(), obj.Entity.Code.GetWareCode(), obj.Entity.Code);
                    return;
                }

                if (taskInfo.Status != TaskStatus.WaitingToExecute) return;

                foreach (var item in tasks)
                {
                    item.Status = TaskStatus.Finish;
                    item.EditTime = DateTime.Now;
                    db.Updateable(item).ExecuteCommand();
                    item.AddWCS_TASK_DTL(db, obj.Entity.Code, "任务结束");
                }

                deliveryTask.Status = TaskStatus.Finish;
                deliveryTask.EndTime = DateTime.Now;
                db.Updateable(deliveryTask).ExecuteCommand();
                deliveryTask.AddWCS_TASK_DTL(db, obj.Entity.Code, $"任务结束");
                var dev = DevicePath.GetPath(obj.Entity.Code, "SRM").Points.Last();
                taskInfo.WarehouseCode = dev.Code.GetWareCode();
                db.Updateable(taskInfo).ExecuteCommand();
                taskInfo.AddWCS_TASK_DTL(db, obj.Entity.Code, $"更新任务对应仓库信息{taskInfo.WarehouseCode}");

                task = taskInfo;
            });
            if (task == null) return;
            obj.Data.TaskNumber = task.ID;
            obj.Data.GoodsStart = obj.Entity.Code.ToShort();
            obj.Data.GoodsEnd = task.AddrNext.ToShort();
            obj.Data4.CmdType = RobotCmdType.End;
        }

        public override bool Select(Device dev)
        {
            return dev.HasFlag(DeviceFlags.环形库码垛工位);
        }
    }
}
