using ServiceCenter.Extensions;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.Entity.Protocol.Station;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.WebApi.Models.WMS.Request;
using WCS.WorkEngineering.Worlds;
using DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    ///  二楼拆盘机自动补空托盘组
    /// </summary>
    [BelongTo(typeof(MainWorld))]
    [Description("二楼拆盘机自动补空托盘组")]
    public class 二楼拆盘机自动补空托盘组 : DeviceSystem<Device<IStation520, IStation521, IStation523>>
    {
        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        public override void Do(Device<IStation520, IStation521, IStation523> obj)
        {
            // 拆盘机没有光电
            if (obj.Data3.Status1.HasFlag(StationStatus1.RES14)) return;
            var tunnel = obj.Entity.Sources.Where(x => x.HasFlag(DeviceFlags.输送机)) //堆垛机取货点设备
                .SelectMany(x => x.Sources)
                .FirstOrDefault(x => x.HasFlag(DeviceFlags.巷道));
            SqlSugarHelper.Do(_db =>
            {
                var db = _db.Default;

                //验证是否有对应的任务
                if (!db.Queryable<WCS_TaskInfo>().Any(v => v.AddrTo == obj.Entity.Code))
                {
                    var res = WmsApi.ApplyEmptyPalletGroupOutStorage(obj.Entity.Code, tunnel.Code.GetLastDigit(), obj.Entity.HasFlag(DeviceFlags.拆盘机09) ? PalletType.Pallet09 : PalletType.PalletNo09);
                }
            });
        }

        public override bool Select(Device dev)
        {
            return dev.HasFlag(DeviceFlags.拆盘机09) || dev.HasFlag(DeviceFlags.拆盘机非09);
        }
    }
}
