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 DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    /// 出库站台交互
    /// </summary>
    [BelongTo(typeof(MainWorld))]
    [Description("出站站点交互系统")]
    public class OutboundSiteInteractionSystems : DeviceSystem<Station>
    {
        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        public override void Do(Station obj)
        {
            var IsThereATask = false; //无任务

            #region 判断站点是否有任务

            //光电有货或有任务有货
            if (obj.Data3.Status.HasFlag(Entity.Protocol.Station.StatusEunm.PH_Status) || obj.Data3.Status.HasFlag(Entity.Protocol.Station.StatusEunm.OT_Status))
            {
                if (!obj.Data3.Status.HasFlag(Entity.Protocol.Station.StatusEunm.PH_Status))
                    IsThereATask = true;
            }

            #endregion 判断站点是否有任务

            if (IsThereATask)
            {
            }
            else
            {
                if (obj.Entity.HasFlag(DeviceFlags.一楼出库口))
                {
                    var any = false;
                    SqlSugarHelper.Do(db =>
                    {
                        any = db.Default.Queryable<WCS_TaskInfo>().Any(v => v.AddrTo == obj.Entity.Code && v.Status <= Entity.TaskStatus.AGVExecution);
                    });
                    if (!any) WmsApi.ApplyStockOutTask(obj.Entity.Code);
                }
            }
        }

        public override bool Select(Device dev)
        {
            //return dev.Code == "1016";
            return dev.HasFlag(DeviceFlags.巷道口) && dev.HasFlag(DeviceFlags.出库);
        }
    }
}
