using ServiceCenter.Redis;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.Service;
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)
        {
            var key = $"WCS:Lock:{obj.Entity.Code}";
            try
            {

                if (RedisHub.Default.Get(key) != null)
                {
                    throw new KnownException($"[{obj.Entity.Code}]--触发并发管控", LogLevelEnum.High);
                }
                RedisHub.Default.Set(key, obj.Entity.Code);
                if (!obj.Data3.Status.HasFlag(Entity.Protocol.Station.StatusEunm.PH_Status) && !obj.Data3.Status.HasFlag(Entity.Protocol.Station.StatusEunm.OT_Status))
                {
                    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);
                }
            }
            finally
            {
                RedisHub.Default.Del(key);
            }
        }

        public override bool Select(Device dev)
        {
            return dev.HasFlag(DeviceFlags.一楼出库口);
        }
    }
}
