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.AspNetCore.Razor.Language;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Z.EntityFramework.Plus;

namespace Khd.Core.Wcs.Wcs
{
    /// <summary>
    /// 五楼AGV调度
    /// </summary>
    public class FiveFloorAGV
    {
        private readonly LoggerUtils _logger = new LoggerUtils();
        private readonly IHost _host;
        private readonly BasePlcpoint LineSignal;
        int FloorNo { get; set; }
        int agvID = 28;
        public FiveFloorAGV(IHost host, int floor)
        {
            this._host = host;
            FloorNo = floor;
            this.LineSignal = StaticData.BasePlcpointList.First(t => t.plcpointNo == "linesignal05");
        }
        /// <summary>
        /// 启动上件扫描监听
        /// </summary>
        public void StartPoint()
        {
            Thread FlowPointThread = new(MonitorInLocatorPoint);
            FlowPointThread.IsBackground = true;
            FlowPointThread.Name = "FiveFloorAGV";
            FlowPointThread.Start();
            Console.WriteLine(DateTime.Now + ":五楼AGV上件扫描监听启动成功");
            _logger.Info("五楼AGV上件扫描监听启动成功");
        }

        public void MonitorInLocatorPoint()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.objid == agvID);
            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 == agvID).OrderBy(t => t.createTime).ToList();
                    foreach (var item in taskList)
                    {
                        if (taskList.Where(t => t.taskStatus > 0).Where(t => t.objid != item.objid).Any())
                        {
                            _logger.Info($"5楼AGV线程：有其他任务正在执行，跳过当前任务{item.objid}");
                            continue;
                        }
                        item.updateTime = DateTime.Now;
                        if (item.taskStatus == 0)//下发任务
                        {
                            BaseDictionary baseDictionary = StaticData.BaseDictionary.First(t => t.objid == item.taskType);
                            if (item.taskType == StaticTaskType.FiveProductOut)//出库任务
                            {
                                BaseEquip lineEquip = dbContext.BaseEquip.First(t => t.objid == 5);
                                if (lineEquip.equipStatus == 0)
                                {
                                    bool canSend = dbContext.WcsTask.Where(t => t.nextPointId == lineEquip.objid && t.taskStatus > 0).Any();
                                    if (lineEquip.equipStatus == 1)
                                    {
                                        _logger.Info("五楼AGV:接驳位有任务，无法下发出库任务");
                                        continue;
                                    }
                                    if (Convert.ToInt32(StaticData.PlcDic[0].Read(LineSignal.plcpointAddress)) == 1 && !canSend)
                                    {
                                        Console.WriteLine($"{DateTime.Now}:5楼接驳位上有货，无法下发Agv出库任务");
                                        continue;
                                    }
                                    BaseEquip nextEquip = StaticData.BaseEquip.First(t => t.floorNo == 5 && t.equipType == 1);
                                    RequestAGVTaskDto agvTask = new()
                                    {
                                        reqCode = StaticData.SnowId.NextId().ToString(),
                                        positionCodePath = new List<Position>
                                        {
                                            new ()
                                            {
                                                positionCode=item.currPointNo,
                                                type="00"
                                            },
                                            new ()
                                            {
                                                positionCode=nextEquip.agvPositionCode,
                                                type="00"
                                            }
                                        },
                                        taskTyp = baseDictionary.dicValue,
                                        ctnrTyp = "2"
                                    };

                                    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.message == "成功")
                                    {
                                        _logger.Info("五楼Agv下发任务成功：" + message);
                                        Console.WriteLine(DateTime.Now + ":五楼Agv下发任务成功：" + item.currPointNo + "," + nextEquip.agvPositionCode);
                                        item.taskCode = reponseMessage.data;
                                        item.taskStatus = 1;
                                        lineEquip.equipStatus = 1;
                                        dbContext.Update(lineEquip);
                                        dbContext.Update(item);
                                        dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog { taskStatus = 1 });
                                        dbContext.SaveChanges();
                                    }
                                    else
                                    {
                                        _logger.Info("五楼Agv下发任务失败" + item.taskType + result);
                                    }

                                }
                            }
                            else if (item.taskType == StaticTaskType.FiveRawToBack)//原材料到背板安装
                            {
                                BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == 30);
                                RequestAGVTaskDto agvTask = new()
                                {
                                    reqCode = StaticData.SnowId.NextId().ToString(),
                                    positionCodePath = new List<Position>
                                    {
                                        new ()
                                        {
                                            positionCode=item.currPointNo,
                                            type="00"
                                        },
                                        new ()
                                        {
                                            positionCode= endEquip.agvPositionCode,
                                            type="00"
                                        }
                                    },
                                    taskTyp = baseDictionary.dicValue,
                                    ctnrTyp = "2"
                                };
                                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.message == "成功")
                                {
                                    _logger.Info("五楼Agv下发任务成功：" + message);
                                    Console.WriteLine(DateTime.Now + ":五楼Agv下发任务成功：" + item.currPointNo + "," + endEquip.agvPositionCode);
                                    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("五楼Agv下发任务失败" + item.taskType + result);
                                }
                            }
                            else if (item.taskType == StaticTaskType.FiveHalfIn)//背板安装到半成品
                            {
                                BaseEquip currentEquip = StaticData.BaseEquip.First(t => t.objid == 30);
                                var agvTask = new RequestAGVTaskDto
                                {
                                    reqCode = StaticData.SnowId.NextId().ToString(),
                                    positionCodePath = new List<Position>
                                    {
                                        new ()
                                        {
                                            positionCode=currentEquip.agvPositionCode,
                                            type="00"
                                        },
                                        new ()
                                        {
                                            positionCode=item.endPointNo,
                                            type="00"
                                        }
                                    },
                                    taskTyp = baseDictionary.dicValue,
                                    ctnrTyp = "2",
                                };
                                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.message == "成功")
                                {
                                    _logger.Info("五楼Agv下发任务成功：" + message);
                                    Console.WriteLine(DateTime.Now + ":五楼Agv下发任务成功：" + currentEquip.agvPositionCode + "," + 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("五楼Agv下发任务失败" + item.taskType + result);
                                }
                            }
                            else if (item.taskType == StaticTaskType.FiveRawToSplit)//原材料到拆分区
                            {
                                BaseEquip currentEquip = StaticData.BaseEquip.First(t => t.objid == 29);
                                RequestAGVTaskDto agvTask = new()
                                {
                                    reqCode = StaticData.SnowId.NextId().ToString(),
                                    positionCodePath = new List<Position>
                                    {
                                        new ()
                                        {
                                            positionCode=item.currPointNo,
                                            type="00"
                                        },
                                        new ()
                                        {
                                            positionCode=currentEquip.agvPositionCode,
                                            type="00"
                                        }
                                    },
                                    taskTyp = baseDictionary.dicValue,
                                    ctnrTyp = "2"
                                };
                                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.message == "成功")
                                {
                                    _logger.Info("五楼Agv下发任务成功：" + message);
                                    Console.WriteLine(DateTime.Now + ":五楼Agv下发任务成功：" + item.currPointNo + "," + currentEquip.agvPositionCode);
                                    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("五楼Agv下发任务失败" + item.taskType + result);
                                }
                            }
                            else if (item.taskType == StaticTaskType.FiveRawSplitReturn)//拆分区返库
                            {
                                BaseEquip currentEquip = StaticData.BaseEquip.First(t => t.objid == 29);
                                RequestAGVTaskDto agvTask = new()
                                {
                                    reqCode = StaticData.SnowId.NextId().ToString(),
                                    positionCodePath = new List<Position>
                                    {
                                        new()
                                        {
                                            positionCode = currentEquip.agvPositionCode,
                                            type = "00"
                                        },
                                        new()
                                        {
                                            positionCode = item.endPointNo,
                                            type = "00"
                                        }
                                    },
                                    taskTyp = baseDictionary.dicValue,
                                    ctnrTyp = "2"

                                };
                                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.message == "成功")
                                {
                                    _logger.Info("五楼Agv下发任务成功：" + message);
                                    Console.WriteLine(DateTime.Now + ":五楼Agv下发任务成功：" + currentEquip.agvPositionCode + "," + 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("五楼Agv下发任务失败" + item.taskType + result);
                                }
                            }
                            else if (item.taskType == StaticTaskType.FiveRawIn)//原材料入库
                            {
                                BaseEquip startEquip = StaticData.BaseEquip.First(t => t.objid == 5);
                                var agvTask = new RequestAGVTaskDto
                                {
                                    reqCode = StaticData.SnowId.NextId().ToString(),
                                    positionCodePath = new List<Position>
                                    {
                                        new ()
                                        {
                                            positionCode= startEquip.agvPositionCode,
                                            type="00"
                                        },
                                        new ()
                                        {
                                            positionCode=item.endPointNo,
                                            type="00"
                                        }
                                    },
                                    taskTyp = baseDictionary.dicValue,
                                    ctnrTyp = "2",
                                };
                                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.message == "成功")
                                {
                                    _logger.Info("五楼Agv下发任务成功：" + message);
                                    Console.WriteLine(DateTime.Now + ":五楼Agv下发任务成功：" + startEquip.agvPositionCode + "," + 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("五楼Agv下发任务失败" + item.taskType + result);
                                }
                            }
                            else if (item.taskType == StaticTaskType.FiveRemove)//移库
                            {
                                var agvTask = new RequestAGVTaskDto
                                {
                                    reqCode = StaticData.SnowId.NextId().ToString(),
                                    positionCodePath = new List<Position>
                                    {
                                        new ()
                                        {
                                            positionCode=item.currPointNo,
                                            type="00"
                                        },
                                        new ()
                                        {
                                            positionCode=item.endPointNo,
                                            type="00"
                                        }
                                    },
                                    taskTyp = baseDictionary.dicValue,
                                    ctnrTyp = "2",
                                };
                                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.message == "成功")
                                {
                                    _logger.Info("五楼Agv下发任务成功：" + message);
                                    Console.WriteLine(DateTime.Now + ":五楼Agv下发任务成功：" + 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("五楼Agv下发任务失败" + item.taskType + result);
                                }
                            }
                        }
                        else
                        {
                            if (item.taskStatus == 3)
                            {
                                if (item.currPointId == 5)
                                {
                                    var lineSignalValue = StaticData.PlcDic[0].Read(LineSignal.plcpointAddress);
                                    if (lineSignalValue == null || Convert.ToInt32(lineSignalValue) == 0)
                                    {
                                        Console.WriteLine(DateTime.Now + ":五楼Agv：接驳位为空，无法取货");
                                        _logger.Info("五楼Agv：接驳位为空，无法取货");
                                        continue;
                                    }
                                }
                                else if (item.endPointId == 5)
                                {
                                    var lineSignalValue = StaticData.PlcDic[0].Read(LineSignal.plcpointAddress);
                                    if (lineSignalValue == null || Convert.ToInt32(lineSignalValue) == 1)
                                    {
                                        Console.WriteLine(DateTime.Now + ":五楼Agv：接驳位有货，无法送货");
                                        _logger.Info("五楼Agv：接驳位有货，无法送货");
                                        continue;
                                    }
                                }
                                var agvTask = new RequestAGVTaskDto
                                {
                                    reqCode = StaticData.SnowId.NextId().ToString(),
                                    taskCode = item.taskCode
                                };
                                string message = JsonConvert.SerializeObject(agvTask);
                                string result = HttpHelper.SendPostMessage(baseEquip.serverIp, baseEquip.serverPort.Value, "rcms/services/rest/hikRpcService/continueTask", message);
                                ReponseMessage? reponseMessage = JsonConvert.DeserializeObject<ReponseMessage>(result);
                                if (reponseMessage != null && reponseMessage.message == "成功")
                                {
                                    _logger.Info("五楼Agv下发继续任务成功：" + message);
                                    Console.WriteLine(DateTime.Now + ":五楼Agv继续任务：" + item.currPointNo + "," + item.endPointNo);
                                    item.taskStatus = 4;
                                    dbContext.Update(item);
                                    dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 4 });
                                    dbContext.SaveChanges();
                                }
                            }
                            else if (item.taskStatus == 5)
                            {
                                if (item.taskType == StaticTaskType.FiveRemove)//移库
                                {
                                    Console.WriteLine(DateTime.Now + ":五楼AGV线程完成任务" + item.currPointNo + "," + item.endPointNo);
                                    _logger.Info("五楼Agv完成任务成功：" + item.ToJsonString());
                                    using var dbContextTransaction = dbContext.Database.BeginTransaction();
                                    try
                                    {
                                        var wmsRawStock = dbContext.WmsRawStock.Where(t => t.locationCode == item.currPointNo).FirstOrDefault();
                                        if (wmsRawStock != null)
                                        {
                                            wmsRawStock.locationCode = item.endPointNo;
                                            dbContext.Update(wmsRawStock);
                                        }
                                        else if (wmsRawStock == null)
                                        {
                                            var wmsProductStock = dbContext.WmsProductStock.FirstOrDefault(t => t.locationCode == item.currPointNo);
                                            if (wmsProductStock != null)
                                            {
                                                wmsProductStock.locationCode = item.endPointNo;
                                                dbContext.Update(wmsProductStock);
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                        WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation.Where(t => t.locationId == item.currPointId).First();
                                        WmsBaseLocation toLocation = dbContext.WmsBaseLocation.Where(t => t.locationId == item.endPointId).First();
                                        SystemData.UnLockOutLocation(wmsBaseLocation, dbContext);
                                        SystemData.UnLockOutLocation(toLocation, dbContext);

                                        dbContext.WmsBaseLocation.Where(t => t.locationId == item.currPointId).Update(t => new WmsBaseLocation
                                        {
                                            returnFlag = "0",
                                            locationStatus = "1",
                                            containerCode = null,
                                            updateTime = DateTime.Now
                                        });
                                        dbContext.WmsBaseLocation.Where(t => t.locationId == item.endPointId).Update(t => new WmsBaseLocation
                                        {
                                            locationStatus = "1",
                                            returnFlag = wmsBaseLocation.returnFlag,
                                            containerCode = item.containerNo,
                                            updateTime = DateTime.Now
                                        });
                                        dbContext.Remove(item);
                                        dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog() { taskStatus = 6 });
                                        #region 插入移库记录
                                        WmsMove wmsMove = new WmsMove();
                                        wmsMove.MoveId = StaticData.SnowId.NextId();
                                        wmsMove.TaskCode = StaticData.SnowId.NextId().ToString();
                                        wmsMove.WarehouseId = wmsBaseLocation.warehouseId;
                                        wmsMove.OriLocationCode = wmsBaseLocation.locationCode;
                                        wmsMove.TargetLocationCode = toLocation.locationCode;
                                        wmsMove.InstockBatch = wmsRawStock.instockBatch;
                                        wmsMove.MaterialId = wmsRawStock.materialId;
                                        wmsMove.PlanAmount = 1;
                                        wmsMove.RealOutstockAmount = 1;
                                        wmsMove.RealInstockAmount = 1;
                                        wmsMove.OperationType = "3";
                                        wmsMove.MoveWay = "2";
                                        wmsMove.MoveType = "1";
                                        wmsMove.AuditStatus = "1";
                                        wmsMove.ExecuteStatus = "2";
                                        wmsMove.UpdateBy = "WCS";
                                        wmsMove.UpdateDate = DateTime.Now;
                                        wmsMove.BeginTime = DateTime.Now;
                                        wmsMove.EndTime = DateTime.Now;

                                        WmsMoveDetail wmsMoveDetail = new WmsMoveDetail();
                                        wmsMoveDetail.MoveId = wmsMove.MoveId;
                                        wmsMoveDetail.MaterialBarcode = wmsMove.InstockBatch;
                                        wmsMoveDetail.InstockBatch = wmsMove.InstockBatch;
                                        wmsMoveDetail.MaterialId = (long)wmsRawStock.materialId;
                                        wmsMoveDetail.LocationCode = toLocation.locationCode;
                                        wmsMoveDetail.PlanAmount = 1;
                                        wmsMoveDetail.RealInstockAmount = 1;
                                        wmsMoveDetail.RealAmount = 1;
                                        wmsMoveDetail.ExecuteStatus = "2";
                                        wmsMoveDetail.ExecuteTime = DateTime.Now;
                                        wmsMoveDetail.ExecuteEndTime = DateTime.Now;
                                        wmsMoveDetail.ExecutePerson = "WCS";
                                        wmsMoveDetail.UpdateBy = "WCS";
                                        wmsMoveDetail.UpdateDate = DateTime.Now;

                                        dbContext.WmsMove.Add(wmsMove);
                                        dbContext.WmsMoveDetail.Add(wmsMoveDetail);
                                        #endregion

                                        dbContext.SaveChanges();
                                        dbContextTransaction.Commit();
                                    }
                                    catch (Exception ex)
                                    {
                                        try
                                        {
                                            dbContextTransaction.Rollback();
                                        }
                                        catch
                                        {

                                        }
                                        _logger.Error(ex.Message + "\n" + ex.StackTrace);
                                    }
                                }
                                else if (item.taskType == StaticTaskType.FiveProductOut)//出库
                                {
                                    Console.WriteLine(DateTime.Now + ":五楼AGV线程完成任务" + item.currPointNo + "," + item.endPointNo);
                                    _logger.Info("五楼Agv完成任务成功：" + item.ToJsonString());
                                   
                                    var wmsProductOutstock = dbContext.WmsProductOutstock.FirstOrDefault(t => t.productOutstockId == item.orderId);

                                    if ( wmsProductOutstock != null)
                                    {
                                        var wmsBaseLocation = dbContext.WmsBaseLocation.Where(t => t.locationId == item.currPointId).First();
                                        WmsProductStock wmsProductStock = dbContext.WmsProductStock.First(t => t.locationCode == wmsBaseLocation.locationCode);


                                        wmsProductOutstock.outstockQty += 1;
                                        if (wmsProductOutstock.applyQty <= wmsProductOutstock.outstockQty)
                                        {
                                            wmsProductOutstock.endTime = DateTime.Now;
                                            wmsProductOutstock.executeStatus = "2";
                                        }


                                        WmsProductOutstockDetail newWmsProductOutstockDetail = new WmsProductOutstockDetail();
                                        newWmsProductOutstockDetail.productOutstockId = wmsProductOutstock.productOutstockId;
                                        newWmsProductOutstockDetail.warehouseId = wmsProductOutstock.warehouseId;
                                        newWmsProductOutstockDetail.locationCode = wmsBaseLocation.locationCode;
                                        newWmsProductOutstockDetail.productBarcode = wmsProductStock.productBatch;
                                        newWmsProductOutstockDetail.productId = wmsProductStock.productId;
                                        newWmsProductOutstockDetail.planAmount = wmsProductOutstock.applyQty;
                                        newWmsProductOutstockDetail.outstockAmount = wmsProductOutstock.outstockQty;
                                        newWmsProductOutstockDetail.executeStatus = "2";
                                        newWmsProductOutstockDetail.updateBy = "WCS";
                                        newWmsProductOutstockDetail.updateDate = DateTime.Now;
                                        newWmsProductOutstockDetail.beginTime = DateTime.Now;
                                        newWmsProductOutstockDetail.endTime = DateTime.Now;
                                                   
                                      

                                        wmsBaseLocation.locationStatus = "1";
                                        wmsBaseLocation.containerCode = null;
                                        wmsBaseLocation.updateTime = DateTime.Now;
                                        wmsBaseLocation.updateBy = "WCS";
                                        dbContext.Update(wmsBaseLocation);

                                        SystemData.UnLockOutLocation(wmsBaseLocation, dbContext);

                                        dbContext.WmsProductStock.Where(t => t.locationCode == wmsBaseLocation.locationCode).Delete();
                                        BaseEquip floorLineEquip = StaticData.BaseEquip.First(t => t.equipType == 1 && t.floorNo == 5);
                                        WcsTask newTask = CoreMapper.Map<WcsTask>(item);
                                        newTask.createTime = DateTime.Now;
                                        newTask.nextPointId = floorLineEquip.objid;
                                        newTask.nextPointNo = floorLineEquip.equipNo;
                                        newTask.fromFloorNo = 5;
                                        newTask.floorNo = 1;
                                        newTask.taskStatus = 6;
                                        newTask.objid = StaticData.SnowId.NextId();
                                        dbContext.Add(newWmsProductOutstockDetail);
                                        dbContext.Remove(item);
                                        dbContext.Add(newTask);
                                        WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                        dbContext.Add(wcsTaskLog);
                                        dbContext.SaveChanges();
                                        dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog { taskStatus = 6 });
                                    }
                                }
                                else if (item.taskType == StaticTaskType.FiveRawToBack)//原材料到背板安装
                                {
                                    Console.WriteLine(DateTime.Now + ":五楼AGV线程完成任务" + item.currPointNo + "," + item.endPointNo);
                                    _logger.Info("五楼Agv完成任务成功：" + item.ToJsonString());
                                    WmsRawOutstock? wmsRawOutstock = dbContext.WmsRawOutstock.Where(t => t.rawOutstockId == item.orderId).FirstOrDefault();
                                    if (wmsRawOutstock != null)
                                    {
  
                                            wmsRawOutstock.realOutstockAmount += 1;
                                            wmsRawOutstock.executeStatus = "2";
                                            wmsRawOutstock.endTime = DateTime.Now;
                                           
                                            WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation.First(t => t.locationId == item.currPointId);
                                            SystemData.UnLockOutLocation(wmsBaseLocation, dbContext);
                                            wmsBaseLocation.returnFlag = "0";
                                            wmsBaseLocation.locationStatus = "1";
                                            wmsBaseLocation.containerCode = null;
                                            wmsBaseLocation.updateTime = DateTime.Now;
                                            wmsBaseLocation.updateBy = "WCS";
                                            dbContext.Update(wmsRawOutstock);
                                           
                                            dbContext.Update(wmsBaseLocation);
                                            dbContext.WmsRawStock.Where(t => t.locationCode == wmsBaseLocation.locationCode).Delete();
                                            dbContext.WcsTask.Remove(item);
                                            dbContext.SaveChanges();
                                            dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog { taskStatus = 6 });
                                        
                                    }
                                }
                                else if (item.taskType == StaticTaskType.FiveHalfIn)//半成品入库
                                {
                                    Console.WriteLine(DateTime.Now + ":五楼AGV线程完成任务" + item.currPointNo + "," + item.endPointNo);
                                    _logger.Info("五楼Agv完成任务成功：" + item.ToJsonString());
                                    WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation.First(t => t.locationId == item.endPointId);
                                    wmsBaseLocation.locationStatus = "1";
                                    wmsBaseLocation.containerCode = item.containerNo;
                                    wmsBaseLocation.updateTime = DateTime.Now;
                                    wmsBaseLocation.updateBy = "WCS";
                                    var mesBasePalletInfo = dbContext.MesBasePalletInfo.Where(t => t.palletInfoCode == item.containerNo).FirstOrDefault();
                                    var wmsProductInstock = dbContext.WmsProductInstock
                                        .Where(t => t.executeStatus == "1" && t.productType == "2" && t.warehouseId == 521)
                                        .FirstOrDefault();
                                    if (mesBasePalletInfo != null && wmsProductInstock != null)
                                    {
                                        //WmsProductInstockDetail? wmsProductInstockDetail = dbContext.WmsProductInstockDetail.Where(t => t.productInstockId == wmsProductInstock.productInstockId).FirstOrDefault();
                                        //if (wmsProductInstockDetail != null)
                                        //{
                                        wmsProductInstock.executeStatus = "2";
                                        wmsProductInstock.endTime = DateTime.Now;
                                        dbContext.Update(wmsProductInstock);
                                        WmsProductStock wmsProductStock = new WmsProductStock()
                                        {
                                            productId = wmsProductInstock.productId,
                                            activeFlag = "1",
                                            updateBy = "WCS",
                                            updateDate = DateTime.Now,
                                            saleorderCode = wmsProductInstock.saleorderCode,
                                            saleOrderId = wmsProductInstock.SaleOrderId == null ? 0 : wmsProductInstock.SaleOrderId,
                                            stockType = "2",
                                            productStockId = wmsProductInstock.productInstockId,
                                            qualityStatus = "0",
                                            createBy = "WCS",
                                            createDate = DateTime.Now,
                                            locationCode = wmsBaseLocation.locationCode,
                                            warehouseFloor = 5,
                                            totalAmount = 1,
                                            instockDate = DateTime.Now,
                                            productBatch = mesBasePalletInfo.materialBarcode,
                                            palletInfoCode = mesBasePalletInfo.palletInfoCode,
                                            frozenAmount = 0,
                                            occupyAmount = 0,
                                            planCode = wmsProductInstock.planCode,
                                            planDetailCode = wmsProductInstock.planDetailCode,
                                            warehouseId = 521
                                        };
                                        BaseEquip startEquip = StaticData.BaseEquip.First(t => t.objid == item.currPointId);
                                        //wmsProductInstockDetail.executeStatus = "2";
                                        //wmsProductInstockDetail.instockDate = DateTime.Now;
                                        startEquip.emptyCount = 0;
                                        //dbContext.Update(wmsProductInstockDetail);
                                        dbContext.Update(startEquip);
                                        dbContext.Add(wmsProductStock);
                                        dbContext.Update(wmsBaseLocation);
                                        dbContext.WcsTask.Remove(item);
                                        dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog { taskStatus = 6 });
                                        dbContext.SaveChanges();
                                        //}

                                    }
                                }
                                else if (item.taskType == StaticTaskType.FiveRawToSplit)//原材料到柜体拆分
                                {
                                    Console.WriteLine(DateTime.Now + ":五楼AGV线程完成任务" + item.currPointNo + "," + item.endPointNo);
                                    _logger.Info("五楼Agv完成任务成功：" + item.ToJsonString());
                                    var wmsRawOutStock = dbContext.WmsRawOutstock.Where(t => t.rawOutstockId == item.orderId).FirstOrDefault();

                                    WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation.First(t => t.locationId == item.currPointId);
                                    WmsRawStock? wmsRawStock = dbContext.WmsRawStock.Where(t => t.locationCode == wmsBaseLocation.locationCode).FirstOrDefault();

                                    if (wmsRawOutStock != null && wmsRawStock != null)
                                    {


                                        wmsRawOutStock.realOutstockAmount += 1;
                                        wmsRawOutStock.executeStatus = "2";
                                        wmsRawOutStock.endTime = DateTime.Now;



                                        WmsRawOutstockDetail newWmsRawOutstockDetail = new WmsRawOutstockDetail();
                                        newWmsRawOutstockDetail.rawOutstockId = wmsRawOutStock.rawOutstockId;
                                        newWmsRawOutstockDetail.taskCode = wmsRawOutStock.taskCode;
                                        newWmsRawOutstockDetail.warehouseId = wmsRawOutStock.warehouseId;
                                        newWmsRawOutstockDetail.locationCode = wmsRawStock.locationCode;
                                        newWmsRawOutstockDetail.materialBarcode = wmsRawStock.instockBatch;
                                        newWmsRawOutstockDetail.materialId = wmsRawStock.materialId;
                                        MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.Where(t => t.barcodeInfo == wmsRawStock.instockBatch).FirstOrDefault();
                                        if (mesBaseBarcodeInfo != null)
                                        {
                                            newWmsRawOutstockDetail.instockBatch = mesBaseBarcodeInfo.batchCode;
                                            newWmsRawOutstockDetail.materialProductionDate = mesBaseBarcodeInfo.productionDate;
                                        }
                                        newWmsRawOutstockDetail.planAmount = wmsRawOutStock.outstockAmount;
                                        newWmsRawOutstockDetail.outstockAmount = wmsRawOutStock.realOutstockAmount;
                                        newWmsRawOutstockDetail.executeStatus = "2";
                                        newWmsRawOutstockDetail.outstockPerson = wmsRawOutStock.applyBy;
                                        newWmsRawOutstockDetail.outstockTime = DateTime.Now;
                                        newWmsRawOutstockDetail.outstockWay = "2";
                                        newWmsRawOutstockDetail.createBy = "WCS";
                                        newWmsRawOutstockDetail.createDate = DateTime.Now;
                                        newWmsRawOutstockDetail.stackAmount = 1;

   

                                        wmsBaseLocation.locationStatus = "1";
                                        wmsBaseLocation.containerCode = null;
                                        wmsBaseLocation.updateTime = DateTime.Now;
                                        wmsBaseLocation.updateBy = "WCS";
                                        SystemData.UnLockOutLocation(wmsBaseLocation, dbContext);
                                        dbContext.Update(wmsRawOutStock);
                                        dbContext.Add(newWmsRawOutstockDetail);
                                        dbContext.Remove(wmsRawStock);
                                        dbContext.Update(wmsBaseLocation);
                                        dbContext.Remove(item);
                                        dbContext.SaveChanges();
                                        dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog { taskStatus = 6 });

                                    }
                                }
                                else if (item.taskType == StaticTaskType.FiveRawSplitReturn)//柜体拆分到原材料
                                {
                                    Console.WriteLine(DateTime.Now + ":五楼AGV线程完成任务" + item.currPointNo + "," + item.endPointNo);
                                    _logger.Info("五楼Agv完成任务成功：" + item.ToJsonString());
                                    WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation.First(t => t.locationId == item.endPointId);
                                    wmsBaseLocation.locationStatus = "1";
                                    wmsBaseLocation.returnFlag = "1";
                                    wmsBaseLocation.containerCode = item.containerNo;
                                    wmsBaseLocation.updateTime = DateTime.Now;
                                    wmsBaseLocation.updateBy = "WCS";
                                    MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.FirstOrDefault(t => t.palletInfoCode == item.containerNo);
                                    if (mesBasePalletInfo != null)
                                    {
                                        MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == mesBasePalletInfo.materialBarcode);
                                        if (mesBaseBarcodeInfo != null)
                                        {
                                            WmsRawStock wmsRawStock = new()
                                            {
                                                palletInfoCode = mesBasePalletInfo.palletInfoCode,
                                                activeFlag = "1",
                                                createBy = "WCS",
                                                createDate = DateTime.Now,
                                                frozenAmount = 0,
                                                instockDate = DateTime.Now,
                                                locationCode = wmsBaseLocation.locationCode,
                                                occupyAmount = 0,
                                                warehouseFloor = 5,
                                                stockType = "1",
                                                totalAmount = 1,
                                                saleOrderId = mesBaseBarcodeInfo.saleOrderId == null ? 0 : mesBaseBarcodeInfo.saleOrderId,
                                                safeFlag = mesBaseBarcodeInfo.safeFlag,
                                                supplierId = mesBaseBarcodeInfo.manufacturerId,
                                                materialId = mesBasePalletInfo.materialId,
                                                qualityStatus = "0",
                                                rawStockId = StaticData.SnowId.NextId(),
                                                completeFlag = "0",
                                                instockBatch = mesBaseBarcodeInfo.barcodeInfo,
                                                updateBy = "WCS",
                                                updateDate = DateTime.Now,
                                                warehouseId = 511,
                                            };
                                            WmsRawInstock? WmsRawInstock = dbContext.WmsRawInstock.FirstOrDefault(t => t.materialBarCode == mesBasePalletInfo.materialBarcode && t.instockType == "2");
                                            WmsRawInstock.returnFlag = null;
                                            WmsRawInstock.executeStatus = "2";
                                            WmsRawInstock.updateDate = DateTime.Now;
                                          
                                            SystemData.UnLockOutLocation(wmsBaseLocation, dbContext);
                                            dbContext.Update(WmsRawInstock);
                                            dbContext.Add(wmsRawStock);
                                            BaseEquip startEquip = StaticData.BaseEquip.First(t => t.objid == item.currPointId);
                                            startEquip.emptyCount = 0;
                                            dbContext.Update(startEquip);
                                            dbContext.Update(wmsBaseLocation);
                                            dbContext.Remove(item);
                                            dbContext.SaveChanges();
                                            dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog { taskStatus = 6 });
                                        }
                                    }

                                }
                                else if (item.taskType == StaticTaskType.FiveRawIn)//原材料入库
                                {
                                    Console.WriteLine(DateTime.Now + ":五楼AGV线程完成任务" + item.currPointNo + "," + item.endPointNo);
                                    _logger.Info("五楼Agv完成任务成功：" + item.ToJsonString());
                                    WmsBaseLocation wmsBaseLocation = dbContext.WmsBaseLocation.First(t => t.locationId == item.endPointId);
                                    wmsBaseLocation.locationStatus = "1";
                                    wmsBaseLocation.containerCode = item.containerNo;
                                    var mesBasePalletInfo = dbContext.MesBasePalletInfo.FirstOrDefault(t => t.palletInfoCode == item.containerNo);
                                    if (mesBasePalletInfo != null)
                                    {
                                        var mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == mesBasePalletInfo.materialBarcode);
                                        if (mesBaseBarcodeInfo != null)
                                        {
                                           
                                            if (mesBaseBarcodeInfo.PurchaseOrderId == -1)
                                            {   // 虚拟托盘号,合并的物料分别插入WmsRawInstock
                                                List<MesSaleOrderRelate> mesSaleOrderRelates = dbContext.MesSaleOrderRelate.Where(x => x.SaleOrderId == mesBaseBarcodeInfo.saleOrderId).ToList();
                                                List<WmsRawInstock>? wmsRawInstocks = new List<WmsRawInstock>();
                                                foreach(var mesSaleOrderRelate in mesSaleOrderRelates)
                                                {
                                                    WmsRawInstock wmsRawInstock = new WmsRawInstock()
                                                    {
                                                        taskCode = StaticData.SnowId.NextId().ToString(),
                                                        materialBarCode = null,
                                                        materialBatchCode = null,
                                                        applyBy = "wcs",
                                                        applyDate = System.DateTime.Now,
                                                        purchaseOrderId = mesSaleOrderRelate.PurchaseOrderId,
                                                        beginTime = DateTime.Now,
                                                        endTime = DateTime.Now,
                                                        locationCode = wmsBaseLocation.locationCode,
                                                        executeStatus = "2",
                                                        instockAmount = mesSaleOrderRelate.RelateSaleOrderAmount,
                                                        instockType = "1",

                                                        materialId = mesSaleOrderRelate.MaterialId,
                                                        operationType = "3",
                                                        palletInfoCode = mesBaseBarcodeInfo.palletInfoCode,
                                                        poNo = mesBaseBarcodeInfo.poNo,
                                                        warehouseId = 511
                                                    };
                                                    wmsRawInstocks.Add(wmsRawInstock);  
                                                }
                                                if(wmsRawInstocks.Count > 0)
                                                {
                                                    dbContext.WmsRawInstock.AddRange(wmsRawInstocks);
                                                }
                                            }
                                            else
                                            {
                                                WmsRawInstock wmsRawInstock = new WmsRawInstock()
                                                {
                                                    taskCode = StaticData.SnowId.NextId().ToString(),
                                                    materialBarCode = mesBaseBarcodeInfo.barcodeInfo,
                                                    materialBatchCode = mesBaseBarcodeInfo.batchCode,
                                                    applyBy = "wcs",
                                                    applyDate = System.DateTime.Now,
                                                    purchaseOrderId = mesBaseBarcodeInfo.PurchaseOrderId,
                                                    beginTime = DateTime.Now,
                                                    endTime = DateTime.Now,
                                                    locationCode = wmsBaseLocation.locationCode,
                                                    executeStatus = "2",
                                                    instockAmount = 1,
                                                    instockType = "1",

                                                    materialId = mesBaseBarcodeInfo.materialId,
                                                    operationType = "3",
                                                    palletInfoCode = mesBaseBarcodeInfo.palletInfoCode,
                                                    poNo = mesBaseBarcodeInfo.poNo,
                                                    warehouseId = 511
                                                };
                                                dbContext.Add(wmsRawInstock);

                                            }

                                            WmsRawStock wmsRawStock = new()
                                            {
                                                palletInfoCode = mesBasePalletInfo.palletInfoCode,
                                                activeFlag = "1",
                                                createBy = "WCS",
                                                createDate = DateTime.Now,
                                                frozenAmount = 0,
                                                instockDate = DateTime.Now,
                                                locationCode = wmsBaseLocation.locationCode,
                                                occupyAmount = 0,
                                                warehouseFloor = 5,
                                                stockType = "1",
                                                totalAmount = 1,
                                                saleOrderId = mesBaseBarcodeInfo.saleOrderId == null ? 0 : mesBaseBarcodeInfo.saleOrderId,
                                                safeFlag = mesBaseBarcodeInfo.safeFlag,
                                                supplierId = mesBaseBarcodeInfo.manufacturerId,
                                                materialId = mesBasePalletInfo.materialId,
                                                qualityStatus = "0",
                                                rawStockId = StaticData.SnowId.NextId(),
                                                completeFlag = mesBaseBarcodeInfo.completeFlag,
                                                instockBatch = mesBaseBarcodeInfo.barcodeInfo,
                                                updateBy = "WCS",
                                                updateDate = DateTime.Now,
                                                warehouseId = 511,
                                            };
                                            SystemData.UnLockOutLocation(wmsBaseLocation, dbContext);
                                            
                                            wmsBaseLocation.returnFlag = "0";
                                            BaseEquip lineEquip = dbContext.BaseEquip.First(t => t.objid == 5);
                                            lineEquip.equipStatus = 0;
                                            dbContext.Update(lineEquip);
                                            dbContext.Add(wmsRawStock);
                                            dbContext.Update(wmsBaseLocation);
                                            dbContext.Remove(item);
                                            dbContext.SaveChanges();
                                            dbContext.WcsTaskLog.Where(t => t.objid == item.objid).Update(t => new WcsTaskLog { taskStatus = 6 });
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (ex is PlcException)
                    {

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

    }
}
