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

namespace WCS.WorkEngineering.Systems.桁架码垛
{
    /// <summary>
    ///  二次码垛任务到RGV取货位处理
    /// </summary>
    [BelongTo(typeof(SortingPalletizingWorld))]
    [Description("二次码垛任务到RGV取货位处理")]
    public class 二次码垛任务到RGV取货位处理 : DeviceSystem<Device<IStation520, IStation521, IStation523, ITruss530>>
    {
        protected override bool ParallelDo => true;

        public override void Do(Device<IStation520, IStation521, IStation523, ITruss530> obj)
        {
            if (!obj.Data3.Status.HasFlag(StationStatus.Auto)) return;
            if (!obj.Data3.Status.HasFlag(StationStatus.PH_Status)) return;
            if (!obj.Data3.Status.HasFlag(StationStatus.OT_Status)) return;
            if (obj.Data2.Request != 1) return;

            var addNext = 1;
            WCS_Palletizing palletizing = null;
            WCS_TaskInfo task = null;

            SqlSugarHelper.Do(_db =>
            {
                var db = _db.Default;
                var soDev = obj.Entity.Sources.First();
                var taskInfo = db.Queryable<WCS_TaskInfo>().Where(x => x.SrmStation == soDev.Code && x.Status == TaskStatus.StackerCompleted).OrderBy(x => x.EditTime).First();
                if (taskInfo == null) return;
                var pall = db.Queryable<WCS_Palletizing>().RowLock().Includes(x => x.Locs).First(x => x.TaskId == taskInfo.ID && !x.Finish);
                if (pall == null) return;
                taskInfo.Status = TaskStatus.Finish;
                taskInfo.EditTime = DateTime.Now;
                taskInfo.EndTime = DateTime.Now;
                db.UpdateableRowLock(taskInfo).UpdateColumns(x => new { x.Status, x.EditTime, x.EndTime }).ExecuteCommand();
                taskInfo.AddWCS_TASK_DTL(db, obj.Entity.Code, "二次码垛出库任务完成");
                addNext = pall.PalletizingStation.ToShort();
                palletizing = pall;
                task = taskInfo;
            });
            if (palletizing == null || task == null) return;
            obj.Data.TaskNumber = palletizing.Id;
            obj.Data.GoodsStart = obj.Entity.Code.ToShort();
            obj.Data.GoodsEnd = 0;
            obj.Data4.Type = 1;
            obj.Data4.MaxQuantity = palletizing.CountQty.ToShort();
            obj.Data4.Quantity = palletizing.Locs.Count(x => x.Finish).ToShort();
            obj.Data4.VoucherNo++;
            obj.Data.VoucherNo++;
        }

        public override bool Select(Device dev)
        {
            return dev.Code is "1606" or "1616" or "1626" or "1636" or "1646" or "1656";
        }
    }
}
