using ServiceCenter.Extensions;
using ServiceCenter.Logs;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.Entity.Protocol.Station;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.Worlds;
using TaskStatus = WCS.Entity.TaskStatus;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    ///  桁架分流点
    /// </summary>
    [BelongTo(typeof(SortingBranchWorld))]
    [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.Data.VoucherNo != obj.Data2.VoucherNo) throw new KnownException($"凭证号不一致,DB520:{obj.Data.VoucherNo}-DB521:{obj.Data2.VoucherNo}", LogLevelEnum.High);
            if (obj.Data3.Status.HasFlag(StationStatus.Run)) throw new KnownException("设备运行中", LogLevelEnum.Low);
            if (!obj.Data3.Status.HasFlag(StationStatus.OT_Status)) throw new KnownException("站台货物信息与实际占用不一致", LogLevelEnum.Low);
            if (obj.Data2.Request != 1) throw new KnownException("无请求", LogLevelEnum.Mid);

            var db = new SqlSugarHelper();
            var taskInfo = db.Default.Queryable<WCS_TaskInfo>().First(v => v.ID == obj.Data2.TaskNumber && v.Status == TaskStatus.FinishOfShunt) ?? throw new KnownException("未找到对应的WCS任务", LogLevelEnum.Mid);

            obj.Data.TaskNumber = obj.Data2.TaskNumber;
            obj.Data.GoodsStart = obj.Entity.Code.ToShort();
            obj.Data.GoodsEnd = taskInfo.AddrNext.ToShort();
            obj.Data.VoucherNo++;
            World.Log($"执行记录:任务号[{obj.Data2.TaskNumber}][{obj.Data.VoucherNo}]");
        }

        public override bool Select(Device dev)
        {
            return dev.HasFlag(Extensions.DeviceFlags.桁架分流点);
        }
    }
}
