using ServiceCenter.Extensions;
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.WebApi.Models.WMS.Request;
using WCS.WorkEngineering.WebApi.Models.WMS.Response;
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;

        

        public override void Do(Device<IStation520, IStation521, IStation523> obj)
        {
            // 拆盘机没有光电
            if (obj.Data3.Status1.HasFlag(StationStatus1.RES14) || obj.Data3.Status.HasFlag(StationStatus.PH_Status)) return;
            var tunnel = obj.Entity.Sources.Where(x => x.HasFlag(DeviceFlags.输送机)) //堆垛机取货点设备
                .SelectMany(x => x.Sources)
                .FirstOrDefault(x => x.HasFlag(DeviceFlags.巷道));
            if (tunnel == null)
            {
                World.Log($"{obj.Entity.Code}找不到对应放货点");
                return;
            }
            SqlSugarHelper.Do(_db =>
            {
                var db = _db.Default;

                //验证是否有对应的任务
                if (db.Queryable<WCS_TaskInfo>().NoLock().Any(v => v.AddrTo == obj.Entity.Code && v.Status < Entity.TaskStatus.Finish)) return;
                var res = WmsApi.ApplyEmptyPalletGroupOutStorage(obj.Entity.Code, tunnel.Code.GetLastDigit(), obj.Entity.HasFlag(DeviceFlags.拆盘机) ? PalletType.Pallet09 : PalletType.PalletNo09);
                if (res.ResCode == ResponseStatusCodeEnum.Sucess) return;
                World.Log(res.ResMsg);
            });
        }

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