using PlcSiemens.Core.Extension;
using ServiceCenter.Extensions;
using ServiceCenter.Logs;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.Entity.Protocol.BCR;
using WCS.Entity.Protocol.Station;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.WebApi.Models.WMS.Request;
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, IStation91, IBCR81>>
    {
        protected override bool ParallelDo => true;

        public override void Do(Device<IStation520, IStation521, IStation523, IStation91, IBCR81> 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.Data2.Request != 1.ToShort())
            {
                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
            {
                //获取托盘条码
                var barcode = obj.Data5.GetBCRCode();
                if (barcode.IsNullOrWhiteSpace())
                {
                    World.Log("扫码失败，内容为空", LogLevelEnum.Mid);
                    return;
                }
                else if (!barcode.Contains("TPB"))
                {
                    World.Log($"扫码异常{barcode}，请检查扫码器", LogLevelEnum.Mid);
                    return;
                }
                SqlSugarHelper.Do(_db =>
                {
                    var db = _db.Default;

                    //var barcode = "TAP00001";
                    //验证是否有对应的任务

                    if (obj.Data4.Length == 2)
                    {
                        if (!db.Queryable<WCS_TaskInfo>().Any(v => v.BarCode == barcode && v.Type == TaskType.EnterDepot && v.Status < Entity.TaskStatus.Finish))
                        {
                            var palletType = PalletType.Pallet09;
                            if (barcode.Contains("TPB")) palletType = PalletType.PalletNo09;

                            var res = WmsApi.OneFloorWorkerBuildEmptyPalletsStock(new OneFloorWorkerBuildEmptyPalletsStockRequest()
                            {
                                PalletCode = barcode,
                                StartLoc = obj.Entity.Code,
                                PalletType = palletType,
                                Height = 2
                            });
                            if (res.ResCode == WebApi.Models.WMS.Response.ResponseStatusCodeEnum.Sucess) return;
                        }
                        //找到对应的任务
                        var taskInfo = db.Queryable<WCS_TaskInfo>().First(v => v.BarCode == barcode && v.Type == TaskType.EnterDepot && v.Status < Entity.TaskStatus.Finish);
                        if (taskInfo.Status != Entity.TaskStatus.WaitingToExecute) return;
                        {
                            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
                            {
                                "2532" => "SRM1",
                                "2732" => "SRM2",
                                "2932" => "SRM3",
                                "3132" => "SRM4",
                                "3332" => "SRM5",
                                "3532" => "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
                    {
                        var taskInfo = db.Queryable<WCS_TaskInfo>().Where(v => v.BarCode == barcode && v.Type == TaskType.EnterDepot).OrderByDescending(x => x.AddTime).First();
                        if (taskInfo == null)
                        {
                            World.Log($"条码{barcode}未组盘，请联系生产创建入库任务！！！！", LogLevelEnum.High);
                            return;
                        }
                        if (taskInfo is not { Status: Entity.TaskStatus.NewBuild, BusType: "人工满托入库" }) return;
                        {
                            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 = 1;
                            taskInfo.Device = obj.Entity.Code switch
                            {
                                "2532" => "SRM1",
                                "2732" => "SRM2",
                                "2932" => "SRM3",
                                "3132" => "SRM4",
                                "3332" => "SRM5",
                                "3532" => "SRM6",
                                _ => taskInfo.Device
                            };
                            taskInfo.WarehouseCode = obj.Entity.Code switch
                            {
                                "2532" => "1N",
                                "2732" => "1S",
                                "2932" => "2N",
                                "3132" => "2S",
                                "3332" => "3N",
                                "3532" => "3S",
                                _ => taskInfo.Device
                            };
                            db.UpdateableRowLock(taskInfo).UpdateColumns(x => new { x.Status, x.StartTime, x.SrmStation, x.LastInteractionPoint, x.Tunnel, x.Height, x.Device, x.WarehouseCode }).ExecuteCommand();
                            taskInfo.AddWCS_TASK_DTL(db, obj.Entity.Code, "开始执行入库任务");
                            task = taskInfo;
                        }
                    }
                });
            }
            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.Data2.Request}]");
            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.Code is "2532" or "2732" or "2932" or "3132" or "3332" or "3532";
            //return dev.HasFlag(Extensions.DeviceFlags.一楼扫码);
        }
    }
}