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



        public override void Do(Device<IStation520, IStation521, IStation523, IRobot530, IRobot531> obj)
        {
            if (!obj.Data5.CmdType.HasFlag(RobotCmdType.End) && obj.Data4.CmdType != 0) 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>().UpdLock().Where(x => taskNoList.Contains(x.ID) && x.Status == TaskStatus.ConveyorExecution).ToList();
                if (tasks.Count() > 0 && tasks.Count() != obj.Data5.MaxQuantity)
                {
                    World.Log($"任务数量{tasks.Count()}-最大码垛数量{obj.Data5.MaxQuantity}");
                    return;
                } 
                var deliveryTask = db.Queryable<WCS_TaskInfo>().UpdLock().Single(x => x.Type == TaskType.Delivery && x.AddrTo == obj.Entity.Code && x.Status >= TaskStatus.RgvExecution && x.Status < TaskStatus.Finish) ?? throw new KnownException($"未找到当前站台对应的托盘搬运任务", LogLevelEnum.High);
                var taskInfo = db.Queryable<WCS_TaskInfo>().UpdLock().Single(x => x.Status <= TaskStatus.RgvCompleted && x.AddrFrom == obj.Entity.Code && x.Type == TaskType.EnterDepot);
                if (deliveryTask.Status != 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);
                    try
                    {
                        //开始绑盘
                        WmsApi.FinishBingPallet(cbrCode.BarCode, tasks.Select(x => x.BarCode).ToList(), obj.Entity.Code.GetWareCode(), obj.Entity.Code);
                    }
                    catch (Exception e)
                    {
                        World.Log($"{e.Message}");
                        try
                        {
                            WmsApi.BingPallet(cbrCode.BarCode, tasks.Select(x => x.BarCode).ToList(), obj.Entity.Code.GetWareCode(), obj.Entity.Code);
                        }
                        catch (Exception exception)
                        {
                            World.Log($"{exception.Message}");
                        }
                    }
                    return;
                }

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

                foreach (var item in tasks)
                {
                    item.Status = TaskStatus.Finish;
                    item.EndTime = DateTime.Now;
                    db.UpdateableRowLock(item).UpdateColumns(x => new { x.Status, x.EndTime }).ExecuteCommand();
                    item.AddWCS_TASK_DTL(db, obj.Entity.Code, "任务结束");
                }

                deliveryTask.Status = TaskStatus.Finish;
                deliveryTask.EndTime = DateTime.Now;
                db.UpdateableRowLock(deliveryTask).UpdateColumns(x => new { x.Status, x.EndTime }).ExecuteCommand();
                deliveryTask.AddWCS_TASK_DTL(db, obj.Entity.Code, $"任务结束");
                var dev = DevicePath.GetPath(obj.Entity.Code, "SRM").Points.Last();
                taskInfo.Status = TaskStatus.ConveyorExecution;
                taskInfo.WarehouseCode = dev.Code.GetWareCode();
                db.UpdateableRowLock(taskInfo).UpdateColumns(x => new { x.Status, x.WarehouseCode }).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.环形库码垛工位);
        }
    }
}
