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.Entity.Protocol.Truss;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.Worlds;
using DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;
using TaskStatus = WCS.Entity.TaskStatus;

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

        

        public override void Do(Device<IStation520, IStation521, IStation523, ITruss530, ITruss531> obj)
        {
            if (!obj.Data5.CmdType.HasFlag(TrussCmdType.End) && !obj.Data4.CmdType.HasFlag(TrussCmdType.End1 | TrussCmdType.Two) && obj.Data4.CmdType != 0) obj.Data4.CmdType = 0;
            if (!obj.Data3.Status.HasFlag(StationStatus.PH_Status)) return;
            if (!obj.Data5.CmdType.HasFlag(TrussCmdType.End)) return;
            if (!obj.Data5.CmdType.HasFlag(TrussCmdType.End1))
            {
                if (obj.Data5.MaxQuantity != obj.Data5.Quantity || obj.Data5.Quantity == 0 || obj.Data5.MaxQuantity == 0) return;
            }
            WCS_TaskInfo task = null;
            //找到对应的码垛数据
            SqlSugarHelper.Do(_db =>
            {
                var db = _db.Default;
                var palletizing = db.Queryable<WCS_Palletizing>().Single(x => x.PalletizingStation == obj.Entity.Code && !x.Finish);

                var TaskNoList = obj.Data5.GetTaskNoList().Where(x => x > 0).ToList();
                var taskList = db.Queryable<WCS_TaskInfo>().Where(x => TaskNoList.Contains(x.ID)).ToList();
                var taskCodes = taskList.Select(x => x.BarCode).ToList();
                if (!obj.Data5.CmdType.HasFlag(TrussCmdType.End1))
                {
                    if (TaskNoList.Count == 0)
                    {
                        var taskAny = db.Queryable<WCS_TaskInfo>().NoLock().Single(x =>  x.Type == TaskType.EnterDepot && x.Status == TaskStatus.ConveyorExecution && x.BusType == "码垛入库" && x.AddrFrom == obj.Entity.Code);
                        //针对断电写入信号失败的情况
                        if (taskAny != null && obj.Data.TaskNumber != taskAny.ID)
                        {
                            obj.Data.TaskNumber = taskAny.ID;
                            obj.Data.GoodsStart = obj.Entity.Code.ToShort();
                            obj.Data.GoodsEnd = taskAny.AddrNext.ToShort();
                            obj.Data4.CmdType = TrussCmdType.End;
                        }
                        return;
                    }
                    
                    if (taskList.Count != TaskNoList.Count)
                    {
                        var taskIn = db.Queryable<WCS_TaskInfo>().NoLock().Single(x => x.BarCode == palletizing.PalleCode && x.Type == TaskType.EnterDepot && x.Status < TaskStatus.Finish);
                        if (taskIn == null)
                        {
                            WmsApi.ForceFinishBingPallet(palletizing.PalleCode, taskCodes, taskList.FirstOrDefault().WarehouseCode, obj.Entity.Code);
                            return;
                        }                       
                    }
                    //throw new KnownException($"任务数量不一致!,请检查托盘任务信息", LogLevelEnum.Mid);
                }
                var taskInfo = db.Queryable<WCS_TaskInfo>().Single(x => x.BarCode == palletizing.PalleCode && x.Type == TaskType.EnterDepot && x.Status < TaskStatus.Finish);
                if (taskInfo == null)
                {
                    if (obj.Data5.CmdType.HasFlag(TrussCmdType.Two)) WmsApi.SecondaryBingPallet(palletizing.PalleCode, taskCodes, taskList.FirstOrDefault().WarehouseCode, obj.Entity.Code);
                    else if (obj.Data5.CmdType.HasFlag(TrussCmdType.End1)) WmsApi.ForceFinishBingPallet(palletizing.PalleCode, taskCodes, taskList.FirstOrDefault().WarehouseCode, obj.Entity.Code);
                    else WmsApi.FinishBingPallet(palletizing.PalleCode, taskCodes, taskList.FirstOrDefault().WarehouseCode, obj.Entity.Code);
                    return;
                }

                if (taskInfo.Status != TaskStatus.WaitingToExecute)
                {
                    if (taskInfo.Status == TaskStatus.NewBuild) throw new KnownException($"等待入库任务{taskInfo.ID}初始化完成", LogLevelEnum.Low);
                    return;
                }

                foreach (var x in taskList)
                {
                    x.Status = TaskStatus.Finish;
                    x.EndTime = DateTime.Now;
                    db.UpdateableRowLock(x).UpdateColumns(x => new { x.Status, x.EndTime }).ExecuteCommand();
                    x.AddWCS_TASK_DTL(db, obj.Entity.Code, "任务结束");
                }

                palletizing.Finish = true;
                palletizing.isItHalf = obj.Data5.CmdType.HasFlag(TrussCmdType.Two);
                if (palletizing.isItHalf)
                {
                    palletizing.TaskId = taskInfo.ID; //如果是半托入库，需要把绑定的任务切换成入库任务
                }
                db.UpdateableRowLock(palletizing).UpdateColumns(x => new { x.Finish, x.isItHalf, x.TaskId }).ExecuteCommand();
                taskInfo.Status = TaskStatus.ConveyorExecution;
                db.UpdateableRowLock(taskInfo).UpdateColumns(x => new { x.Status }).ExecuteCommand();
                taskInfo.AddWCS_TASK_DTL(db, obj.Entity.Code, $"桁架码垛结束处理完成");
                task = taskInfo;
            });
            if (task == null) return;
            obj.Data.TaskNumber = task.ID;
            obj.Data.GoodsStart = obj.Entity.Code.ToShort();
            obj.Data.GoodsEnd = task.AddrNext.ToShort();
            obj.Data4.CmdType = TrussCmdType.End;
        }

        public override bool Select(Device dev)
        {
            var devCodes = new List<string>() { "1670", "1671", "1715", "1716", "1685", "1686" };
            return dev.HasFlag(DeviceFlags.桁架码垛位) || devCodes.Contains(dev.Code);
        }
    }
}
