using Khd.Core.Domain.Dto.TaskType;
using Khd.Core.Domain.Dto.webapi;
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 Newtonsoft.Json;
using System.Diagnostics;
using Z.EntityFramework.Plus;

namespace Khd.Core.Wcs.Wcs
{
    /// <summary>
    /// 五楼CTU调度
    /// </summary>
    public class FiveFloorCTU
    {
        List<BasePlcpoint> ScanPoint { get; set; }//点位信息
        private readonly IHost _host;
        private readonly LoggerUtils _logger = new LoggerUtils();
        private readonly BasePlcpoint LineRFID;
        private readonly BasePlcpoint isarrive;
        private readonly BasePlcpoint isput;
        private readonly BasePlcpoint canReceive;
        private readonly BasePlcpoint ReceiveMaterial;
        private readonly BasePlcpoint CtuLineWaring;
        int FloorNo { get; set; }
        int CTUID = 11;
        public FiveFloorCTU(IHost host, int floor)
        {
            this._host = host;
            FloorNo = floor;
            this.LineRFID = StaticData.BasePlcpointList.First(t => t.plcpointNo == "RFID5001");
            this.isarrive = StaticData.BasePlcpointList.First(t => t.plcpointNo == "isarrive");
            this.isput = StaticData.BasePlcpointList.First(t => t.plcpointNo == "isput");
            this.canReceive = StaticData.BasePlcpointList.First(t => t.plcpointNo == "canReceive");
            this.ReceiveMaterial = StaticData.BasePlcpointList.First(t => t.plcpointNo == "ReceiveMaterial");
            this.CtuLineWaring = StaticData.BasePlcpointList.First(t => t.plcpointNo == "CTULineWaring");
        }

        /// <summary>
        /// 启动上件扫描监听
        /// </summary>
        public void StartPoint()
        {

            Thread FlowPointThread = new Thread(MonitorInLocatorPoint);
            FlowPointThread.IsBackground = true;
            FlowPointThread.Name = "FiveFloorCTU";
            FlowPointThread.Start();

            Thread FlowCTUInWareThread = new Thread(MonitorInWare);
            FlowCTUInWareThread.IsBackground = true;
            FlowCTUInWareThread.Name = "FiveFloorCTULine";
            FlowCTUInWareThread.Start();

            Thread HeartThread = new Thread(HeartLogic);
            HeartThread.Start();

            Console.WriteLine(DateTime.Now + ":五楼CTU上件扫描监听启动");
            _logger.Info("五楼CTU上件扫描监听启动");
        }

        private void HeartLogic(object? obj)
        {
            BasePlcpoint heartPoint = StaticData.BasePlcpointList.First(t => t.plcpointNo == "CTUHeart");
            bool flag = true;
            while (true)
            {
                try
                {
                    flag = !flag;
                    StaticData.PlcDic[1].WriteToPoint(heartPoint.plcpointAddress, flag.ToString(), heartPoint.plcpointLength.ToString());
                }
                catch
                {

                }
                Thread.Sleep(1000);
            }
        }

        private void MonitorInWare(object? obj)
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    var rfid = StaticData.PlcDic[1].ReadRFID(LineRFID.plcpointAddress);
                    var isArrive = StaticData.PlcDic[1].Read(isarrive.plcpointAddress);
                    var receiveMaterial = StaticData.PlcDic[1].Read(ReceiveMaterial.plcpointAddress);
                    var waring = StaticData.PlcDic[1].Read(CtuLineWaring.plcpointAddress);
                    if (rfid != null && isArrive != null && receiveMaterial != null && Convert.ToInt32(receiveMaterial) == 1 && Convert.ToInt32(isArrive) == 1)
                    {
                        rfid = rfid[rfid.IndexOf('C')..];
                        WcsTask? task = dbContext.WcsTask.FirstOrDefault(t => t.containerNo == rfid);
                        if (task == null)
                        {
                            //根据rfid找到库位
                            //生成入库任务
                            var wmsBaseLocation = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == rfid);
                            if (wmsBaseLocation != null)
                            {
                                BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.equipNo == "FL051");
                                BaseEquip ctuEquip = StaticData.BaseEquip.First(t => t.objid == 11);
                                if (wmsBaseLocation != null)
                                {
                                    var wcsTask = new WcsTask()
                                    {
                                        objid = StaticData.SnowId.NextId(),
                                        currPointId = baseEquip.objid,
                                        currPointNo = baseEquip.agvPositionCode,
                                        nextPointId = ctuEquip.objid,
                                        nextPointNo = ctuEquip.equipNo,
                                        endPointId = wmsBaseLocation.locationId,
                                        endPointNo = wmsBaseLocation.agvPositionCode,
                                        taskType = StaticTaskType.FiveAccessoryIn,
                                        taskStatus = 0,
                                        useFlag = 1,
                                        floorNo = 5,
                                        containerNo = rfid.ToString(),
                                        equipmentNo = baseEquip.equipNo,
                                        createBy = FloorNo + "楼CTU",
                                        createTime = DateTime.Now,
                                    };
                                    wmsBaseLocation.locationStatus = "2";
                                    wmsBaseLocation.updateTime = DateTime.Now;
                                    dbContext.Update(wmsBaseLocation);
                                    dbContext.Add(wcsTask);
                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                    dbContext.Add(wcsTaskLog);
                                    dbContext.SaveChanges();
                                    StaticData.PlcDic[1].WriteToPoint(CtuLineWaring.plcpointAddress, false, CtuLineWaring.plcpointLength.ToString());
                                }
                            }
                            else
                            {
                                //报警
                                StaticData.PlcDic[1].WriteToPoint(CtuLineWaring.plcpointAddress, true, CtuLineWaring.plcpointLength.ToString());
                            }
                        }
                        else
                        {
                            if (task.taskType == StaticTaskType.FiveAccessoryOut || task.taskType == StaticTaskType.FiveAccessoryRemove || task.taskType == StaticTaskType.FiveAccessoryStorage)
                            {
                                dbContext.WcsTask.Where(t => t.objid == task.objid).Delete();
                                #region 暂不使用-因为删除之后ctu无法知道还有几个箱子///如果已经开始入库,还有出库任务，删除出库任务
                                //List<WcsTask> outTasks = dbContext.WcsTask.Where(t => t.taskType == StaticTaskType.FiveAccessoryOut && t.taskStatus == 6).ToList();
                                //if(outTasks!=null && outTasks.Count > 0)
                                //{
                                //    dbContext.RemoveRange(outTasks);
                                //}                              
                                #endregion
                                //根据rfid找到库位
                                //生成入库任务
                                var wmsBaseLocation = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == rfid);
                                if (wmsBaseLocation != null)
                                {
                                    BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.equipNo == "FL051");
                                    BaseEquip ctuEquip = StaticData.BaseEquip.First(t => t.objid == 11);
                                    if (wmsBaseLocation != null)
                                    {
                                        var wcsTask = new WcsTask()
                                        {
                                            objid = StaticData.SnowId.NextId(),
                                            currPointId = baseEquip.objid,
                                            currPointNo = baseEquip.agvPositionCode,
                                            nextPointId = ctuEquip.objid,
                                            useFlag = 1,
                                            endPointId = wmsBaseLocation.locationId,
                                            endPointNo = wmsBaseLocation.agvPositionCode,
                                            taskType = StaticTaskType.FiveAccessoryIn,
                                            taskStatus = 0,
                                            floorNo = 5,
                                            containerNo = rfid.ToString(),
                                            equipmentNo = baseEquip.equipNo,
                                            createBy = FloorNo + "楼CTU",
                                            createTime = DateTime.Now,
                                            ud3 = "1"//标记任务是出库任务转为入库任务
                                        };
                                        wmsBaseLocation.locationStatus = "2";
                                        wmsBaseLocation.updateTime = DateTime.Now;
                                        dbContext.Update(wmsBaseLocation);
                                        dbContext.Add(wcsTask);
                                        WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                        dbContext.Add(wcsTaskLog);
                                        dbContext.SaveChanges();
                                        StaticData.PlcDic[1].WriteToPoint(CtuLineWaring.plcpointAddress, false, CtuLineWaring.plcpointLength.ToString());
                                    }
                                }
                            }
                            else if (task.taskType == StaticTaskType.FiveAccessoryStorage)
                            {
                                WmsInventoryCheck? wmsInventoryCheck = dbContext.WmsInventoryCheck.Where(t => t.InventoryCheckId == task.orderId).FirstOrDefault();
                                if (wmsInventoryCheck != null)
                                {
                                    wmsInventoryCheck.InventoryingAmount = wmsInventoryCheck.InventoryingAmount > 0 ? wmsInventoryCheck.InventoryingAmount - 1 : 0;
                                    wmsInventoryCheck.InventoriedAmount++;
                                    if (wmsInventoryCheck.InventoriedAmount >= wmsInventoryCheck.LocationAmount)
                                    {
                                        wmsInventoryCheck.CheckStatus = "2";
                                        wmsInventoryCheck.EndTime = DateTime.Now;
                                    }
                                    dbContext.WcsTask.Where(t => t.objid == task.objid).Delete();
                                    //根据rfid找到库位
                                    //生成入库任务
                                    var wmsBaseLocation = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == rfid);
                                    if (wmsBaseLocation != null)
                                    {
                                        BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.equipNo == "FL051");
                                        BaseEquip ctuEquip = StaticData.BaseEquip.First(t => t.objid == 11);
                                        if (wmsBaseLocation != null)
                                        {
                                            var wcsTask = new WcsTask()
                                            {
                                                objid = StaticData.SnowId.NextId(),
                                                currPointId = baseEquip.objid,
                                                currPointNo = baseEquip.agvPositionCode,
                                                nextPointId = ctuEquip.objid,
                                                useFlag = 1,
                                                endPointId = wmsBaseLocation.locationId,
                                                endPointNo = wmsBaseLocation.agvPositionCode,
                                                taskType = StaticTaskType.FiveAccessoryIn,
                                                taskStatus = 0,
                                                floorNo = 5,
                                                containerNo = rfid.ToString(),
                                                equipmentNo = baseEquip.equipNo,
                                                createBy = FloorNo + "楼CTU",
                                                createTime = DateTime.Now,
                                            };
                                            dbContext.Update(wmsInventoryCheck);
                                            wmsBaseLocation.locationStatus = "2";
                                            wmsBaseLocation.updateTime = DateTime.Now;
                                            dbContext.Update(wmsBaseLocation);
                                            dbContext.Add(wcsTask);
                                            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                            dbContext.Add(wcsTaskLog);
                                            dbContext.SaveChanges();
                                            StaticData.PlcDic[1].WriteToPoint(CtuLineWaring.plcpointAddress, false, CtuLineWaring.plcpointLength.ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (Convert.ToInt32(receiveMaterial) == 1 && Convert.ToInt32(isArrive) == 1 && string.IsNullOrEmpty(rfid))
                    {
                        if (!Convert.ToBoolean(waring))
                        {
                            StaticData.PlcDic[1].WriteToPoint(CtuLineWaring.plcpointAddress, true, CtuLineWaring.plcpointLength.ToString());
                        }
                    }
                    else
                    {
                        StaticData.PlcDic[1].WriteToPoint(CtuLineWaring.plcpointAddress, false, CtuLineWaring.plcpointLength.ToString());
                    }
                }
                catch (Exception ex)
                {
                    if (ex is PlcException)
                    {

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

        /// <summary>
        /// 预执行任务下发
        /// </summary>
        //private void CtuWaitLogic()
        //{
        //    BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.objid == CTUID);
        //    BaseEquip Fl051 = StaticData.BaseEquip.First(t => t.objid == 19);//入库输送线
        //    while (true)
        //    {
        //        try
        //        {
        //            while (isWait)
        //            {
        //                var waitTask = new
        //                {
        //                    reqCode = StaticData.SnowId.NextId().ToString(),
        //                    positionCode = "CTU_IN",
        //                    nextTask = 1200
        //                };
        //                string waitMessage = JsonConvert.SerializeObject(waitTask);
        //                string waitResult = HttpHelper.SendPostMessage(baseEquip.serverIp, baseEquip.serverPort.Value, "rcms/services/rest/hikRpcService/genPreScheduleTask", waitMessage);
        //                var waitReponse = JsonConvert.DeserializeObject<ReponseMessage>(waitResult);
        //                if (waitReponse != null && waitReponse.code == "0")
        //                {
        //                    isSendWait = true;
        //                }
        //                else
        //                {
        //                    _logger.Info("CTU下发预执行任务失败:\nwaitTask:" + waitMessage + "\nwaitResult:" + waitResult);
        //                }
        //                Thread.Sleep(1000 * 60 * 10);//每10分钟重新下发预执行任务
        //            }
        //            isSendWait = false;
        //        }
        //        catch (Exception ex)
        //        {
        //            _logger.Error(ex.Message + "\n" + ex.StackTrace);
        //        }
        //        Thread.Sleep(3000);
        //    }
        //}

        private bool CtuWaitLogic()
        {
            BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.objid == CTUID);
            BaseEquip Fl051 = StaticData.BaseEquip.First(t => t.objid == 19);//入库输送线
            try
            {
                var waitTask = new
                {
                    reqCode = StaticData.SnowId.NextId().ToString(),
                    positionCode = "CTU_IN",
                    nextTask = 120
                };
                string waitMessage = JsonConvert.SerializeObject(waitTask);
                string waitResult = HttpHelper.SendPostMessage(baseEquip.serverIp, baseEquip.serverPort.Value, "rcms/services/rest/hikRpcService/genPreScheduleTask", waitMessage);
                var waitReponse = JsonConvert.DeserializeObject<ReponseMessage>(waitResult);
                if (waitReponse != null && waitReponse.code == "0")
                {
                    return true;
                }
                else
                {
                    _logger.Info("CTU下发预执行任务失败:\nwaitTask:" + waitMessage + "\nwaitResult:" + waitResult);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message + "\n" + ex.StackTrace);
                return false;
            }
            return false;
        }
        /// <summary>
        /// 监控上件扫描点位
        /// </summary>
        public void MonitorInLocatorPoint()
        {
            List<int?> taskType = new() { 1, 3, 5, 7 };
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.objid == CTUID);
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    var taskList = dbContext.WcsTask
                        .Where(t => t.useFlag == 1)
                        .Where(t => t.IsDelete == 0 || t.IsDelete == null)
                        .Where(t => t.nextPointId == CTUID).OrderByDescending(t => t.ud1).ToList();
                    foreach (var item in taskList)
                    {
                        item.updateTime = DateTime.Now;
                        if (item.taskStatus == 0)//CTU会同时生成多个任务，生成就下发？
                        {
                            if (item.taskType == StaticTaskType.FiveAccessoryOut || item.taskType == StaticTaskType.FiveAccessoryStorage || item.taskType == StaticTaskType.FiveAccessoryRemove)//出库任务
                            {
                                BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == item.endPointId);
                                WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation.First(t => t.locationId == item.currPointId);
                                var agvTask = new RequestAGVTaskDto
                                {
                                    reqCode = StaticData.SnowId.NextId().ToString(),
                                    positionCodePath = new List<Position>
                                            {
                                                new()
                                                {
                                                    positionCode =wmsBaseLocation.agvPositionCode,
                                                    type = "05"//05库位
                                                },
                                                new()
                                                {
                                                    positionCode = endEquip.agvPositionCode,
                                                    type = "00"//设备
                                                },
                                            },
                                    ctnrTyp = "1",
                                    taskTyp = "F504"
                                };
                                string message = JsonConvert.SerializeObject(agvTask);
                                string result = HttpHelper.SendPostMessage(baseEquip.serverIp, baseEquip.serverPort.Value, "rcms/services/rest/hikRpcService/genAgvSchedulingTask", message);
                                var reponseMessage = JsonConvert.DeserializeObject<ReponseMessage>(result);
                                if (reponseMessage != null && reponseMessage.code == "0")
                                {
                                    _logger.Info("五楼CTU线程开始任务" + item.objid);
                                    Console.WriteLine(DateTime.Now + ":五楼CTU线程开始任务" + item.currPointNo + "," + item.endPointNo);
                                    item.taskCode = reponseMessage.data;
                                    item.taskStatus = 1;

                                    dbContext.Update(item);
                                    dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 1 });
                                    dbContext.SaveChanges();
                                }
                                else
                                {
                                    _logger.Info("CTU下发出库任务失败：" + reponseMessage?.message);
                                }
                            }
                            else if (item.taskType == StaticTaskType.FiveAccessoryIn)//入库任务
                            {
                                bool haveOut = taskList.Where(t => t.taskType == StaticTaskType.FiveAccessoryOut).Where(t => t.taskStatus != 6).Any();
                                if (!haveOut && CtuWaitLogic())
                                {
                                    BaseEquip startEquip = StaticData.BaseEquip.First(t => t.objid == item.currPointId);
                                    WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation.First(t => t.locationId == item.endPointId);
                                    var agvTask = new
                                    {
                                        reqCode = StaticData.SnowId.NextId().ToString(),
                                        positionCodePath = new List<Position>
                                            {
                                                new()
                                                {
                                                    positionCode = startEquip.agvPositionCode ,
                                                    type = "05"//设备
                                                },
                                                new()
                                                {
                                                    positionCode = wmsBaseLocation.agvPositionCode,
                                                    type = "05"//库位
                                                },
                                            },
                                        ctnrTyp = "1",
                                        taskTyp = "F503"
                                    };
                                    string message = JsonConvert.SerializeObject(agvTask);
                                    string result = HttpHelper.SendPostMessage(baseEquip.serverIp, baseEquip.serverPort.Value, "rcms/services/rest/hikRpcService/genAgvSchedulingTask", message);
                                    var reponseMessage = JsonConvert.DeserializeObject<ReponseMessage>(result);
                                    if (reponseMessage != null && reponseMessage.code == "0")
                                    {
                                        _logger.Info("五楼CTU线程开始任务" + item.objid);
                                        Console.WriteLine(DateTime.Now + ":五楼CTU线程开始任务" + item.currPointNo + "," + item.endPointNo);
                                        item.taskCode = reponseMessage.data;
                                        item.taskStatus = 1;
                                        dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 1 });
                                        dbContext.Update(item);
                                        lock (SystemData.outStockLock)
                                        {
                                            bool hasTask = dbContext.WcsTask.Where(t => t.nextPointId == 11 && t.taskType == StaticTaskType.FiveAccessoryOut).Any();
                                            int taskCount = dbContext.WcsTask.Where(t => t.nextPointId == 11 && t.taskType == StaticTaskType.FiveAccessoryIn).Count();
                                            if ((!hasTask && item.ud3 == "1") || (taskCount >= 6))//如果CTU当前任务数量很多，取消预执行任务,或者出库的任务都生成了入库任务
                                            {
                                                ExecuteInTask(baseEquip);
                                            }
                                        }

                                        dbContext.SaveChanges();
                                    }
                                    else
                                    {
                                        _logger.Info("CTU下发入库任务失败：" + reponseMessage?.message);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (item.taskStatus == 3)
                            {
                                if (item.taskType == StaticTaskType.FiveAccessoryOut || item.taskType == StaticTaskType.FiveAccessoryStorage || item.taskType == StaticTaskType.FiveAccessoryRemove)
                                {
                                    var canOut = StaticData.PlcDic[1].Read(isput.plcpointAddress);
                                    if (canOut != null && Convert.ToInt64(canOut) == 0)
                                    {
                                        var agvTask = new
                                        {
                                            reqCode = StaticData.SnowId.NextId().ToString(),
                                            taskCode = item.taskCode,
                                            type = 2
                                        };
                                        string message = JsonConvert.SerializeObject(agvTask);
                                        string result = HttpHelper.SendPostMessage(baseEquip.serverIp, baseEquip.serverPort.Value, "rcms/services/rest/hikRpcService/boxApplyPass", message);
                                        ReponseMessage? reponseMessage = JsonConvert.DeserializeObject<ReponseMessage>(result);
                                        if (reponseMessage != null && reponseMessage.code == "0")
                                        {
                                            _logger.Info("五楼AGV线程下发任务" + agvTask.ToJsonString() + "\n" + message);
                                            Console.WriteLine(DateTime.Now + ":五楼CTU线程继续任务" + item.currPointId + "," + item.endPointNo);
                                            dbContext.WcsTask.Where(t => t.objid == item.objid).Update(t => new WcsTask() { taskStatus = 4 });
                                            dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 4 });
                                        }
                                        else
                                        {
                                            _logger.Info("CTU第一次下发继续任务失败：" + reponseMessage?.message);
                                        }
                                    }
                                }
                                if (item.taskType == StaticTaskType.FiveAccessoryIn)
                                {
                                    var agvTask = new
                                    {
                                        reqCode = StaticData.SnowId.NextId().ToString(),
                                        taskCode = item.taskCode,
                                        type = 1
                                    };
                                    string message = JsonConvert.SerializeObject(agvTask);
                                    string result = HttpHelper.SendPostMessage(baseEquip.serverIp, baseEquip.serverPort.Value, "rcms/services/rest/hikRpcService/boxApplyPass", message);
                                    ReponseMessage? reponseMessage = JsonConvert.DeserializeObject<ReponseMessage>(result);
                                    if (reponseMessage != null && reponseMessage.code == "0")
                                    {
                                        _logger.Info("五楼CTU线程下发任务" + agvTask.ToJsonString() + "\n" + message);
                                        Console.WriteLine(DateTime.Now + ":五楼CTU线程下发任务" + item.currPointId + "," + item.endPointNo);
                                        dbContext.WcsTask.Where(t => t.objid == item.objid).Update(t => new WcsTask() { taskStatus = 4 });
                                        dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 4 });
                                        dbContext.SaveChanges();
                                    }
                                    else
                                    {
                                        _logger.Info("CTU第二次下发继续任务失败：" + reponseMessage?.message);
                                    }
                                }
                            }
                            else if (item.taskStatus == 5)
                            {
                                _logger.Info("五楼CTU线程完成任务" + item.objid);
                                Console.WriteLine(DateTime.Now + ":五楼CTU线程完成任务" + item.currPointNo + "," + item.endPointNo);
                                if (item.taskType == StaticTaskType.FiveAccessoryOut || item.taskType == StaticTaskType.FiveAccessoryStorage || item.taskType == StaticTaskType.FiveAccessoryRemove)//出库任务
                                {
                                    WmsRawOutstockDetail? wmsRawOutstockDetail = dbContext.WmsRawOutstockDetail.FirstOrDefault(t => t.taskCode == item.objid.ToString());
                                    if (wmsRawOutstockDetail != null)
                                    {
                                        wmsRawOutstockDetail.executeStatus = "2";
                                        wmsRawOutstockDetail.updateDate = DateTime.Now;
                                        dbContext.Update(wmsRawOutstockDetail);
                                    }
                                    WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation
                                           .First(t => t.locationId == item.currPointId && t.warehouseFloor == 5);
                                    wmsBaseLocation.locationStatus = "1";
                                    wmsBaseLocation.ContainerStatus = "2";
                                    dbContext.Update(wmsBaseLocation);
                                    dbContext.SaveChanges();
                                    dbContext.WmsRawOutstockDetail.Where(t => t.locationCode == wmsBaseLocation.locationCode).Update(t => new WmsRawOutstockDetail { executeStatus = "2" });
                                    dbContext.WcsTask.Where(t => t.objid == item.objid).Update(t => new WcsTask() { taskStatus = 6 });
                                    dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 6 });
                                    int wcsTaskCount = dbContext.WcsTask.Where(t => t.taskType == StaticTaskType.FiveAccessoryOut && t.taskStatus != 6).Count();
                                    if (wcsTaskCount == 0)
                                    {
                                        StaticData.PlcDic[1].WriteToPoint(this.canReceive.plcpointAddress, "1", this.canReceive.plcpointLength?.ToString());
                                    }
                                }
                                else if (item.taskType == StaticTaskType.FiveAccessoryIn)//入库任务
                                {
                                    try
                                    {
                                        WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation
                                      .First(t => t.locationId == item.endPointId && t.warehouseFloor == 5);
                                        wmsBaseLocation.locationStatus = "1";
                                        wmsBaseLocation.ContainerStatus = "1";
                                        dbContext.Update(wmsBaseLocation);
                                        dbContext.Remove(item);
                                        dbContext.SaveChanges();
                                        dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 6 });
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.Error($"入库异常捕捉:{ex.Message}");
                                    }
                                }
                                else if (item.taskType == StaticTaskType.FiveAccessoryStorage || item.taskType == StaticTaskType.FiveAccessoryRemove)//出库任务
                                {
                                    WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation
                                           .First(t => t.locationId == item.currPointId && t.warehouseFloor == 5);
                                    wmsBaseLocation.locationStatus = "1";
                                    wmsBaseLocation.ContainerStatus = "2";
                                    dbContext.Update(wmsBaseLocation);
                                    dbContext.WcsTask.Where(t => t.objid == item.objid).Update(t => new WcsTask() { taskStatus = 6 });
                                    dbContext.SaveChanges();
                                    dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 6 });
                                    int wcsTaskCount = dbContext.WcsTask.Where(t => (item.taskType == StaticTaskType.FiveAccessoryOut || item.taskType == StaticTaskType.FiveAccessoryStorage || item.taskType == StaticTaskType.FiveAccessoryRemove) && t.taskStatus != 6).Count();
                                    if (wcsTaskCount == 0)
                                    {
                                        StaticData.PlcDic[1].WriteToPoint(this.canReceive.plcpointAddress, "1", this.canReceive.plcpointLength?.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex is PlcException)
                    {

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

        /// <summary>
        /// 通知CTU取消预执行任务
        /// </summary>
        /// <param name="baseEquip"></param>
        /// <param name="wcsCmd"></param>
        private void ExecuteInTask(BaseEquip baseEquip)
        {
            //while (isWait)
            {
                var executeTask = new
                {
                    reqCode = StaticData.SnowId.NextId().ToString(),
                    positionCode = "CTU_IN",
                    nextTask = -1
                };
                string executeMessage = JsonConvert.SerializeObject(executeTask);
                string executeResult = HttpHelper.SendPostMessage(baseEquip.serverIp, baseEquip.serverPort.Value, "rcms/services/rest/hikRpcService/genPreScheduleTask", executeMessage);
                var executeReponse = JsonConvert.DeserializeObject<ReponseMessage>(executeResult);
                if (executeReponse != null && executeReponse.code == "0")
                {
                    _logger.Info("下发CTU执行入库任务成功");
                }
                else
                {
                    _logger.Info("下发CTU执行入库任务失败");
                    Console.WriteLine($"{DateTime.Now}:下发CTU执行入库任务失败" + executeReponse?.message);
                    ExecuteInTask(baseEquip);
                    Thread.Sleep(1000);
                }
            }
        }

    }
}
