using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Library;
using Khd.Core.Library.Mapper;
using Khd.Core.Plc.S7;
using Khd.Core.Wcs.Global;
using Masuit.Tools;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Z.EntityFramework.Plus;

namespace Khd.Core.Wcs.Wcs
{
    /// <summary>
    /// 一楼线程（包括接驳位，提升机调度）
    /// </summary>
    public class FirstFloor
    {
        private readonly LoggerUtils _logger = new LoggerUtils();
        private readonly IHost _host;
        private readonly long F01 = 1;
        private readonly long T01 = 6;
        /// <summary>
        /// 一楼RFID 读
        /// </summary>
        private readonly BasePlcpoint RFID001;
        private readonly BasePlcpoint automatic;
        /// <summary>
        /// 到位信号 读
        /// </summary>
        private readonly BasePlcpoint linesignal01;
        /// <summary>
        /// 提升机流水号 读
        /// </summary>
        private readonly BasePlcpoint serialno06;
        /// <summary>
        /// 提升机状态 读
        /// </summary>
        private readonly BasePlcpoint equipstate06;
        /// <summary>
        /// 提升机任务状态 读
        /// </summary>
        private readonly BasePlcpoint hoistertrayin06;
        /// <summary>
        /// 提升机当前楼层 写
        /// </summary>
        private readonly BasePlcpoint currentfloor06;
        /// <summary>
        /// 提升机目的楼层 写
        /// </summary>
        private readonly BasePlcpoint targetfloor06;
        /// <summary>
        /// 提升机反馈流水号
        /// </summary>
        private readonly BasePlcpoint reserialno06;
        /// <summary>
        /// 提升机手自动状态
        /// </summary>
        private readonly BasePlcpoint hoisterStatus;
        /// <summary>
        /// 提升机到位信号 读
        /// </summary>
        private readonly BasePlcpoint mesClose;

        public FirstFloor(IHost host)
        {
            this._host = host;

            //一楼RFID 读
            this.RFID001 = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("FirstFloorLine") && t.plcpointNo.Contains("RFID001"));
            //到位信号 读
            this.linesignal01 = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("FirstFloorLine") && t.plcpointNo.Contains("linesignal01"));
            //一楼提升机流水号 读
            this.serialno06 = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("serialno06"));
            this.mesClose = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("mesclose"));
            this.automatic = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("automatic"));
            //一楼提升机状态 读
            this.equipstate06 = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("equipstate06"));
            //一楼提升机任务状态 读
            this.hoistertrayin06 = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("hoistertrayin06"));
            //一楼提升机当前楼层 写
            this.currentfloor06 = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("currentfloor06"));
            //一楼提升机目的楼层 写
            this.targetfloor06 = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("targetfloor06"));
            //一楼提升机到位信号 读
            this.reserialno06 = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("reserialno06"));
            //提升机手自动状态
            this.hoisterStatus = StaticData.BasePlcpointList.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("hoisterStatus"));
        }

        /// <summary>
        /// 启动上件扫描监听
        /// </summary>
        public void StartPoint()
        {
            Thread firstFloorLine = new(FirstFloorLine)//一楼接驳位线程
            {
                IsBackground = true,
                Name = "FirstFloorLine"
            };
            firstFloorLine.Start();

            Thread firstFloorHoister = new(FirstFloorHoister)//提升机
            {
                IsBackground = true,
                Name = "FirstFloorHoister"
            };
            firstFloorHoister.Start();

            Thread equipStatusThread = new Thread(EquipStatusLogic)//设备状态，1-5楼接驳位能不能送货，提升机和小车任务
            {
                IsBackground = true,
                Name = "EquipStatusThread"
            };
            equipStatusThread.Start();

            Console.WriteLine(DateTime.Now + ":一楼提升机线程启动成功");
            _logger.Info("一楼提升机线程启动成功");
        }

        private void EquipStatusLogic(object? obj)
        {
            using var scope = this._host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    for (int i = 1; i <= 5; i++)
                    {
                        BasePlcpoint basePlcpoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == $"linesignal0{i}");
                        var lineSignal = StaticData.PlcDic[0].Read(basePlcpoint.plcpointAddress);
                        if (lineSignal != null)
                        {
                            if (Convert.ToInt32(lineSignal) == 1)
                            {
                                BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == i);
                                if (baseEquip.equipStatus != 1)//不是忙碌状态，改为忙碌状态
                                {
                                    baseEquip.equipStatus = 1;
                                    dbContext.Update(baseEquip);
                                    dbContext.SaveChanges();
                                }
                                //else
                                //{
                                //    bool hasTask = dbContext.WcsTask.Where(t => t.endPointId == i || t.currPointId == i).Any();
                                //    if (!hasTask)
                                //    {
                                //        baseEquip.equipStatus = 0;
                                //        dbContext.Update(baseEquip);
                                //        dbContext.SaveChanges();
                                //    }
                                //}
                            }
                            else
                            {
                                BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == i);
                                bool hasCmd = dbContext.WcsCmd.Where(t => t.nextPointId == i || t.currPointId == i).Any();//小车任务
                                bool hasTask = dbContext.WcsTask.Where(t => (t.currPointId == i || t.endPointId == i) && t.taskStatus >= 1 && t.nextPointId == 6).Any();//提升机任务，有没有正在执行的往这个接驳位送的
                                if (!hasCmd || !hasTask)
                                {
                                    baseEquip.containerNo = null;
                                    baseEquip.equipStatus = 0;
                                    dbContext.Update(baseEquip);
                                    dbContext.SaveChanges();
                                }
                                else//接驳位改为忙碌状态
                                {
                                    baseEquip.containerNo = null;
                                    baseEquip.equipStatus = 1;
                                    dbContext.Update(baseEquip);
                                    dbContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex is PlcException)
                    {

                    }
                    else
                    {
                        _logger.Error(ex.Message + "\n" + ex.StackTrace);
                    }
                }

            }
        }

        private void CallEmpty()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            BasePlcpoint oneOutPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "oneOut");
            BasePlcpoint someOutPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "someOut");
            BaseEquip mdjEquip = StaticData.BaseEquip.First(t => t.objid == 40);
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    var linesignal = StaticData.PlcDic[0].Read(this.linesignal01.plcpointAddress);
                    int taskCount = dbContext.WcsTask.Where(t => t.nextPointId == 6 && t.taskStatus > 0 && t.endPointId == 1).Count();
                    int firstFloorCount = dbContext.WcsTask.Where(t => t.currPointId == 1).Count();
                    if (Convert.ToInt32(linesignal) == 0 && taskCount == 0 && firstFloorCount == 0)
                    {
                        bool canSend = dbContext.WcsTask.Where(t => t.floorNo == 1).Where(t => t.taskStatus > 0).Any();
                        if (!canSend)
                        {
                            WcsTaskManual? wcsTaskManual = dbContext.WcsTaskManual.Where(t => t.nextPointId == 40).FirstOrDefault();
                            if (wcsTaskManual != null)
                            {
                                if (wcsTaskManual.taskType == 53)
                                {
                                    StaticData.PlcDic[0].WriteToPoint(someOutPoint.plcpointAddress, "1", someOutPoint.plcpointLength.ToString());
                                    WcsTask wcsTask = CoreMapper.Map<WcsTask>(wcsTaskManual);
                                    wcsTask.createTime = DateTime.Now;
                                    wcsTask.createBy = "一楼接驳位线程";
                                    wcsTask.taskStatus = 0;
                                    wcsTask.useFlag = 1;
                                    wcsTask.isEmpty = "1";
                                    wcsTask.qty = mdjEquip.emptyCount;
                                    wcsTask.remark = "一楼创建入库任务";
                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                    mdjEquip.emptyCount = 0;
                                    dbContext.Update(mdjEquip);
                                    dbContext.Add(wcsTaskLog);
                                    dbContext.Add(wcsTask);
                                    dbContext.SaveChanges();
                                    _logger.Info("一楼接驳位线程：空托盘任务下发成功");
                                    Console.WriteLine(DateTime.Now + ":一楼接驳位线程：空托盘任务下发成功");
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex is PlcException)
                    {

                    }
                    else
                    {
                        _logger.Error(ex.Message + "\n" + ex.StackTrace);
                    }
                }
                Thread.Sleep(1000);
            }
        }

        public static bool ReadEmptyLocation()
        {
            var oneOutPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "oneOut");
            var someOutPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "someOut");
            var oneInPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "oneIn");
            var someInPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "someIn");
            var oneOutValue = StaticData.PlcDic[0].Read(oneOutPoint.plcpointAddress);
            var someOutValue = StaticData.PlcDic[0].Read(someOutPoint.plcpointAddress);
            var oneInValue = StaticData.PlcDic[0].Read(oneInPoint.plcpointAddress);
            var someInValue = StaticData.PlcDic[0].Read(someInPoint.plcpointAddress);
            if (oneOutValue != null && someOutValue != null && oneInValue != null && someInValue != null)
            {
                if (Convert.ToInt32(oneOutValue) == 0 && Convert.ToInt32(someOutValue) == 0 && Convert.ToInt32(oneInValue) == 0 && Convert.ToInt32(someInValue) == 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 启动一楼接驳位线程
        /// </summary>
        private void FirstFloorLine()
        {
            List<int?> Outtpyes = new() { 2, 4, 8, 6 };
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());//上次查出1，不加这行，数据库实际2，查出1
                    var RFID001Value = StaticData.PlcDic[0].ReadRFID(this.RFID001.plcpointAddress);  //一楼RFID 读
                    var linesignal01Value = StaticData.PlcDic[0].Read(this.linesignal01.plcpointAddress); //到位信号 读
                    //正常读到plc值
                    if (linesignal01Value != null && RFID001Value != null)
                    {
                        //正常托盘到位
                        BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 1);
                        if (Convert.ToInt32(linesignal01Value) == 1)
                        {
                            var wcsTasks = dbContext.WcsTask.ToList();
                            //判断task表里没有该rfid的未完成的入库
                            //信息，未下发去向
                            var task = wcsTasks.Where(t => t.IsDelete == 0 || t.IsDelete == null)
                                .Where(t => t.nextPointId == 1)
                                .OrderBy(t => t.createTime).FirstOrDefault();

                            if (task == null)
                            {
                                if (StaticData.BigContainerCodes.Contains(RFID001Value))
                                {
                                    var newTask = new WcsTask()
                                    {
                                        objid = StaticData.SnowId.NextId(),
                                        serialNo = SystemData.GetSerialNo(dbContext),
                                        equipmentNo = "F01",
                                        taskType = 5,
                                        taskStatus = 0,
                                        containerNo = RFID001Value,
                                        currPointId = F01,
                                        currPointNo = "TSJ_01",
                                        nextPointId = T01,
                                        nextPointNo = "TSJ_01",
                                        fromFloorNo = 1,
                                        floorNo = 4,
                                        useFlag = 1,
                                        createBy = "一楼接驳位",
                                        createTime = DateTime.Now,
                                        remark = "一楼创建入库任务"
                                    };
                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                    dbContext.Add(wcsTaskLog);
                                    dbContext.Add(newTask);
                                    dbContext.SaveChanges();
                                }
                                else
                                {
                                    var hasTask = wcsTasks.Where(t => t.containerNo == RFID001Value).Any();
                                    if (!hasTask)
                                    {
                                        //根据托盘号获取物料码
                                        var material = dbContext.MesBasePalletInfo.Where(t => t.palletInfoCode == RFID001Value).FirstOrDefault();
                                        WcsTaskLog? taskLog = dbContext.WcsTaskLog.Where(t => t.containerNo == RFID001Value).OrderByDescending(t => t.createTime).FirstOrDefault();

                                        if (material != null)
                                        {
                                            if (string.IsNullOrEmpty(material.materialBarcode))
                                            {
                                                continue;
                                            }
                                            bool hasBarInfo = dbContext.MesBaseBarcodeInfo.Where(t => t.palletInfoCode == RFID001Value && t.barcodeInfo == material.materialBarcode).Any();
                                            if (!hasBarInfo)
                                            {
                                                continue;
                                            }
                                            if (taskLog != null)
                                            {
                                                if (taskLog.materialBarcode == material.materialBarcode)
                                                {
                                                    if (baseEquip.containerNo == "0")
                                                    {
                                                        baseEquip.containerNo = null;
                                                        dbContext.Update(baseEquip);
                                                        dbContext.SaveChanges();
                                                        _logger.Info("一楼接驳位线程：托盘" + RFID001Value + "解绑信息更新成功");
                                                    }
                                                    else if (baseEquip.containerNo != RFID001Value)
                                                    {
                                                        baseEquip.containerNo = RFID001Value;
                                                        dbContext.Update(baseEquip);
                                                        dbContext.SaveChanges();
                                                        _logger.Info("一楼接驳位线程：托盘" + RFID001Value + "绑定信息更新成功");
                                                        Console.WriteLine(DateTime.Now + ":一楼接驳位线程：托盘" + RFID001Value + "绑定信息更新成功");
                                                        Thread.Sleep(3000);
                                                        continue;
                                                    }
                                                    else
                                                    {
                                                        Thread.Sleep(3000);
                                                        continue;
                                                    }
                                                }
                                            }

                                            var warehouseId = dbContext.WmsWarehouseMaterial.Where(t => t.storageType == "1" && t.storageId == material.materialId).FirstOrDefault()?.warehouseId;
                                            if (warehouseId != null)
                                            {
                                                var TargetFloor = dbContext.WmsBaseWarehouse.Where(t => t.warehouseId == warehouseId).FirstOrDefault();
                                                if (TargetFloor != null)
                                                {
                                                    //插入task表

                                                    var dic = StaticData.BaseDictionary.Where(t => t.dicKey == "TaskType" && t.agvType == "I" && t.dicField == TargetFloor.warehouseInstockType).FirstOrDefault();
                                                    if (dic != null)
                                                    {
                                                        var newTask = new WcsTask()
                                                        {
                                                            objid = StaticData.SnowId.NextId(),
                                                            serialNo = SystemData.GetSerialNo(dbContext),
                                                            equipmentNo = "F01",
                                                            taskType = Convert.ToInt32(dic.dicValue),
                                                            taskStatus = 0,
                                                            containerNo = RFID001Value,
                                                            materialBarcode = material.materialBarcode,
                                                            materialId = material.materialId,
                                                            qty = Convert.ToInt32(material.bindAmount),
                                                            currPointId = F01,
                                                            currPointNo = "TSJ_01",
                                                            nextPointId = T01,
                                                            nextPointNo = "TSJ_01",
                                                            endPointId = warehouseId,
                                                            fromFloorNo = 1,
                                                            floorNo = TargetFloor.warehouseFloor,
                                                            useFlag = 1,
                                                            createBy = "一楼接驳位",
                                                            createTime = DateTime.Now,
                                                            remark = "一楼创建入库任务"
                                                        };
                                                        WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                                        dbContext.Add(wcsTaskLog);
                                                        dbContext.Add(newTask);
                                                        dbContext.SaveChanges();
                                                    }
                                                }
                                            }
                                            else
                                            {  //TODO 物料未绑定仓库，添加报警

                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(task.containerNo))//人工调出
                                {
                                    if (task.useFlag == 1)
                                    {
                                        if (task.qty > 1)//多个托盘
                                        {
                                            if (task.endPointId != 1)
                                            {
                                                task.nextPointId = 6;
                                                dbContext.SaveChanges();
                                            }
                                        }
                                        else if (task.qty == 1)
                                        {
                                            if (task.endPointId != 1)
                                            {
                                                task.nextPointId = 6;
                                                task.containerNo = RFID001Value;
                                                dbContext.SaveChanges();
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.FirstOrDefault(t => t.palletInfoCode == RFID001Value);
                                    if (mesBasePalletInfo != null)
                                    {
                                        MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.Where(t => t.palletInfoCode == RFID001Value).FirstOrDefault();
                                        if (mesBaseBarcodeInfo != null)
                                        {
                                            mesBaseBarcodeInfo.palletInfoCode = null;
                                            dbContext.Update(mesBaseBarcodeInfo);
                                        }
                                        mesBasePalletInfo.bindAmount = null;
                                        mesBasePalletInfo.bindAmount = null;
                                        mesBasePalletInfo.materialBarcode = null;
                                        mesBasePalletInfo.materialCode = null;
                                        mesBasePalletInfo.materialId = null;
                                        mesBasePalletInfo.materialName = null;
                                        mesBasePalletInfo.updateBy = "WCS";
                                        mesBasePalletInfo.updateTime = DateTime.Now;
                                        dbContext.Update(mesBasePalletInfo);
                                        dbContext.Remove(task);
                                        dbContext.WcsTaskLog.Where(t => t.objid == task.objid).Update(t => new WcsTaskLog { taskStatus = 6 });
                                        dbContext.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex is PlcException)
                    {

                    }
                    else
                    {
                        _logger.Error(ex.Message + "\n" + ex.StackTrace);
                    }
                }
                Thread.Sleep(3000);
            }
        }

        /// <summary>
        /// 提升机线程
        /// </summary>
        private void FirstFloorHoister()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

            while (true)
            {
                using var transaction = dbContext.Database.BeginTransaction();
                try
                {
                    var mesCloseValue = StaticData.PlcDic[0].Read(this.mesClose.plcpointAddress);  //MES关闭状态 读
                    var serialno06Value = StaticData.PlcDic[0].Read(this.serialno06.plcpointAddress);  //提升机流水号 读
                    var equipstate06Value = StaticData.PlcDic[0].Read(this.equipstate06.plcpointAddress); //提升机状态 读
                    var hoisterTrayIn06Value = StaticData.PlcDic[0].Read(this.hoistertrayin06.plcpointAddress);      //提升机货物到位状态 读
                    var currentfloor06Value = StaticData.PlcDic[0].Read(this.currentfloor06.plcpointAddress);   //提升机当前楼层 读
                    var targetfloor06Value = StaticData.PlcDic[0].Read(this.targetfloor06.plcpointAddress);  //提升机目的楼层 写
                    var hoisterStatusValue = StaticData.PlcDic[0].Read(this.hoisterStatus.plcpointAddress);  //提升机目的楼层 写
                    var reserialno06 = StaticData.PlcDic[0].Read(this.reserialno06.plcpointAddress);  //反馈流水号
                    _logger.Info($"MES开启?{mesCloseValue},提升机自动状态?{hoisterStatusValue},提升机流水号?{serialno06Value},提升机状态?{equipstate06Value},提升机货物到位状态?{hoisterTrayIn06Value},提升机当前楼层?{currentfloor06Value},提升机目的楼层?{targetfloor06Value},反馈流水号?{reserialno06}");
                    if (mesCloseValue != null && hoisterStatusValue != null && Convert.ToInt32(hoisterStatusValue) == 1 && Convert.ToInt32(mesCloseValue) == 0)
                    {
                        //正常读到plc值
                        if (targetfloor06Value != null && serialno06Value != null && equipstate06Value != null && currentfloor06Value != null && reserialno06 != null && hoisterTrayIn06Value != null)
                        {
                            //提升机空闲
                            if (Convert.ToInt32(equipstate06Value) == 0)
                            {
                                dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                                var wcsTasks = dbContext.WcsTask.Where(t => t.nextPointId == T01 && t.taskStatus < 5).OrderBy(t => t.createTime).ToList();
                                foreach (var wcsTask in wcsTasks)
                                {
                                    _logger.Info($"当前任务?{wcsTask.ToJsonString()}");
                                    bool hasTask = dbContext.WcsTask.Where(t => t.endPointId == wcsTask.endPointId && t.objid != wcsTask.objid && t.nextPointId != 6).Any();
                                    if (!hasTask)
                                    {
                                        wcsTask.serialNo ??= SystemData.GetSerialNo(dbContext);
                                        if (wcsTasks.Where(t => t.taskStatus > 0).Where(t => t.objid != wcsTask.objid).Any())
                                        {
                                            _logger.Info("提升机线程：有其他任务正在执行，跳过当前任务");
                                            continue;
                                        }
                                        BaseEquip lineEquip = dbContext.BaseEquip.First(t => t.objid == wcsTask.floorNo);
                                        if (wcsTask.taskStatus == 0 && Convert.ToInt32(hoisterTrayIn06Value) == 0)//创建状态，并且里面没有货物
                                        {
                                            if (lineEquip.equipStatus == 1)
                                            {
                                                _logger.Info("提升机线程：" + wcsTask.floorNo + "楼接驳位有AGV任务，跳过当前任务");
                                                continue;
                                            }

                                            BasePlcpoint floorPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "RFID00" + wcsTask.fromFloorNo);
                                            string? rfid = StaticData.PlcDic[0].ReadRFID(floorPoint.plcpointAddress);
                                            _logger.Info($"{wcsTask.fromFloorNo}楼RFID?{rfid}，任务RFID{wcsTask.containerNo}");
                                            if (wcsTask.containerNo == rfid || (string.IsNullOrEmpty(wcsTask.containerNo) && wcsTask.qty > 1))
                                            {
                                                if (Convert.ToInt32(currentfloor06Value) == wcsTask.fromFloorNo)//当前楼层和起始楼层一致
                                                {
                                                    wcsTask.taskStatus = 2;
                                                    wcsTask.updateBy = "提升机线程";
                                                    wcsTask.updateTime = DateTime.Now;
                                                    wcsTask.remark = "提升机任务执行中";
                                                    BasePlcpoint basePlcpoint = StaticData.BasePlcpointList.First(t => t.floorNo == wcsTask.fromFloorNo && t.plcpointNo.Contains("wcsrun"));
                                                    dbContext.Update(wcsTask);
                                                    dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(t => new WcsTaskLog { taskStatus = 2, updateBy = "提升机线程", updateTime = DateTime.Now, remark = "提升机任务执行中" });
                                                    lineEquip.equipStatus = 1;
                                                    dbContext.Update(lineEquip);
                                                    dbContext.SaveChanges();
                                                    StaticData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "1", basePlcpoint.plcpointLength.ToString());
                                                    StaticData.PlcDic[0].WriteToPoint(this.serialno06.plcpointAddress, wcsTask.serialNo.ToString(), this.serialno06.plcpointLength.ToString());
                                                    Console.WriteLine(DateTime.Now + ":提升机下发" + wcsTask.fromFloorNo + "楼入库指令");
                                                    _logger.Info("提升机下发" + wcsTask.fromFloorNo + "楼入库指令");
                                                    transaction.Commit();
                                                }
                                                else//当前楼层和起始楼层不一致
                                                {
                                                    wcsTask.taskStatus = 1;
                                                    wcsTask.updateBy = "提升机线程";
                                                    wcsTask.updateTime = DateTime.Now;
                                                    wcsTask.remark = "提升机任务执行中";
                                                    dbContext.Update(wcsTask);
                                                    dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(t => new WcsTaskLog { taskStatus = 1, updateBy = "提升机线程", updateTime = DateTime.Now, remark = "提升机任务执行中" });
                                                    lineEquip.equipStatus = 1;
                                                    dbContext.Update(lineEquip);
                                                    dbContext.SaveChanges();
                                                    StaticData.PlcDic[0].WriteToPoint(this.targetfloor06.plcpointAddress, wcsTask.fromFloorNo.ToString(), this.targetfloor06.plcpointLength.ToString());//目的地楼层
                                                    StaticData.PlcDic[0].WriteToPoint(this.serialno06.plcpointAddress, wcsTask.serialNo.ToString(), this.serialno06.plcpointLength.ToString());
                                                    Console.WriteLine(DateTime.Now + ":提升机下发去往" + wcsTask.fromFloorNo + "楼指令");
                                                    _logger.Info("提升机下发去往" + wcsTask.fromFloorNo + "楼指令");
                                                    transaction.Commit();
                                                }
                                            }
                                        }
                                        if (wcsTask.taskStatus == 1 && Convert.ToInt32(reserialno06) == wcsTask.serialNo)
                                        {
                                            BasePlcpoint floorPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "RFID00" + wcsTask.fromFloorNo);
                                            string? rfid = StaticData.PlcDic[0].ReadRFID(floorPoint.plcpointAddress);
                                            _logger.Info($"{wcsTask.fromFloorNo}楼RFID?{rfid}，任务RFID{wcsTask.containerNo}");
                                            if (wcsTask.containerNo == rfid || (string.IsNullOrEmpty(wcsTask.containerNo) && wcsTask.qty > 1))
                                            {
                                                if (Convert.ToInt32(currentfloor06Value) == wcsTask.fromFloorNo)//提升机当前楼层为初始地楼层
                                                {
                                                    wcsTask.taskStatus = 2;
                                                    wcsTask.updateBy = "提升机线程";
                                                    wcsTask.updateTime = DateTime.Now;
                                                    wcsTask.remark = "提升机任务执行中";
                                                    BasePlcpoint basePlcpoint = StaticData.BasePlcpointList.First(t => t.floorNo == wcsTask.fromFloorNo && t.plcpointNo.Contains("wcsrun"));
                                                    dbContext.Update(wcsTask);
                                                    dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(t => new WcsTaskLog { taskStatus = 2, updateBy = "提升机线程", updateTime = DateTime.Now, remark = "提升机任务执行中" });
                                                    dbContext.SaveChanges();
                                                    StaticData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "1", basePlcpoint.plcpointLength.ToString());
                                                    StaticData.PlcDic[0].WriteToPoint(this.serialno06.plcpointAddress, wcsTask.serialNo.ToString(), this.serialno06.plcpointLength.ToString());
                                                    Console.WriteLine(DateTime.Now + ":提升机下发" + wcsTask.fromFloorNo + "楼入库指令");
                                                    _logger.Info("提升机下发" + wcsTask.fromFloorNo + "楼入库指令");
                                                    transaction.Commit();
                                                }
                                            }
                                        }
                                        if (wcsTask.taskStatus == 2 && Convert.ToInt32(reserialno06) == wcsTask.serialNo)
                                        {
                                            if (Convert.ToInt32(hoisterTrayIn06Value) == 1)//托盘已经进提升机
                                            {
                                                wcsTask.taskStatus = 3;
                                                wcsTask.updateBy = "提升机线程";
                                                wcsTask.updateTime = DateTime.Now;
                                                wcsTask.remark = "提升机任务执行完成";
                                                dbContext.Update(wcsTask);
                                                dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(t => new WcsTaskLog { taskStatus = 3, updateBy = "提升机线程", updateTime = DateTime.Now, remark = "提升机任务执行完成" });
                                                dbContext.SaveChanges();
                                                StaticData.PlcDic[0].WriteToPoint(this.targetfloor06.plcpointAddress, wcsTask.floorNo.ToString(), this.targetfloor06.plcpointLength.ToString());//目的地楼层
                                                Console.WriteLine(DateTime.Now + ":提升机下发去往" + wcsTask.floorNo + "楼目的地指令");
                                                _logger.Info("提升机下发去往" + wcsTask.floorNo + "楼目的地指令");
                                                transaction.Commit();
                                            }
                                        }
                                        if (wcsTask.taskStatus == 3 && Convert.ToInt32(currentfloor06Value) == wcsTask.floorNo && Convert.ToInt32(reserialno06) == wcsTask.serialNo)//任务状态为3，且当前楼层为任务的目的楼层
                                        {
                                            if (wcsTask.floorNo == 1)//目的楼层是1
                                            {
                                                bool emptyStatus = ReadEmptyLocation();
                                                _logger.Info($"一楼托盘库是否有任务?{emptyStatus}");
                                                if (emptyStatus)//托盘库是否有任务，没有任务返回true
                                                {
                                                    var linesignal = StaticData.PlcDic[0].Read(StaticData.BasePlcpointList.First(t => t.plcpointNo == $"linesignal0{wcsTask.floorNo}").plcpointAddress);
                                                    _logger.Info($"一楼接驳位外侧是否有东西?{linesignal}");
                                                    if (linesignal != null && Convert.ToInt32(linesignal) == 0)//接驳位外侧没有东西
                                                    {
                                                        BasePlcpoint clearPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == $"clear0{wcsTask.floorNo}");
                                                        var clearValue = StaticData.PlcDic[0].Read(clearPoint.plcpointAddress);
                                                        if (clearPoint != null && Convert.ToBoolean(clearValue) == true)//是否有报警
                                                        {
                                                            Console.WriteLine(DateTime.Now + ":提升机下发报警消除指令");
                                                            _logger.Info("提升机下发报警消除指令");
                                                            StaticData.PlcDic[0].WriteToPoint(clearPoint.plcpointAddress, false, clearPoint.plcpointLength.ToString());//清除报警
                                                        }
                                                        wcsTask.taskStatus = 4;
                                                        wcsTask.updateBy = "提升机线程";
                                                        wcsTask.updateTime = DateTime.Now;
                                                        wcsTask.remark = "提升机任务执行完成";
                                                        dbContext.Update(wcsTask);
                                                        dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(t => new WcsTaskLog { taskStatus = 4, updateBy = "提升机线程", updateTime = DateTime.Now, remark = "提升机任务执行完成" });
                                                        dbContext.SaveChanges();
                                                        BasePlcpoint basePlcpoint = StaticData.BasePlcpointList.First(t => t.floorNo == wcsTask.floorNo && t.plcpointNo.Contains("wcsrun"));
                                                        StaticData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "2", basePlcpoint.plcpointLength.ToString());//去向为2，表示提升机已到达目的地，让货出去
                                                        Console.WriteLine(DateTime.Now + ":提升机下发" + wcsTask.floorNo + "楼出库指令");
                                                        _logger.Info("提升机下发" + wcsTask.floorNo + "楼出库指令");
                                                        transaction.Commit();
                                                    }
                                                    else//接驳位外侧有东西
                                                    {
                                                        BasePlcpoint clearPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == $"clear0{wcsTask.floorNo}");
                                                        var clearValue = StaticData.PlcDic[0].Read(clearPoint.plcpointAddress);
                                                        if (clearPoint != null && Convert.ToBoolean(clearValue) == false)
                                                        {
                                                            StaticData.PlcDic[0].WriteToPoint(clearPoint.plcpointAddress, true, clearPoint.plcpointLength.ToString());
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    Console.WriteLine(DateTime.Now + ":一楼托盘库有任务正在执行，等待任务执行完成");
                                                    _logger.Info("一楼托盘库有任务正在执行，等待任务执行完成");
                                                }
                                            }
                                            else
                                            {
                                                var linesignal = StaticData.PlcDic[0].Read(StaticData.BasePlcpointList.First(t => t.plcpointNo == $"linesignal0{wcsTask.floorNo}").plcpointAddress);
                                                _logger.Info($"{wcsTask.floorNo}楼接驳位外侧是否有东西?{linesignal}");
                                                if (linesignal != null && Convert.ToInt32(linesignal) == 0)
                                                {
                                                    wcsTask.taskStatus = 4;
                                                    wcsTask.updateBy = "提升机线程";
                                                    wcsTask.updateTime = DateTime.Now;
                                                    wcsTask.remark = "提升机任务执行完成";
                                                    dbContext.Update(wcsTask);
                                                    dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(t => new WcsTaskLog { taskStatus = 4, updateBy = "提升机线程", updateTime = DateTime.Now, remark = "提升机任务执行完成" });
                                                    dbContext.SaveChanges();
                                                    BasePlcpoint basePlcpoint = StaticData.BasePlcpointList.First(t => t.floorNo == wcsTask.floorNo && t.plcpointNo.Contains("wcsrun"));
                                                    StaticData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "2", basePlcpoint.plcpointLength.ToString());//去向为2，表示提升机已到达目的地，让货出去
                                                    Console.WriteLine(DateTime.Now + ":提升机下发" + wcsTask.floorNo + "楼出库指令");
                                                    _logger.Info("提升机下发" + wcsTask.floorNo + "楼出库指令");
                                                    transaction.Commit();
                                                }
                                                else
                                                {
                                                    BasePlcpoint basePlcpoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == $"clear0{wcsTask.floorNo}");
                                                    StaticData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "1", basePlcpoint.plcpointLength.ToString());
                                                }
                                            }
                                        }
                                        else if (wcsTask.taskStatus == 4)//提升机任务结束
                                        {
                                            BasePlcpoint basePlcpoint = StaticData.BasePlcpointList.First(t => t.floorNo == wcsTask.floorNo && t.plcpointNo.Contains("wcsrun"));
                                            var wcsRun = StaticData.PlcDic[0].Read(basePlcpoint.plcpointAddress);
                                            _logger.Info($"{wcsTask.floorNo}楼接驳位任务状态{wcsRun}");
                                            if (wcsRun != null && Convert.ToInt32(wcsRun) == 0)//判断当前接驳位的任务状态，wcsrrun如果是1代表入库，2是出库，0是空闲
                                            {
                                                BaseEquip floorEquip = StaticData.BaseEquip.First(t => t.objid == wcsTask.floorNo);
                                                wcsTask.nextPointId = floorEquip.objid;
                                                wcsTask.nextPointNo = floorEquip.equipNo;
                                                wcsTask.taskStatus = 5;
                                                wcsTask.updateBy = "提升机线程";
                                                wcsTask.updateTime = DateTime.Now;
                                                wcsTask.remark = "提升机任务执行完成";
                                                lineEquip.equipStatus = 0;
                                                Console.WriteLine(DateTime.Now + ":提升机任务完成" + wcsTask.fromFloorNo + "---" + wcsTask.floorNo + "楼指令");
                                                _logger.Info("提升机任务完成" + wcsTask.fromFloorNo + "---" + wcsTask.floorNo + "楼指令");
                                                dbContext.Update(lineEquip);
                                                dbContext.Update(wcsTask);
                                                dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(t => new WcsTaskLog { taskStatus = 5, nextPointId = floorEquip.objid, nextPointNo = floorEquip.equipNo, updateBy = "提升机线程", updateTime = DateTime.Now, remark = "提升机任务执行完成" });
                                                dbContext.SaveChanges();
                                                transaction.Commit();
                                            }
                                        }
                                        break;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                    else//同步楼层，屏蔽状态
                    {
                        if (currentfloor06Value != null && targetfloor06Value != null)
                        {
                            StaticData.PlcDic[0].WriteToPoint(this.targetfloor06.plcpointAddress, Convert.ToString(currentfloor06Value), this.targetfloor06.plcpointLength.ToString());
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        transaction.Rollback();
                    }
                    catch
                    {
                    }
                    if (ex is PlcException)
                    {

                    }
                    else
                    {
                        _logger.Error(ex.Message + "\n" + ex.StackTrace);
                    }
                }
                Thread.Sleep(5000);
            }
        }
    }
}
