using ServiceCenter.Extensions;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
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
{
    [BelongTo(typeof(MainWorld))]
    [Description("机台叫料生成AGV任务")]
    public class 机台叫料生成AGV任务 : DeviceSystem<Device<IStation520, IStation521, IStation523>>
    {
        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        public override void Do(Device<IStation520, IStation521, IStation523> obj)
        {
            //var res = AgvApi.测试路径("2533", "12346");
            //var res = AgvApi.机台叫料("2534", "LX32", Guid.NewGuid().ToString().Replace("-", ""));
            //var res = AgvApi.托盘回库("LX32", Guid.NewGuid().ToString().Replace("-",""));

            if (!obj.Data3.Status.HasFlag(StationStatus.PH_Status)) return;
            if (!obj.Data3.Status.HasFlag(StationStatus.Low_Station_2)) return;
            //if (!obj.Data3.Status.HasFlag(StationStatus.Auto)) return;

            SqlSugarHelper.Do(_db =>
            {
                var db = _db.Default;
                var task = db.Queryable<WCS_TaskInfo>().Single(x => x.ID == obj.Data.TaskNumber);
                if (task == null) return;
                if (task.Status != Entity.TaskStatus.ConveyorExecution) return;
                //开始创建AGV任务
                var agvTask = db.Queryable<WCS_AgvTaskInfo>().SplitTable(x => x.Take(2)).Single(x => x.TaskId == task.ID && x.TaskType == AGVTaskType.CallMaterial);
                if (agvTask == null) return;
                if (agvTask.Status != AGVTaskStatus.NewBuild) return;
                var agvId = DateTime.Now.GetFormat(GetFormatterEnum.only) /*SnowFlakeSingle.instance.getID()*/;

                var res = AgvApi.机台叫料(obj.Entity.Code, task.WorkBench, agvId);
                agvTask.AgvID = agvId;
                agvTask.Status = AGVTaskStatus.Confirm;
                agvTask.AgvStatus = AGVTaskStatus.Confirm;
                db.Updateable(agvTask).SplitTable(x=>x.Take(2)).ExecuteCommand();
                task.Status = TaskStatus.AGVExecution;
                task.AgvTaskID = agvTask.ID;
                task.Updateable(db);
                task.AddWCS_TASK_DTL(db, obj.Entity.Code, "AGV", $"任务下发至AGV{agvId}");
            });
        }

        public override bool Select(Device dev)
        {
            return dev.HasFlag(DeviceFlags.AGV取货站台口);
        }
    }
}
