using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.Worlds;
using WCS.WorkEngineering.Worlds.Logs;
using DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;

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

        protected override bool SaveLogsToFile => true;

        public override void Do(Station obj)
        {
            if (!obj.Data3.Status.HasFlag(Entity.Protocol.Station.StatusEunm.PH_Status)) throw new KnownException("无光电", LogLevelEnum.Low);
            SqlSugarHelper.Do(db =>
            {
                var task = db.Default.Queryable<WCS_TaskInfo>().First(v => v.ID == obj.Data.TaskNumber && v.Status == Entity.TaskStatus.ConveyorExecution) ?? throw new KnownException("无可执行任务", LogLevelEnum.Low);
                var agv = db.Default.Queryable<WCS_AgvTaskInfo>().SplitTable(v => v.Take(2)).First(v => v.ID == task.AgvTaskID && v.Status == AGVTaskStatus.NewBuild) ?? throw new KnownException("未找到对应的AGV任务", LogLevelEnum.Low);
                var res = IwmsApi.满轮出库(task.MatCode, task.AddrTo, task.ID.ToString(), task.BarCode, task.InvBarCode, task.IsSurplus, task.IsRework, task.IsFast, task.Grade);
                agv.Status = AGVTaskStatus.Confirm;
                agv.AgvID = res.data;
                agv.Station = obj.Entity.Code;
                db.Default.Updateable(agv).SplitTable().ExecuteCommand();
                task.Status = Entity.TaskStatus.AGVExecution;
                db.Default.Updateable(task).ExecuteCommand();
                task.AddWCS_TASK_DTL(db, obj.Entity.Code, "AGV", "任务已下发AGV");
            });
        }

        public override bool Select(Device dev)
        {
            //return dev.Code == "1026";
            return dev.HasFlag(DeviceFlags.二楼出库口);
        }
    }
}
