using Microsoft.OpenApi.Extensions;
using ServiceCenter.Extensions;
using ServiceCenter.Logs;
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;

        public override void Do(Device<IStation520, IStation521, IStation523> obj)
        {
            if (!obj.Data3.Status.HasFlag(StationStatus.Auto))
            {
                World.Log($"设备处于{obj.Data3.Status.GetDisplayName()}状态");
                return;
            }

            if (!obj.Data3.Status.HasFlag(StationStatus.PH_Status))
            {
                World.Log($"设备无光电");
                return;
            }

            if (obj.Data3.Status.HasFlag(StationStatus.PH_Status) && !obj.Data3.Status.HasFlag(StationStatus.Low_Station_2))
            {
                World.Log($"设备有光电，但不在低位", LogLevelEnum.High);
                return;
            }

            if (!obj.Data3.Status.HasFlag(StationStatus.Low_Station_2))
            {
                World.Log($"设备不在低位", LogLevelEnum.High);
                return;
            }

            SqlSugarHelper.Do(_db =>
            {
                var db = _db.Default;
                var task = db.Queryable<WCS_TaskInfo>().ReadPastUpdLock().Single(x => x.Uploaded == TaskStatus.ConveyorExecution && x.Status == TaskStatus.ConveyorExecution && x.ID == obj.Data.TaskNumber);
                if (task == null)
                {
                    World.Log($"未找到对应任务[{obj.Data.TaskNumber}],请检查该任务状态与更新状态是否均为输送机执行中", LogLevelEnum.High);
                    return;
                }
                var agvId = DateTime.Now.GetFormat(GetFormatterEnum.only) + task.ID;

                //开始创建AGV任务
                var agvTask = db.Queryable<WCS_AgvTaskInfo>().UpdLock().SplitTable(x => x.Take(2)).Single(x => x.TaskId == task.ID && x.TaskType == AGVTaskType.CallMaterial);
                if (agvTask == null)
                {
                    //开始处理车间叫料AGV任务任务
                    db.InsertableRowLock(new WCS_AgvTaskInfo()
                    {
                        ID = _db.GetAgvTaskId(),
                        TaskType = AGVTaskType.CallMaterial,
                        Status = AGVTaskStatus.NewBuild,
                        TaskId = task.ID,
                        Position = task.WorkBench,
                        Station = task.SrmStation,
                        AddWho = "WCS",
                        AddTime = DateTime.Now,
                        AgvID = agvId
                    }).SplitTable().ExecuteCommand();
                    World.Log($"{task.ID}未找到对应的AGV任务");
                    return;
                }

                if (agvTask.Status != AGVTaskStatus.NewBuild)
                {
                    World.Log($"AGV任务{agvTask.ID}状态不是新建", LogLevelEnum.High);
                    return;
                }
                agvId = agvTask.AgvID;

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

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