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.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)
        {
            obj.入库站点是否被禁止();
            if (obj.Data.VoucherNo != obj.Data2.VoucherNo)
            {
                World.Log($"凭证号不一致,DB520:{obj.Data.VoucherNo}-DB521:{obj.Data2.VoucherNo}");
                return;
            }

            if (obj.Data3.Status.HasFlag(StationStatus.Run))
            {
                World.Log("设备运行中");
                return;
            }

            if (obj.Data3.Status.HasFlag(StationStatus.PH_Status) && obj.Data2.Request == 0)
            {
                World.Log("有光电无请求");
                return;
            }

            if (!obj.Data3.Status.HasFlag(StationStatus.PH_Status) && obj.Data2.Request == 1)
            {
                World.Log("无光电有请求");
                return;
            }

            if (!obj.Data3.Status.HasFlag(StationStatus.OT_Status))
            {
                World.Log("站台货物信息与实际占用不一致");
                return;
            }

            if (!obj.Data3.Status.HasFlag(StationStatus.PH_Status))
            {
                World.Log("无光电");
                return;
            }

            if (obj.Data2.Request != 1)
            {
                World.Log("无请求");
                return;
            }

            WCS_TaskInfo task = null;//处理完成的任务
            try
            {
                string barcode = "TPB";
                var palletType = PalletType.PalletNo09;
                //if (obj.Entity.Code is "2527" or "2727" or "2927" or "3127" or "3327" or "3527")
                //{
                //    palletType = PalletType.Pallet09;
                //    barcode = "TPA";
                //}

                SqlSugarHelper.Do(_db =>
                {
                    var db = _db.Default;
                    var isTask = db.Queryable<WCS_TaskInfo>().NoLock().Any(v => v.BarCode.Contains(barcode) && v.AddrFrom == obj.Entity.Code && v.Type == TaskType.EnterDepot);
                    //验证是否有对应的任务
                    if (!isTask)
                    {
                        var res = WmsApi.OneFloorWorkerBuildEmptyPalletsStock(new OneFloorWorkerBuildEmptyPalletsStockRequest()
                        {
                            PalletCode = barcode,
                            StartLoc = obj.Entity.Code,
                            PalletType = palletType,
                            Height = 2
                        });
                        if (res.ResCode != ResponseStatusCodeEnum.Sucess)
                        {
                            throw new KnownException(res.ResMsg, LogLevelEnum.High);
                        }
                        if (res.ResCode == WebApi.Models.WMS.Response.ResponseStatusCodeEnum.Sucess) return;
                    }
                    //找到对应的任务
                    var taskInfo = db.Queryable<WCS_TaskInfo>().UpdLock().First(v => v.BarCode.Contains(barcode) && v.AddrFrom == obj.Entity.Code && v.Type == TaskType.EnterDepot);
                    if (taskInfo.Status == Entity.TaskStatus.WaitingToExecute)
                    {
                        var tunnel = obj.Entity.Targets.FirstOrDefault(v => v.HasFlag(DeviceFlags.巷道));
                        //开始对任务进行处理
                        taskInfo.Status = Entity.TaskStatus.ConveyorExecution;
                        taskInfo.StartTime = DateTime.Now;
                        taskInfo.SrmStation = taskInfo.AddrFrom;
                        taskInfo.LastInteractionPoint = obj.Entity.Code;
                        taskInfo.Tunnel = tunnel.Code;
                        taskInfo.Height = 2;
                        taskInfo.Device = obj.Entity.Code switch
                        {
                            "2527" => "SRM1",
                            "2528" => "SRM1",
                            "2727" => "SRM2",
                            "2728" => "SRM2",
                            "2927" => "SRM3",
                            "2928" => "SRM3",
                            "3127" => "SRM4",
                            "3128" => "SRM4",
                            "3327" => "SRM5",
                            "3328" => "SRM5",
                            "3527" => "SRM6",
                            "3528" => "SRM6",
                            _ => taskInfo.Device
                        };
                        db.UpdateableRowLock(taskInfo).UpdateColumns(x => new { x.Status, x.StartTime, x.SrmStation, x.LastInteractionPoint, x.Tunnel, x.Height, x.Device }).ExecuteCommand();
                        taskInfo.AddWCS_TASK_DTL(db, obj.Entity.Code, "开始执行入库任务");
                        task = taskInfo;
                    }
                    else
                    {
                        World.Log($"未找到对应的任务{taskInfo}");
                        return;
                    }
                });
            }
            catch (Exception ex)
            {
                throw new KnownException(ex.Message, LogLevelEnum.High);
            }
            if (task == null) return;

            World.Log($"任务处理:开始-DB520[{obj.Data.TaskNumber}]-[{obj.Data.VoucherNo}]-DB521[{obj.Data2.TaskNumber}]-[{obj.Data2.VoucherNo}]");
            obj.Data.TaskNumber = task.ID;
            obj.Data.VoucherNo++;
            World.Log($"任务处理:结束-DB520[{obj.Data.TaskNumber}]-[{obj.Data.VoucherNo}]-DB521[{obj.Data2.TaskNumber}]-[{obj.Data2.VoucherNo}]");
        }

        public override bool Select(Device dev)
        {
            return dev.HasFlag(Extensions.DeviceFlags.一楼叠盘机);
        }
    }
}
