using Khd.Core.Domain.Dto.TaskType;
using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Library;
using Khd.Core.Library.Mapper;
using Khd.Core.Wcs.Global;
using Masuit.Tools;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SixLabors.ImageSharp;
using System.Data;
using System.Drawing.Text;
using Z.EntityFramework.Plus;

namespace Khd.Core.Wcs.Wcs
{
    /// <summary>
    /// 根据出入库记录创建出入库任务
    /// </summary>
    public class CreateTaskByRecord
    {
        private readonly LoggerUtils _logger = new LoggerUtils();
        private readonly IHost _host;
        public CreateTaskByRecord(IHost host)
        {
            this._host = host;
        }

        /// <summary>
        /// 启动上件扫描监听
        /// </summary>
        public void StartPoint()
        {
            //var createRemoveThread = new Thread(CreateRemoveLogic);
            //createRemoveThread.IsBackground = true;
            //createRemoveThread.Name = "CreateRemoveLogic";
            //createRemoveThread.Start();

            //背负式Agv返库任务
            var createBearAgvReturnThread = new Thread(CreateBearAgvReturnLogic);
            createBearAgvReturnThread.IsBackground = true;
            createBearAgvReturnThread.Name = "CreateBearAgvReturnLogic";
            createBearAgvReturnThread.Start();
            //五楼半成品入库任务
            var createFiveProductInTaskThread = new Thread(CreateFiveProductInTaskLogic);
            createFiveProductInTaskThread.IsBackground = true;
            createFiveProductInTaskThread.Name = "CreateFiveProductInTaskLogic";
            createFiveProductInTaskThread.Start();
            //五楼成品出库任务
            var createFiveProductTaskThread = new Thread(CreateFiveProductTaskLogic);
            createFiveProductTaskThread.IsBackground = true;
            createFiveProductTaskThread.Name = "CreateFiveProductTaskLogic";
            createFiveProductTaskThread.Start();
            //五楼CTU出库任务以及原材料出库任务
            var createRawTaskThread = new Thread(CreateRawTaskLogic);
            createRawTaskThread.IsBackground = true;
            createRawTaskThread.Name = "CreateRawTaskLogic";
            createRawTaskThread.Start();
            //五楼柜体拆分返库任务
            var createRawInThread = new Thread(CreateRawInTaskLogic);
            createRawInThread.IsBackground = true;
            createRawInThread.Name = "CreateRawInTaskLogic";
            createRawInThread.Start();
            //三楼去翻转机任务
            var createThirdOutTaskThread = new Thread(CreateThirdOutTaskLogic);
            createThirdOutTaskThread.IsBackground = true;
            createThirdOutTaskThread.Name = "CreateThirdOutTaskLogic";
            createThirdOutTaskThread.Start();
            //二楼成品出库任务
            var CreateSecondProductTaskThread = new Thread(CreateSecondProductTaskLogic);
            CreateSecondProductTaskThread.IsBackground = true;
            CreateSecondProductTaskThread.Name = "CreateSecondProductTaskLogic";
            CreateSecondProductTaskThread.Start();
            //三楼托盘收集架满5个或10个时出库合盘任务
            var createEmptyTrayThread = new Thread(CreateEmptyTrayLogic);
            createEmptyTrayThread.IsBackground = true;
            createEmptyTrayThread.Name = "CreateEmptyTrayLogic";
            createEmptyTrayThread.Start();
            //二楼废品区人工调度任务
            var createThirdWasterTaskThread = new Thread(CreateThirdWasterTaskLogic);
            createThirdWasterTaskThread.IsBackground = true;
            createThirdWasterTaskThread.Name = "CreateThirdWasterTaskLogic";
            createThirdWasterTaskThread.Start();
            //背负式退库
            var BackReturnTaskThread = new Thread(BackReturnTaskLogic);
            BackReturnTaskThread.IsBackground = true;
            BackReturnTaskThread.Name = "BackReturnTaskLogic";
            BackReturnTaskThread.Start();
            Console.WriteLine(DateTime.Now + ":出库任务监听启动成功");
            _logger.Info("出库任务监听启动成功");
        }

        /// <summary>
        /// 主动移库
        /// </summary>
        /// <param name="obj"></param>
        private void CreateRemoveLogic(object? obj)
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            List<string> cannotIn = new List<string>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    var CanRemoveWmsBaseLocations = dbContext.WmsBaseLocation.Where(t => t.locationStatus == "7").ToList();
                    List<string> locationCodes = CanRemoveWmsBaseLocations.Select(t => t.locationCode).ToList();
                    List<WmsProductStock> CanRemoveWmsProductStocks = dbContext.WmsProductStock.Where(t => locationCodes.Contains(t.locationCode)).ToList();
                    foreach (var wmsProductStock in CanRemoveWmsProductStocks)
                    {
                        BaseEquip? agvEquip = null;
                        if (wmsProductStock.warehouseId == 531)
                        {
                            agvEquip = StaticData.BaseEquip.First(t => t.objid == 28);
                        }
                        else if (wmsProductStock.warehouseId == 231)
                        {
                            agvEquip = StaticData.BaseEquip.First(t => t.objid == 8);
                        }
                        if (agvEquip != null)
                        {
                            bool hasTask = dbContext.WcsTask.Where(t => t.nextPointId == agvEquip.objid).Any();
                            if (!hasTask)
                            {
                                WmsBaseLocation fromLocationCode = CanRemoveWmsBaseLocations.First(t => t.locationCode == wmsProductStock.locationCode);
                                if (wmsProductStock.warehouseId == 531 || wmsProductStock.warehouseId == 231)//成品移库
                                {
                                    var wmsBaseLocations = dbContext.WmsBaseLocation
                                                       .Where(t => t.activeFlag == "1")
                                                       .Where(t => t.delFlag == "0")
                                                       .Where(t => t.locationScrapType == "1")
                                                       .Where(t => t.locationStatus == "1")
                                                       .Where(t => t.warehouseId == wmsProductStock.warehouseId)
                                                       .ToList();//所有可用库位
                                    var wmsProductStocks = dbContext.WmsProductStock
                                        .Where(t => t.warehouseId == wmsProductStock.warehouseId)
                                        .ToList();//仓库的库存
                                    WmsBaseLocation? wmsBaseLocation = null;
                                    if (wmsBaseLocations.Count > 0)
                                    {
                                        List<string> containerCodes = wmsBaseLocations
                                                .Where(t => t.locDeep == 1)
                                                .Select(t => t.containerCode).ToList();//深库位的有托盘

                                        List<MesBaseBarcodeInfo> mesBasePalletInfos = dbContext.MesBaseBarcodeInfo
                                            .Where(t => t.saleOrderId == (wmsProductStock.saleOrderId == null ? 0 : wmsProductStock.saleOrderId))//销售订单
                                            .Where(t => t.materialId == wmsProductStock.productId)//物料Id
                                            .Where(t => containerCodes.Contains(t.palletInfoCode)).ToList();//深库位的托盘的物料等于当前任务的物料

                                        var bill = from a in mesBasePalletInfos
                                                   join b in wmsBaseLocations.Where(t => t.locDeep == 1) on a.palletInfoCode equals b.containerCode
                                                   select new { b };//等于当前任务的物料的托盘的库位信息

                                        var outBill = from a in bill//深库位托盘和当前任务绑定物料一致的托盘库位
                                                      from b in wmsBaseLocations//所有库位
                                                      where b.locDeep == 2//浅库位
                                                      && b.locRow == (a.b.locRow % 2 == 0 ? a.b.locRow - 1 : a.b.locRow + 1)
                                                      //如果是4则找3，如果是1则找2
                                                      && a.b.locColumn == b.locColumn//列数相同
                                                      && string.IsNullOrEmpty(b.containerCode)
                                                      select new { a, b };//在上面的基础上获取对应托盘的外侧库位的空库位信息
                                        wmsBaseLocation ??= outBill.Where(t => !cannotIn.Contains(t.b.locationCode)).FirstOrDefault()?.b;//先找相同物料的外侧库位
                                        wmsBaseLocation ??= wmsBaseLocations.Where(t => !cannotIn.Contains(t.locationCode)).Where(t => string.IsNullOrEmpty(t.containerCode)).FirstOrDefault(t => t.locDeep == 1);//找不到再找深库位
                                        wmsBaseLocation ??= wmsBaseLocations.Where(t => !cannotIn.Contains(t.locationCode)).Where(t => string.IsNullOrEmpty(t.containerCode)).FirstOrDefault();//找不到再找任意库位
                                        if (wmsBaseLocation != null)//如果找到库位，生成入库任务
                                        {
                                            if (wmsBaseLocation.locDeep == 1)
                                            {
                                                bool hasLocation = wmsBaseLocations
                                                .Where(t => t.locRow == (wmsBaseLocation.locRow % 2 == 1 ? (wmsBaseLocation.locRow + 1) : (wmsBaseLocation.locRow - 1)))
                                                .Where(t => t.locColumn == wmsBaseLocation.locColumn)
                                                    .Any();
                                                if (!hasLocation)
                                                {
                                                    cannotIn.Add(wmsBaseLocation.locationCode);
                                                    Console.WriteLine(DateTime.Now + $":目标库位{cannotIn.Join(",")}的浅库位库位状态异常，无法移库");
                                                    _logger.Info($"目标库位{cannotIn.Join(",")}的浅库位库位状态异常，无法移库");
                                                    continue;
                                                }
                                            }
                                            var wcsTask = new WcsTask()
                                            {
                                                objid = StaticData.SnowId.NextId(),
                                                currPointId = fromLocationCode.locationId,
                                                currPointNo = fromLocationCode.locationCode,
                                                nextPointId = agvEquip.objid,
                                                nextPointNo = agvEquip.equipNo,
                                                endPointId = wmsBaseLocation.locationId,
                                                endPointNo = wmsBaseLocation.locationCode,
                                                taskStatus = 0,
                                                useFlag = 1,
                                                containerNo = wmsProductStock.palletInfoCode,
                                                createBy = "WCS",
                                                createTime = DateTime.Now,
                                                isEmpty = "0",
                                                taskType = agvEquip.objid == 28 ? StaticTaskType.FiveRemove : StaticTaskType.SecondRemove,
                                                qty = 1,
                                            };
                                            fromLocationCode.locationStatus = "4";
                                            dbContext.Update(fromLocationCode);
                                            wmsBaseLocation.locationStatus = "4";
                                            dbContext.Update(wmsBaseLocation);
                                            dbContext.Add(wcsTask);
                                            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                            dbContext.Add(wcsTaskLog);
                                            dbContext.SaveChanges();
                                            cannotIn.Clear();
                                            Console.WriteLine(DateTime.Now + ":二楼码垛输送线生成入库托盘任务成功:" + wcsTask.objid);
                                            _logger.Info("二楼码垛输送线生成入库托盘任务成功:" + wcsTask.objid);
                                        }
                                        else
                                        {
                                            //报警
                                        }
                                    }
                                }
                            }
                        }
                    }

                    List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock.Where(t => locationCodes.Contains(t.locationCode)).ToList();
                    foreach (var wmsRawStock in wmsRawStocks)
                    {

                        WmsBaseLocation fromLocationCode = CanRemoveWmsBaseLocations.First(t => t.locationCode == wmsRawStock.locationCode);
                        if (wmsRawStock.warehouseId == 511 || wmsRawStock.warehouseId == 311)
                        {
                            BaseEquip? agvEquip = null;
                            if (wmsRawStock.warehouseId == 511)
                            {
                                agvEquip = StaticData.BaseEquip.First(t => t.objid == 28);
                            }
                            else if (wmsRawStock.warehouseId == 311)
                            {
                                agvEquip = StaticData.BaseEquip.First(t => t.objid == 9);
                            }
                            if (agvEquip != null)
                            {
                                bool hasTask = dbContext.WcsTask.Where(t => t.nextPointId == agvEquip.objid).Any();
                                if (!hasTask)
                                {
                                    var wmsBaseLocations = dbContext.WmsBaseLocation
                                                  .Where(t => t.activeFlag == "1")
                                                  .Where(t => t.delFlag == "0")
                                                  .Where(t => t.locationScrapType == "1")
                                                  .Where(t => t.locationStatus == "1")
                                                  .Where(t => t.warehouseId == wmsRawStock.warehouseId)
                                                  .ToList();//所有可用库位
                                    var wmsProductStocks = dbContext.WmsRawStock
                                                .Where(t => t.warehouseId == wmsRawStock.warehouseId)
                                                .ToList();//仓库的库存
                                    WmsBaseLocation? wmsBaseLocation = null;
                                    if (wmsBaseLocations.Count > 0)
                                    {
                                        List<string> containerCodes = wmsBaseLocations
                                                .Where(t => t.locDeep == 1)
                                                .Select(t => t.containerCode).ToList();//深库位的有托盘

                                        List<MesBaseBarcodeInfo> mesBasePalletInfos = dbContext.MesBaseBarcodeInfo
                                            .Where(t => t.saleOrderId == (wmsRawStock.saleOrderId == null ? 0 : wmsRawStock.saleOrderId))//销售订单
                                            .Where(t => t.materialId == wmsRawStock.materialId)//物料Id
                                            .Where(t => containerCodes.Contains(t.palletInfoCode)).ToList();//深库位的托盘的物料等于当前任务的物料

                                        var bill = from a in mesBasePalletInfos
                                                   join b in wmsBaseLocations.Where(t => t.locDeep == 1) on a.palletInfoCode equals b.containerCode
                                                   select new { b };//等于当前任务的物料的托盘的库位信息

                                        var outBill = from a in bill//深库位托盘和当前任务绑定物料一致的托盘库位
                                                      from b in wmsBaseLocations//所有库位
                                                      where b.locDeep == 2//浅库位
                                                      && b.locRow == (a.b.locRow % 2 == 0 ? a.b.locRow - 1 : a.b.locRow + 1)
                                                      //如果是4则找3，如果是1则找2
                                                      && a.b.locColumn == b.locColumn//列数相同
                                                      && string.IsNullOrEmpty(b.containerCode)
                                                      select new { a.b };//在上面的基础上获取对应托盘的外侧库位的空库位信息

                                        wmsBaseLocation ??= outBill.FirstOrDefault()?.b;//先找相同物料的外侧库位
                                        wmsBaseLocation ??= wmsBaseLocations.Where(t => string.IsNullOrEmpty(t.containerCode)).FirstOrDefault(t => t.locDeep == 1);//找不到再找深库位
                                        wmsBaseLocation ??= wmsBaseLocations.Where(t => string.IsNullOrEmpty(t.containerCode)).FirstOrDefault();//找不到再找任意库位
                                        if (wmsBaseLocation != null)//如果找到库位，生成入库任务
                                        {
                                            if (wmsBaseLocation.locDeep == 1)
                                            {
                                                bool hasLocation = wmsBaseLocations
                                                .Where(t => t.locRow == (wmsBaseLocation.locRow % 2 == 1 ? (wmsBaseLocation.locRow + 1) : (wmsBaseLocation.locRow - 1)))
                                                .Where(t => t.locColumn == wmsBaseLocation.locColumn)
                                                    .Any();
                                                if (!hasLocation)
                                                {
                                                    Console.WriteLine(DateTime.Now + $":目标库位{wmsBaseLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                    _logger.Info($"目标库位{wmsBaseLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                    continue;
                                                }
                                            }
                                            var wcsTask = new WcsTask()
                                            {
                                                objid = StaticData.SnowId.NextId(),
                                                currPointId = fromLocationCode.locationId,
                                                currPointNo = fromLocationCode.locationCode,
                                                nextPointId = agvEquip.objid,
                                                nextPointNo = agvEquip.equipNo,
                                                endPointId = wmsBaseLocation.locationId,
                                                endPointNo = wmsBaseLocation.locationCode,
                                                taskStatus = 0,
                                                useFlag = 1,
                                                containerNo = wmsRawStock.palletInfoCode,
                                                createBy = "WCS",
                                                createTime = DateTime.Now,
                                                isEmpty = "0",
                                                taskType = agvEquip.objid == 28 ? StaticTaskType.FiveRemove : StaticTaskType.ThirdRemove,
                                                qty = 1,
                                            };
                                            fromLocationCode.locationStatus = "4";
                                            dbContext.Update(fromLocationCode);
                                            wmsBaseLocation.locationStatus = "4";
                                            dbContext.Update(wmsBaseLocation);
                                            dbContext.Add(wcsTask);
                                            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                            dbContext.Add(wcsTaskLog);
                                            dbContext.SaveChanges();
                                            Console.WriteLine(DateTime.Now + ":二楼码垛输送线生成入库托盘任务成功:" + wcsTask.objid);
                                            _logger.Info("二楼码垛输送线生成入库托盘任务成功:" + wcsTask.objid);
                                        }
                                        else
                                        {
                                            //报警
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {

                }
            }
        }

        /// <summary>
        /// 五楼柜体拆分返库任务
        /// </summary>
        private void CreateRawInTaskLogic()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            List<string> cannotIn = new List<string>();
            while (true)
            {
                try
                {
                    lock (SystemData.FiveTaskLock)
                    {
                        dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                        BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 29);
                        if (baseEquip.emptyCount == 1)
                        {
                            WcsTask? wcsTask = dbContext.WcsTask.Where(t => t.nextPointId == 28).FirstOrDefault();
                            if (wcsTask == null)
                            {
                                WmsRawInstock? wmsRawInstock = dbContext.WmsRawInstock.Where(t => t.warehouseId == 511 && t.instockType == "2" && t.executeStatus == "0").FirstOrDefault();
                                if (wmsRawInstock != null)
                                {
                                    MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.FirstOrDefault(t => t.palletInfoCode == wmsRawInstock.palletInfoCode);
                                    if (mesBasePalletInfo != null)
                                    {
                                        MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == mesBasePalletInfo.materialBarcode);
                                        if (mesBaseBarcodeInfo != null)
                                        {
                                            var wmsBaseLocations = dbContext.WmsBaseLocation.Where(t => t.warehouseFloor == 5)
                                               .Where(t => t.activeFlag == "1")
                                               .Where(t => t.delFlag == "0")
                                               .Where(t => t.locationScrapType == "1")
                                               .Where(t => t.warehouseId == 511)
                                               .Where(t => t.locationStatus == "1")
                                               .OrderByDescending(t => t.locColumn)
                                               .ToList();

                                            List<string> containerCodes = wmsBaseLocations
                                                             .Where(t => t.locDeep == 1)
                                                             .Select(t => t.containerCode).ToList();//深库位的托盘
                                            containerCodes.RemoveAll(t => string.IsNullOrEmpty(t));
                                            List<MesBaseBarcodeInfo> mesBasePalletInfos = dbContext.MesBaseBarcodeInfo
                                                .Where(t => t.materialId == mesBasePalletInfo.materialId)
                                                .Where(t => t.saleOrderId == mesBaseBarcodeInfo.saleOrderId)
                                                .Where(t => containerCodes.Contains(t.palletInfoCode)).ToList();//深库位的托盘的物料等于当前任务的物料

                                            var bill = from a in mesBasePalletInfos
                                                       join b in wmsBaseLocations.Where(t => t.locDeep == 1 && t.returnFlag == "1") on a.palletInfoCode equals b.containerCode
                                                       select new { b };//等于当前任务的物料的托盘的库位信息

                                            var outBill = from a in bill
                                                          from b in wmsBaseLocations
                                                          where b.locDeep == 2
                                                          && b.locRow == (a.b.locRow % 2 == 0 ? a.b.locRow - 1 : a.b.locRow + 1)
                                                          && a.b.locColumn == b.locColumn
                                                          && b.locationStatus == "1"
                                                          && string.IsNullOrEmpty(b.containerCode)
                                                          select new { a, b };//在上面的基础上获取对应托盘的外侧库位的空库位信息

                                            WmsBaseLocation? wmsBaseLocation = null;
                                            wmsBaseLocation ??= outBill.Where(t => !cannotIn.Contains(t.b.locationCode)).FirstOrDefault()?.b;//先找相同物料的外侧库位
                                            wmsBaseLocation ??= wmsBaseLocations.Where(t => !cannotIn.Contains(t.locationCode)).Where(t => string.IsNullOrEmpty(t.containerCode)).FirstOrDefault(t => t.locDeep == 1);//找不到再找深库位
                                            wmsBaseLocation ??= wmsBaseLocations.Where(t => !cannotIn.Contains(t.locationCode)).Where(t => string.IsNullOrEmpty(t.containerCode)).FirstOrDefault();//找不到再找任意库位
                                                                                                                                                                                                   //深浅库位问题？库位入库优先级等

                                            var AgvEquip = StaticData.BaseEquip.First(t => t.objid == 28);//5楼叉车
                                            if (wmsBaseLocation != null)
                                            {
                                                if (wmsBaseLocation.locDeep == 1)
                                                {
                                                    bool hasLocation = wmsBaseLocations
                                                        .Where(t => t.locRow == (wmsBaseLocation.locRow % 2 == 1 ? (wmsBaseLocation.locRow + 1) : (wmsBaseLocation.locRow - 1)))
                                                        .Where(t => t.locColumn == wmsBaseLocation.locColumn).Any();
                                                    if (!hasLocation)
                                                    {
                                                        cannotIn.Add(wmsBaseLocation.locationCode);
                                                        Console.WriteLine(DateTime.Now + $":目标库位{cannotIn.Join(",")}的浅库位库位状态异常，无法入库");
                                                        _logger.Info($"目标库位{cannotIn.Join(",")}的浅库位库位状态异常，无法入库");
                                                        continue;
                                                    }
                                                }
                                                WcsTask newTask = new WcsTask();
                                                newTask.taskStatus = 0;//创建状态
                                                newTask.updateTime = DateTime.Now;
                                                newTask.currPointId = baseEquip.objid;
                                                newTask.currPointNo = baseEquip.equipNo;
                                                newTask.nextPointId = AgvEquip.objid;
                                                newTask.nextPointNo = AgvEquip.equipNo;
                                                newTask.endPointId = wmsBaseLocation.locationId;
                                                newTask.endPointNo = wmsBaseLocation.locationCode;
                                                newTask.containerNo = mesBasePalletInfo.palletInfoCode;
                                                newTask.materialId = mesBasePalletInfo.materialId;
                                                newTask.objid = StaticData.SnowId.NextId();
                                                newTask.createTime = DateTime.Now;
                                                newTask.taskType = StaticTaskType.FiveRawSplitReturn;
                                                newTask.useFlag = 1;
                                                wmsBaseLocation.locationStatus = "2";
                                                WmsRawInstockDetail wmsRawInstockDetail = new WmsRawInstockDetail
                                                {
                                                    rawInstockDetailId = StaticData.SnowId.NextId(),
                                                    stackAmount = 1,
                                                    erpStatus = "0",
                                                    executeStatus = "1",
                                                    qualityStatus = "0",
                                                    activeFlag = "1",
                                                    createBy = "WCS",
                                                    createDate = DateTime.Now,
                                                    erpAmount = 0,
                                                    instockAmount = 1,
                                                    instockBatch = mesBasePalletInfo.materialBarcode,
                                                    instockTime = DateTime.Now,
                                                    instockWay = "2",
                                                    locationCode = newTask.endPointNo,
                                                    machineName = mesBaseBarcodeInfo.machineName,
                                                    materialBarcode = mesBasePalletInfo.materialBarcode,
                                                    materialId = mesBaseBarcodeInfo.materialId,
                                                    materialProductionDate = mesBaseBarcodeInfo.productionDate,
                                                    planAmount = 1,
                                                    poNo = mesBaseBarcodeInfo.poNo,
                                                    rawInstockId = wmsRawInstock.rawInstockId,
                                                    taskCode = wmsRawInstock.taskCode,
                                                };
                                                SystemData.LockOutLocation(wmsBaseLocation, dbContext);
                                                dbContext.Add(wmsRawInstockDetail);
                                                dbContext.Update(wmsBaseLocation);
                                                dbContext.Add(newTask);
                                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                                dbContext.Add(wcsTaskLog);
                                                dbContext.SaveChanges();
                                                cannotIn.Clear();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 根据人工任务生成可执行任务
        /// </summary>
        /// <param name="obj"></param>
        private void CreateThirdWasterTaskLogic()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    bool hasTask = dbContext.WcsTask.Where(t => t.nextPointId == 9).Any();
                    if (!hasTask)
                    {
                        WcsTaskManual? wcsTaskManual = dbContext.WcsTaskManual.Where(t => t.nextPointId == 9 || t.nextPointId == 8).OrderBy(t => t.createBy).FirstOrDefault();
                        if (wcsTaskManual != null)
                        {
                            var equip = dbContext.BaseEquip.Where(t => t.objid == wcsTaskManual.endPointId).FirstOrDefault();
                            if (equip != null && equip.equipStatus == 0)
                            {
                                WcsTask wcsTask = CoreMapper.Map<WcsTask>(wcsTaskManual);
                                wcsTask.createTime = DateTime.Now;
                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                dbContext.Add(wcsTask);
                                dbContext.Add(wcsTaskLog);
                                dbContext.Remove(wcsTaskManual);
                                dbContext.SaveChanges();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 3楼托盘库出库任务
        /// </summary>
        /// <param name="obj"></param>
        private void CreateEmptyTrayLogic()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            BaseEquip agvEquip = StaticData.BaseEquip.First(t => t.objid == 9);
            while (true)
            {
                try
                {
                    bool isCreate = false;
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    bool canCreate = dbContext.WcsTask.Where(t => t.nextPointId == 9)
                        .Where(t => t.useFlag == 1)
                        .Where(t => t.taskStatus <= 6).Any();
                    if (!canCreate)
                    {
                        BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 35);
                        #region 原逻辑
                        //if (baseEquip.emptyCount == (SystemData.maxTray / 2))
                        //{
                        //    var endEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipType == 15 && t.equipStatus == 1 && t.emptyCount == (SystemData.maxTray / 2));
                        //    if (endEquip != null)
                        //    {
                        //        var wcsTask = new WcsTask()
                        //        {
                        //            objid = StaticData.SnowId.NextId(),
                        //            serialNo = SystemData.GetSerialNo(dbContext),
                        //            taskType = 40,
                        //            nextPointId = agvEquip.objid,
                        //            nextPointNo = agvEquip.equipNo,
                        //            endPointId = baseEquip.objid,
                        //            endPointNo = baseEquip.equipNo,
                        //            currPointId = endEquip.objid,
                        //            currPointNo = endEquip.equipNo,
                        //            equipmentNo = agvEquip.equipNo,
                        //            useFlag = 1,
                        //            qty = 5,
                        //            isEmpty = "1",
                        //            taskStatus = 0,
                        //            createBy = "WCS",
                        //            createTime = DateTime.Now,
                        //            floorNo = 3,
                        //            fromFloorNo = 3,
                        //            masterId = 0,
                        //            orderId = 0,
                        //            materialId = 0,
                        //        };
                        //        WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                        //        dbContext.Add(wcsTask);
                        //        dbContext.Add(wcsTaskLog);
                        //        dbContext.SaveChanges();
                        //    }
                        //    else
                        //    {
                        //        endEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipType == 15 && t.equipStatus == 0 && t.emptyCount == 0);
                        //        if (endEquip != null)
                        //        {
                        //            var wcsTask = new WcsTask()
                        //            {
                        //                objid = StaticData.SnowId.NextId(),
                        //                serialNo = SystemData.GetSerialNo(dbContext),
                        //                taskType = 43,
                        //                nextPointId = agvEquip.objid,
                        //                nextPointNo = agvEquip.equipNo,
                        //                endPointId = endEquip.objid,
                        //                endPointNo = endEquip.equipNo,
                        //                currPointId = baseEquip.objid,
                        //                currPointNo = baseEquip.equipNo,
                        //                equipmentNo = agvEquip.equipNo,
                        //                useFlag = 1,
                        //                qty = 5,
                        //                isEmpty = "1",
                        //                taskStatus = 0,
                        //                createBy = "WCS",
                        //                createTime = DateTime.Now,
                        //                floorNo = 3,
                        //                fromFloorNo = 3,
                        //                masterId = 0,
                        //                orderId = 0,
                        //                materialId = 0,
                        //            };
                        //            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                        //            dbContext.Add(wcsTask);
                        //            dbContext.Add(wcsTaskLog);
                        //            dbContext.SaveChanges();
                        //        }
                        //    }
                        //}
                        //else 
                        #endregion
                        if (baseEquip.emptyCount == SystemData.maxTray)//达到最大值
                        {
                            var endEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipType == 15 && t.equipStatus == 0 && t.emptyCount == 0);//找周转区
                            if (endEquip != null)
                            {
                                var wcsTask = new WcsTask()
                                {
                                    objid = StaticData.SnowId.NextId(),
                                    serialNo = SystemData.GetSerialNo(dbContext),
                                    taskType = StaticTaskType.ThirdBinToTransit,
                                    nextPointId = agvEquip.objid,
                                    nextPointNo = agvEquip.equipNo,
                                    endPointId = endEquip.objid,
                                    endPointNo = endEquip.equipNo,
                                    currPointId = baseEquip.objid,
                                    currPointNo = baseEquip.equipNo,
                                    equipmentNo = agvEquip.equipNo,
                                    useFlag = 1,
                                    qty = SystemData.maxTray,
                                    isEmpty = "1",
                                    taskStatus = 0,
                                    createBy = "WCS",
                                    createTime = DateTime.Now,
                                    floorNo = 3,
                                    fromFloorNo = 3,
                                    masterId = 0,
                                    orderId = 0,
                                    materialId = 0,
                                };
                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                dbContext.Add(wcsTask);
                                dbContext.Add(wcsTaskLog);
                                dbContext.SaveChanges();
                                isCreate = true;
                            }
                        }
                        if (!isCreate)
                        {
                            var emptyEquip = dbContext.BaseEquip.Where(t => t.equipType == 15).Where(t => t.emptyCount == SystemData.maxTray).ToList();
                            var secondEmptyEquip = dbContext.BaseEquip.Where(t => t.equipType == 20).Where(t => t.emptyCount == 0).ToList();
                            if (emptyEquip.Count >= 2 && secondEmptyEquip.Count >= 4)//二楼空库位多余4个，三楼空库位大于4个
                            {
                                BaseEquip startEquip = emptyEquip.First();
                                WcsTask wcsTask = new WcsTask()
                                {
                                    objid = StaticData.SnowId.NextId(),
                                    serialNo = SystemData.GetSerialNo(dbContext),
                                    taskType = StaticTaskType.ThirdTransitToSecond,
                                    nextPointId = agvEquip.objid,
                                    nextPointNo = agvEquip.equipNo,
                                    currPointId = startEquip.objid,
                                    currPointNo = startEquip.equipNo,
                                    endPointId = secondEmptyEquip.First().objid,
                                    endPointNo = secondEmptyEquip.First().equipNo,
                                    equipmentNo = agvEquip.equipNo,
                                    useFlag = 1,
                                    qty = startEquip.emptyCount,
                                    isEmpty = "1",
                                    taskStatus = 0,
                                    createBy = "WCS",
                                    createTime = DateTime.Now,
                                    floorNo = 2,
                                    fromFloorNo = 3,
                                    masterId = 0,
                                    orderId = 0,
                                    materialId = 0,
                                };
                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                dbContext.Add(wcsTask);
                                dbContext.Add(wcsTaskLog);
                                dbContext.SaveChanges();
                            }
                            else if (emptyEquip.Count == 3 && secondEmptyEquip.Count >= 2)
                            {
                                BaseEquip startEquip = emptyEquip.First();
                                WcsTask wcsTask = new WcsTask()
                                {
                                    objid = StaticData.SnowId.NextId(),
                                    serialNo = SystemData.GetSerialNo(dbContext),
                                    taskType = StaticTaskType.ThirdTransitToSecond,
                                    nextPointId = agvEquip.objid,
                                    nextPointNo = agvEquip.equipNo,
                                    currPointId = startEquip.objid,
                                    currPointNo = startEquip.equipNo,
                                    endPointId = secondEmptyEquip.First().objid,
                                    endPointNo = secondEmptyEquip.First().equipNo,
                                    equipmentNo = agvEquip.equipNo,
                                    useFlag = 1,
                                    qty = startEquip.emptyCount,
                                    isEmpty = "1",
                                    taskStatus = 0,
                                    createBy = "WCS",
                                    createTime = DateTime.Now,
                                    floorNo = 2,
                                    fromFloorNo = 3,
                                    masterId = 0,
                                    orderId = 0,
                                    materialId = 0,
                                };
                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                dbContext.Add(wcsTask);
                                dbContext.Add(wcsTaskLog);
                                dbContext.SaveChanges();
                            }
                            else
                            {
                                //报警
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 背负式Agv退库
        /// </summary>
        private void BackReturnTaskLogic()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 10);
                    if (baseEquip.IsOut == 2 && !string.IsNullOrEmpty(baseEquip.endStationCode))
                    {
                        bool hasTask = dbContext.WcsTask.Where(t => t.nextPointId == 10).Any();
                        if (!hasTask)
                        {
                            BaseEquip startEquip = StaticData.BaseEquip.First(t => t.endStationCode == baseEquip.endStationCode);
                            List<WmsRawReturn> wmsRawReturns = dbContext.WmsRawReturn.Where(t => t.endStationCode == baseEquip.endStationCode)
                                .Where(t => t.auditStatus == "1")
                                .Where(t => t.executeStatus == "0" || t.executeStatus == "1")
                                .ToList();
                            wmsRawReturns.ForEach(t => t.executeStatus = "1");
                            dbContext.UpdateRange(wmsRawReturns);
                            BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == 21);
                            var wcsTask = new WcsTask()
                            {
                                objid = StaticData.SnowId.NextId(),
                                serialNo = SystemData.GetSerialNo(dbContext),
                                taskType = 48,
                                nextPointId = baseEquip.objid,
                                nextPointNo = baseEquip.equipNo,
                                currPointId = startEquip.objid,
                                currPointNo = startEquip.equipNo,
                                endPointId = endEquip.objid,
                                endPointNo = endEquip.equipNo,
                                equipmentNo = baseEquip.equipNo,
                                useFlag = 1,
                                qty = 1,
                                taskStatus = 0,
                                containerNo = "",
                                IsDelete = 0,
                                createTime = DateTime.Now,
                            };
                            baseEquip.IsOut = 0;
                            dbContext.Update(baseEquip);
                            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                            dbContext.Add(wcsTask);
                            dbContext.Add(wcsTaskLog);
                            dbContext.SaveChanges();
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 半成品入库
        /// </summary>
        /// <param name="obj"></param>
        private void CreateFiveProductInTaskLogic()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            BaseEquip agvEquip = StaticData.BaseEquip.First(t => t.objid == 28);
            BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == 30);
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    bool task = dbContext.WcsTask.Where(t => t.nextPointId == 28 && t.useFlag == 1 && t.taskStatus <= 5).Any();
                    if (!task)
                    {
                        var wmsProductInstock = dbContext.WmsProductInstock
                            .Where(t => t.productType == "2")
                            .Where(t => t.auditStatus == "1" && t.executeStatus == "0")
                            .Where(t => t.warehouseId == 521)
                            .FirstOrDefault();
                        if (wmsProductInstock != null)
                        {
                            var wmsBaseLocation = dbContext.WmsBaseLocation
                               .Where(t => t.activeFlag == "1")
                                .Where(t => t.delFlag == "0")
                                .Where(t => t.locationScrapType == "1")
                                .Where(t => t.locationStatus == "1")
                                .Where(t => string.IsNullOrEmpty(t.containerCode))
                                .Where(t => t.warehouseId == 521)
                                .OrderByDescending(t => t.locColumn)
                                .FirstOrDefault();
                            if (wmsBaseLocation != null)
                            {
                                var wcsTask = new WcsTask()
                                {
                                    objid = StaticData.SnowId.NextId(),
                                    serialNo = SystemData.GetSerialNo(dbContext),
                                    taskType = StaticTaskType.FiveHalfIn,
                                    endPointId = wmsBaseLocation.locationId,
                                    endPointNo = wmsBaseLocation.locationCode,
                                    currPointId = endEquip.objid,
                                    currPointNo = endEquip.equipNo,
                                    equipmentNo = agvEquip.equipNo,
                                    useFlag = 1,
                                    qty = 1,
                                    containerNo = wmsProductInstock.palletInfoCode,
                                    taskStatus = 0,
                                    createBy = "WCS",
                                    createTime = DateTime.Now,
                                    floorNo = 5,
                                    fromFloorNo = 5,
                                    isEmpty = "0",
                                    masterId = wmsProductInstock.productId,
                                    orderId = wmsProductInstock.productInstockId,
                                    materialId = wmsProductInstock.productId,
                                    nextPointId = agvEquip.objid,
                                    nextPointNo = agvEquip.equipNo,
                                    materialBarcode = wmsProductInstock.productBatch,
                                };
                                //WmsProductInstockDetail wmsProductInstockDetail = new WmsProductInstockDetail()
                                //{
                                //    erpAmount = 0,
                                //    productId = wmsProductInstock.productId,
                                //    executeStatus = "1",
                                //    productInstockDetailId = StaticData.SnowId.NextId(),
                                //    instockAmount = 1,
                                //    instockBy = "WCS",
                                //    instockDate = DateTime.Now,
                                //    instockWay = "2",
                                //    locationCode = wmsBaseLocation.locationCode,
                                //    planAmount = 1,
                                //    productBarcode = wmsProductInstock.productBatch,
                                //    productBatch = wmsProductInstock.productBatch,
                                //    productInstockId = wmsProductInstock.productInstockId,
                                //};
                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                wmsProductInstock.executeStatus = "1";
                                wmsBaseLocation.locationStatus = "2";
                                //dbContext.Add(wmsProductInstockDetail);
                                dbContext.Update(wmsProductInstock);
                                dbContext.Update(wmsBaseLocation);
                                dbContext.Add(wcsTask);
                                dbContext.Add(wcsTaskLog);
                                dbContext.SaveChanges();
                            }
                            else
                            {
                                //报警
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 创建去翻转机的任务
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void CreateThirdOutTaskLogic()
        {
            BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == 31);
            BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.objid == 9);
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    lock (SystemData.ThirdTaskLock)
                    {
                        dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                        bool task = dbContext.WcsTask.Where(t => t.nextPointId == 9 && t.taskStatus <= 5).Any();
                        if (!task)
                        {
                            endEquip = dbContext.BaseEquip.First(t => t.objid == 31);
                            if (endEquip.emptyCount == 0)
                            {
                                WcsTask? wcsTask = dbContext.WcsTask.FirstOrDefault(t => t.endPointId == endEquip.objid);
                                if (wcsTask == null)
                                {
                                    WcsTaskManual? wcsTaskManual = dbContext.WcsTaskManual.Where(t => t.taskType == 999).FirstOrDefault();//调接口生成的任务
                                    if (wcsTaskManual != null)
                                    {
                                        var wmsRawOutstock = dbContext.WmsRawOutstock.FirstOrDefault(t => t.rawOutstockId == wcsTaskManual.orderId);
                                        if (wmsRawOutstock != null)
                                        {
                                            var wmsRawStocks = dbContext.WmsRawStock
                                                .Where(t => t.saleOrderId == (wmsRawOutstock.saleOrderId == null ? 0 : wmsRawOutstock.saleOrderId))
                                                .Where(t => t.warehouseId == 311)
                                                .Where(t => t.materialId == wmsRawOutstock.materialId)
                                                .Where(t => t.totalAmount > t.frozenAmount)
                                                 .ToList();
                                            var wmsRawStockLocations = wmsRawStocks.Select(x => x.locationCode).ToList();
                                            var AllWmsBaseLocations = dbContext.WmsBaseLocation
                                                .Where(t => t.activeFlag == "1")
                                                .Where(t => t.delFlag == "0")
                                                .Where(t => t.locationScrapType == "1")
                                                .Where(t => t.warehouseId == 311)
                                                .Where(t => t.locationStatus == "1").ToList();
                                            var wmsBaseLocations = AllWmsBaseLocations
                                                .Where(t => t.warehouseId == 311)
                                                .Where(t => wmsRawStockLocations.Contains(t.locationCode))
                                                .ToList();
                                            var bill = from a in wmsBaseLocations
                                                       from b in wmsRawStocks
                                                       where a.locationCode == b.locationCode
                                                       select new { a, b };
                                            WmsBaseLocation? wmsBaseLocation = null;
                                            WmsRawStock? wmsRawStock = null;
                                            bill = bill.OrderBy(t => t.b.instockDate.Value.Date);//按某个时间段
                                            foreach (var item in bill)
                                            {
                                                // 目标库位
                                                var fistbill = item;

                                                int? locRow = 0;
                                                if (fistbill.a.locRow % 2 == 1)
                                                {
                                                    locRow = fistbill.a.locRow + 1;
                                                }
                                                else
                                                {
                                                    locRow = fistbill.a.locRow - 1;
                                                }
                                                wmsBaseLocation = fistbill.a;

                                                // 目标库位处于深库位，判断是否需要移库浅库位
                                                if (wmsBaseLocation.locDeep == 1)
                                                {
                                                    int? row = 0;
                                                    if (wmsBaseLocation.locRow % 2 == 1)
                                                    {
                                                        row = wmsBaseLocation.locRow + 1;
                                                    }
                                                    else
                                                    {
                                                        row = wmsBaseLocation.locRow - 1;
                                                    }

                                                    var lowLocationBill = bill.Where(t => t.a.locRow == locRow).Where(t => t.a.locColumn == wmsBaseLocation.locColumn).Where(t => t.a.warehouseId == wmsBaseLocation.warehouseId).FirstOrDefault();
                                                    if (lowLocationBill != null)
                                                    {
                                                        //对应的浅库位满足条件，直接出浅库位
                                                        wmsBaseLocation = lowLocationBill.a;
                                                    }
                                                    else
                                                    {
                                                        //目标出库库位对应的浅库位
                                                        WmsBaseLocation? fromBaseLocation = dbContext.WmsBaseLocation.Where(t => t.locRow == row)
                                                        .Where(t => t.locColumn == wmsBaseLocation.locColumn)
                                                        .Where(t => t.warehouseId == wmsBaseLocation.warehouseId).FirstOrDefault();
                                                        if (fromBaseLocation != null && !string.IsNullOrEmpty(fromBaseLocation.containerCode) && fromBaseLocation.locationStatus == "1")
                                                        {
                                                            // 浅库位有库存
                                                            WmsRawStock? wmsRawStock1 = dbContext.WmsRawStock.FirstOrDefault(t => t.locationCode == fromBaseLocation.locationCode);
                                                            if (wmsRawStock1 != null)
                                                            {
                                                                #region 找寻移库目标库位
                                                                // 寻找移库目的库位
                                                                WmsBaseLocation? toLocation = null;

                                                                var moveLocationList = AllWmsBaseLocations.Where(t => t.warehouseId == fromBaseLocation.warehouseId)
                                                                    .Where(t => t.warehouseId != fromBaseLocation.locationId)
                                                                    .Where(t => string.IsNullOrEmpty(t.containerCode)).OrderBy(t => t.locDeep).ToList();

                                                                foreach (WmsBaseLocation itemLocation in moveLocationList)
                                                                {

                                                                    if (itemLocation.locDeep == 1)
                                                                    {
                                                                        bool hasLocation = AllWmsBaseLocations
                                                                        .Where(t => t.locRow == (itemLocation.locRow % 2 == 1 ? (itemLocation.locRow + 1) : (itemLocation.locRow - 1)))
                                                                        .Where(t => t.locColumn == itemLocation.locColumn)
                                                                        .Where(t => t.locationStatus == "1" && string.IsNullOrEmpty(t.containerCode))
                                                                            .Any();
                                                                        if (!hasLocation)
                                                                        {
                                                                            Console.WriteLine(DateTime.Now + $":目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                            _logger.Info($"目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                            continue;
                                                                        }
                                                                        else
                                                                        {
                                                                            // 找到可以移库的目标库位
                                                                            toLocation = itemLocation;
                                                                            break;
                                                                        }

                                                                    }
                                                                    else
                                                                    {
                                                                        // 找到可以移库的目标库位
                                                                        toLocation = itemLocation;
                                                                        break;
                                                                    }

                                                                }
                                                                if (toLocation == null)
                                                                {
                                                                    // 找寻下一个可出库库存
                                                                    continue;
                                                                }

                                                                var RemoveTask = new WcsTask()
                                                                {
                                                                    objid = StaticData.SnowId.NextId(),
                                                                    taskType = StaticTaskType.ThirdRemove,
                                                                    containerNo = wmsRawStock1.palletInfoCode,
                                                                    createBy = "WCS",
                                                                    createTime = DateTime.Now.AddSeconds(-10),
                                                                    taskStatus = 0,
                                                                    currPointId = fromBaseLocation.locationId,
                                                                    currPointNo = fromBaseLocation.locationCode,
                                                                    nextPointId = baseEquip.objid,
                                                                    nextPointNo = baseEquip.equipNo,
                                                                    endPointId = toLocation.locationId,
                                                                    endPointNo = toLocation.locationCode,
                                                                    equipmentNo = baseEquip.equipNo,
                                                                    useFlag = 1,
                                                                    qty = 1
                                                                };
                                                                SystemData.LockOutLocation(toLocation, dbContext);
                                                                SystemData.LockOutLocation(fromBaseLocation, dbContext);
                                                                toLocation.locationStatus = "4";
                                                                toLocation.updateBy = "WCS";
                                                                toLocation.updateTime = DateTime.Now;
                                                                fromBaseLocation.updateBy = "WCS";
                                                                fromBaseLocation.updateTime = DateTime.Now;
                                                                fromBaseLocation.locationStatus = "4";
                                                                dbContext.Update(toLocation);
                                                                dbContext.Update(fromBaseLocation);
                                                                dbContext.Add(RemoveTask);
                                                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(RemoveTask);
                                                                dbContext.Add(wcsTaskLog);
                                                                #endregion


                                                            }

                                                        }
                                                        else if(fromBaseLocation != null&& fromBaseLocation.locationStatus != "1")
                                                        {
                                                            //浅库位状态异常，找寻下一个可出库库存
                                                            continue;
                                                        }
                                                    }
                                                }

                                                if (wmsBaseLocation != null)
                                                {
                                                    wmsRawStock = wmsRawStocks.Where(t => t.locationCode == wmsBaseLocation.locationCode).First();
                                                    MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.FirstOrDefault(t => t.palletInfoCode == wmsRawStock.palletInfoCode);
                                                    if (mesBasePalletInfo != null)
                                                    {
                                                        MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == mesBasePalletInfo.materialBarcode);
                                                        if (mesBaseBarcodeInfo != null)
                                                        {
                                                            WmsRawOutstockDetail wmsRawOutstockDetail = new WmsRawOutstockDetail()
                                                            {
                                                                rawOutstockDetailId = StaticData.SnowId.NextId(),
                                                                createBy = "WCS",
                                                                createDate = DateTime.Now,
                                                                executeStatus = "0",
                                                                erpAmount = 0,
                                                                erpStatus = "0",
                                                                instockBatch = mesBaseBarcodeInfo.batchCode,
                                                                stackAmount = 1,
                                                                locationCode = wmsBaseLocation.locationCode,
                                                                rawOutstockId = wmsRawOutstock.rawOutstockId,
                                                                planAmount = 1,
                                                                outstockWay = "2",
                                                                outstockPerson = "WCS",
                                                                outstockTime = DateTime.Now,
                                                                materialProductionDate = mesBaseBarcodeInfo.productionDate,
                                                                materialBarcode = mesBasePalletInfo.materialBarcode,
                                                                materialId = wmsRawOutstock.materialId,
                                                                machineName = mesBaseBarcodeInfo.machineName,
                                                                outstockAmount = 1,
                                                                taskCode = wmsRawOutstock.taskCode
                                                            };
                                                            wcsTask = new WcsTask()
                                                            {
                                                                objid = StaticData.SnowId.NextId(),
                                                                orderId = wmsRawOutstock.rawOutstockId,
                                                                taskType = StaticTaskType.ThirdRawToFlip,
                                                                containerNo = wmsRawStock.palletInfoCode,
                                                                createBy = "WCS",
                                                                createTime = DateTime.Now,
                                                                taskStatus = 0,
                                                                materialId = wmsRawOutstock.materialId,
                                                                currPointId = wmsBaseLocation.locationId,
                                                                currPointNo = wmsBaseLocation.locationCode,
                                                                nextPointId = baseEquip.objid,
                                                                nextPointNo = baseEquip.equipNo,
                                                                endPointId = endEquip.objid,
                                                                endPointNo = endEquip.equipNo,
                                                                equipmentNo = endEquip.equipNo,
                                                                useFlag = 1,
                                                                qty = 1
                                                            };
                                                            SystemData.LockOutLocation(wmsBaseLocation, dbContext);
                                                            wmsBaseLocation.locationStatus = "6";
                                                            dbContext.Update(wmsBaseLocation);
                                                            dbContext.Add(wmsRawOutstockDetail);
                                                            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                                            dbContext.Remove(wcsTaskManual);
                                                            dbContext.Add(wcsTask);
                                                            dbContext.Add(wcsTaskLog);
                                                            dbContext.SaveChanges();
                                                        }
                                                    }
                                                }

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

        /// <summary>
        /// 创建返库任务
        /// </summary>
        /// <param name="obj"></param>
        private void CreateBearAgvReturnLogic()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == 21);
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 10);

                    if (!string.IsNullOrEmpty(baseEquip.endStationCode) && baseEquip.ud3 == "1")
                    {
                        var wmsRawReturn = dbContext.WmsRawReturn
                           .Where(t => t.auditStatus == "1")
                           .Where(t => t.executeStatus == "0")
                           .Where(t => t.endStationCode == baseEquip.endStationCode)
                           .FirstOrDefault();
                        if (wmsRawReturn != null)
                        {
                            bool hasTask = dbContext.WcsTask.Where(t => t.nextPointId == baseEquip.objid).Any();
                            if (!hasTask)
                            {
                                //任务未开始Status=0
                                BaseEquip? startEquip = StaticData.BaseEquip.FirstOrDefault(t => t.equipNo == wmsRawReturn.endStationCode);
                                if (startEquip != null)
                                {
                                    WcsTask wcsTask = new()
                                    {
                                        objid = StaticData.SnowId.NextId(),
                                        orderId = wmsRawReturn.rawReturnId,
                                        taskType = 48,
                                        containerNo = null,
                                        currPointId = startEquip.objid,
                                        currPointNo = startEquip.equipNo,
                                        nextPointId = baseEquip.objid,
                                        nextPointNo = baseEquip.equipNo,
                                        endPointId = endEquip.objid,
                                        endPointNo = endEquip.equipNo,
                                        serialNo = SystemData.GetSerialNo(dbContext),
                                        taskStatus = 0,
                                        createTime = DateTime.Now,
                                        createBy = "WCS",
                                        materialId = wmsRawReturn.materialId,
                                        qty = 1,
                                        useFlag = 1,
                                        equipmentNo = startEquip.equipNo,
                                        remark = "装配区返库",
                                        floorNo = 5,
                                        masterId = wmsRawReturn.materialId,
                                        fromFloorNo = 5,
                                        //materialNo = wmsRawReturn.materialBatch,
                                    };
                                    baseEquip.ud3 = null;
                                    dbContext.Update(baseEquip);
                                    dbContext.Add(wcsTask);
                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                    dbContext.Add(wcsTaskLog);
                                    dbContext.Update(wmsRawReturn);
                                    dbContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 成品出库
        /// </summary>
        private void CreateFiveProductTaskLogic()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    BaseEquip lineEquip = dbContext.BaseEquip.First(t => t.objid == 5);
                    if (lineEquip.equipStatus == 0)
                    {
                        bool task = dbContext.WcsTask.Where(t => t.nextPointId == 28 && t.taskStatus <= 5).Any();
                        if (!task)
                        {
                            var proStock = dbContext.WmsProductStock
                            .Where(t => t.warehouseId == 531)
                            .Where(t => t.activeFlag == "1").ToList();
                            var proOutStock = dbContext.WmsProductOutstock
                                .Where(t => t.outstockQty < t.applyQty)
                                .Where(t => t.auditStatus == "1")
                                .Where(t => t.warehouseId == 531)
                                .Where(t => t.productType == "3")
                                .Where(t => t.executeStatus == "0" || t.executeStatus == "1").ToList();
                            //获取最早入库时间
                            foreach (var item in proOutStock)
                            {
                                task = dbContext.WcsTask.Where(t => t.nextPointId == 28 && t.taskStatus <= 5).Any();
                                if (!task)
                                {
                                    BaseEquip endEquip = dbContext.BaseEquip.First(t => t.floorNo == 5 && t.equipType == 1);

                                    var wmsproStocks = proStock
                                               .Where(t => t.productId == item.productId && t.warehouseId == item.warehouseId)
                                               .Where(t => t.totalAmount > t.frozenAmount)
                                               .Select(t => t.locationCode)
                                               .ToList();
                                    List<WmsBaseLocation> AllWmsBaseLocations = dbContext.WmsBaseLocation
                                        .Where(t => t.activeFlag == "1")
                                        .Where(t => t.delFlag == "0")
                                        .Where(t => t.locationScrapType == "1")
                                        .Where(t => t.locationStatus == "1")
                                        .Where(t => t.warehouseId == item.warehouseId).ToList();
                                    var wmsBaseLocations = AllWmsBaseLocations
                                        .Where(t => t.warehouseId == item.warehouseId)
                                        .Where(t => wmsproStocks.Contains(t.locationCode))
                                        .ToList();

                                    decimal needNumber = Convert.ToDecimal(item.applyQty - item.outstockQty);
                                    if (needNumber <= 0)
                                    {
                                        item.executeStatus = "2";
                                        dbContext.Update(item);
                                        dbContext.SaveChanges();
                                        continue;
                                    }

                                    var bill = from a in wmsBaseLocations
                                               from b in proStock
                                               where a.locationCode == b.locationCode
                                               select new { a, b };

                                    BaseEquip agvEquip = StaticData.BaseEquip.First(t => t.objid == 28);
                                    foreach (var b in bill)
                                    {
                                        item.executeStatus = "1";
                                        WmsBaseLocation location = b.a;
                                        WmsProductStock stock = b.b;
                                        WcsTask wcsTask;
                                        stock.updateDate = DateTime.Now;
                                        MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.FirstOrDefault(t => t.palletInfoCode == stock.palletInfoCode);
                                        if (mesBasePalletInfo != null)
                                        {
                                            if (location.locDeep == 1)
                                            {
                                                int? row = 0;
                                                if (location.locRow % 2 == 1)
                                                {
                                                    row = location.locRow + 1;
                                                }
                                                else
                                                {
                                                    row = location.locRow - 1;
                                                }
                                                var lowLocationBill = bill.Where(t => t.a.locRow == row).Where(t => t.a.locColumn == location.locColumn).Where(t => t.a.warehouseId == location.warehouseId).FirstOrDefault();
                                                if (lowLocationBill != null)
                                                {
                                                    location = lowLocationBill.a;
                                                    stock = lowLocationBill.b;
                                                }
                                                else
                                                {
                                                    // 外侧浅库位
                                                    WmsBaseLocation? wmsBaseLocation = dbContext.WmsBaseLocation.Where(t => t.locRow == row)
                                                    .Where(t => t.locColumn == location.locColumn)
                                                    .Where(t => t.warehouseId == location.warehouseId).FirstOrDefault();
                                                    if (!string.IsNullOrEmpty(wmsBaseLocation.containerCode) && wmsBaseLocation.locationStatus == "1")
                                                    {

                                                        WmsProductStock? wmsProductStock = dbContext.WmsProductStock.FirstOrDefault(t => t.locationCode == wmsBaseLocation.locationCode);
                                                        if (wmsProductStock != null)
                                                        {
                                                            #region 找寻移库目标库位

                                                            WmsBaseLocation? toLocation = null;


                                                            var moveLocationList = AllWmsBaseLocations.Where(t => t.warehouseId == location.warehouseId)
                                                                .Where(t => t.warehouseId != location.locationId)
                                                                .Where(t => string.IsNullOrEmpty(t.containerCode) && t.locationStatus == "1").OrderBy(t => t.locDeep).ToList();

                                                            foreach (WmsBaseLocation itemLocation in moveLocationList)
                                                            {

                                                                if (itemLocation.locDeep == 1)
                                                                {
                                                                    bool hasLocation = AllWmsBaseLocations
                                                                    .Where(t => t.locRow == (itemLocation.locRow % 2 == 1 ? (itemLocation.locRow + 1) : (itemLocation.locRow - 1)))
                                                                    .Where(t => t.locColumn == itemLocation.locColumn)
                                                                    .Where(t => t.locationStatus == "1" && string.IsNullOrEmpty(t.containerCode))
                                                                        .Any();
                                                                    if (!hasLocation)
                                                                    {
                                                                        Console.WriteLine(DateTime.Now + $":目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                        _logger.Info($"目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                        continue;
                                                                    }
                                                                    else
                                                                    {
                                                                        // 找到可以移库的目标库位
                                                                        toLocation = itemLocation;
                                                                        break;
                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    // 找到可以移库的目标库位
                                                                    toLocation = itemLocation;
                                                                    break;
                                                                }

                                                            }
                                                            if (toLocation == null)
                                                            {
                                                                // 找寻下一个可出库库存
                                                                continue;
                                                            }
                                                            var RemoveTask = new WcsTask()
                                                            {
                                                                objid = StaticData.SnowId.NextId(),
                                                                orderId = item.productOutstockId,
                                                                taskType = StaticTaskType.SecondRemove,
                                                                containerNo = wmsBaseLocation.containerCode,
                                                                createBy = "WCS",
                                                                createTime = DateTime.Now.AddSeconds(-10),
                                                                taskStatus = 0,
                                                                materialId = item.productId,
                                                                currPointId = wmsBaseLocation.locationId,
                                                                currPointNo = wmsBaseLocation.locationCode,
                                                                nextPointId = agvEquip.objid,
                                                                nextPointNo = agvEquip.equipNo,
                                                                endPointId = toLocation.locationId,
                                                                endPointNo = toLocation.locationCode,
                                                                equipmentNo = agvEquip.equipNo,
                                                                useFlag = 1,
                                                                qty = 1
                                                            };
                                                            SystemData.LockOutLocation(toLocation, dbContext);
                                                            SystemData.LockOutLocation(wmsBaseLocation, dbContext);
                                                            toLocation.locationStatus = "4";
                                                            toLocation.updateBy = "WCS";
                                                            toLocation.updateTime = DateTime.Now;
                                                            wmsBaseLocation.updateBy = "WCS";
                                                            wmsBaseLocation.updateTime = DateTime.Now;
                                                            wmsBaseLocation.locationStatus = "4";
                                                            dbContext.Update(toLocation);
                                                            dbContext.Update(wmsBaseLocation);
                                                            dbContext.Add(RemoveTask);
                                                            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(RemoveTask);
                                                            dbContext.Add(wcsTaskLog);
                                                            #endregion
                                                            //WmsBaseLocation? toLocation = AllWmsBaseLocations.Where(t => t.warehouseId == location.warehouseId)
                                                            //    .Where(t => t.locDeep == 1)
                                                            //    .Where(t => string.IsNullOrEmpty(t.containerCode)).FirstOrDefault();
                                                            //toLocation ??= AllWmsBaseLocations.Where(t => t.warehouseId == location.warehouseId)
                                                            //    .Where(t => t.warehouseId != location.locationId)
                                                            //    .Where(t => string.IsNullOrEmpty(t.containerCode))
                                                            //    .FirstOrDefault();

                                                            //if (toLocation != null)
                                                            //{
                                                            //    if (toLocation.locDeep == 1)
                                                            //    {
                                                            //        bool hasLocation = AllWmsBaseLocations
                                                            //            .Where(t => t.locRow == (toLocation.locRow % 2 == 1 ? (toLocation.locRow + 1) : (toLocation.locRow - 1)))
                                                            //            .Where(t => t.locColumn == toLocation.locColumn)
                                                            //            .Any();
                                                            //        if (!hasLocation)
                                                            //        {
                                                            //            Console.WriteLine(DateTime.Now + $":目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                            //            _logger.Info($"目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                            //            continue;
                                                            //        }
                                                            //    }
                                                            //    var RemoveTask = new WcsTask()
                                                            //    {
                                                            //        objid = StaticData.SnowId.NextId(),
                                                            //        orderId = item.productOutstockId,
                                                            //        taskType = StaticTaskType.FiveRemove,
                                                            //        containerNo = wmsProductStock.palletInfoCode,
                                                            //        createBy = "WCS",
                                                            //        createTime = DateTime.Now.AddSeconds(-10),
                                                            //        taskStatus = 0,
                                                            //        materialId = item.productId,
                                                            //        currPointId = wmsBaseLocation.locationId,
                                                            //        currPointNo = wmsBaseLocation.locationCode,
                                                            //        nextPointId = agvEquip.objid,
                                                            //        nextPointNo = agvEquip.equipNo,
                                                            //        endPointId = toLocation.locationId,
                                                            //        endPointNo = toLocation.locationCode,
                                                            //        equipmentNo = agvEquip.equipNo,
                                                            //        useFlag = 1,
                                                            //        qty = 1
                                                            //    };
                                                            //    SystemData.LockOutLocation(toLocation, dbContext);
                                                            //    SystemData.LockOutLocation(wmsBaseLocation, dbContext);

                                                            //    toLocation.locationStatus = "4";
                                                            //    toLocation.updateBy = "WCS";
                                                            //    toLocation.updateTime = DateTime.Now;
                                                            //    wmsBaseLocation.updateBy = "WCS";
                                                            //    wmsBaseLocation.updateTime = DateTime.Now;
                                                            //    wmsBaseLocation.locationStatus = "4";
                                                            //    dbContext.Update(toLocation);
                                                            //    dbContext.Update(wmsBaseLocation);
                                                            //    dbContext.Add(RemoveTask);
                                                            //    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(RemoveTask);
                                                            //    dbContext.Add(wcsTaskLog);
                                                            //}
                                                            //else
                                                            //{
                                                            //    continue;
                                                            //}
                                                        }
                                                        else
                                                        {
                                                            continue;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        Console.WriteLine(DateTime.Now + $":{wmsBaseLocation.locationCode}库位状态异常，无法移库");
                                                        _logger.Info($"{wmsBaseLocation.locationCode}库位状态异常，无法移库");
                                                        continue;
                                                    }
                                                }

                                            }
                                            WmsProductOutstockDetail detail = new()
                                            {
                                                productId = item.productId,
                                                productOutstockId = item.productOutstockId,
                                                locationCode = location.locationCode,
                                                executeStatus = "1",
                                                beginTime = DateTime.Now,
                                                warehouseId = item.warehouseId,
                                                erpAmount = 0,
                                                confirmAmount = 0,
                                                outstockAmount = 1,
                                                planAmount = 1,
                                                productBatch = item.productBatch,
                                                productOutstockDetailId = StaticData.SnowId.NextId(),
                                                productBarcode = mesBasePalletInfo.materialBarcode
                                            };
                                            wcsTask = new WcsTask()
                                            {
                                                objid = StaticData.SnowId.NextId(),
                                                orderId = item.productOutstockId,
                                                taskType = StaticTaskType.FiveProductOut,
                                                containerNo = stock.palletInfoCode,
                                                createBy = "WCS",
                                                createTime = DateTime.Now,
                                                taskStatus = 0,
                                                materialId = item.productId,
                                                currPointId = location.locationId,
                                                currPointNo = location.locationCode,
                                                nextPointId = agvEquip.objid,
                                                nextPointNo = agvEquip.equipNo,
                                                endPointId = lineEquip.objid,
                                                endPointNo = lineEquip.equipNo,
                                                equipmentNo = agvEquip.equipNo,
                                                useFlag = 1,
                                                qty = 1
                                            };
                                            SystemData.LockOutLocation(location, dbContext);
                                            location.locationStatus = "6";
                                            location.updateBy = "WCS";
                                            location.updateTime = DateTime.Now;
                                            dbContext.Add(detail);
                                            dbContext.Update(location);
                                            dbContext.Add(wcsTask);
                                            dbContext.Update(stock);
                                            break;
                                        }
                                    }
                                    if (item.beginTime == null)
                                    {
                                        item.beginTime = DateTime.Now;
                                    }
                                    dbContext.Update(item);
                                    dbContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + ex.StackTrace);
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 成品出库
        /// </summary>
        private void CreateSecondProductTaskLogic()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    BaseEquip lineEquip = dbContext.BaseEquip.First(t => t.objid == 2);
                    if (lineEquip.equipStatus == 0)
                    {
                        bool task = dbContext.WcsTask.Where(t => t.nextPointId == 8 && t.taskStatus <= 7).Any();
                        if (!task)
                        {
                            lock (SystemData.SecondTaskLock)
                            {
                                var proStock = dbContext.WmsProductStock
                                    .Where(t => t.warehouseId == 231)
                                    .Where(t => t.activeFlag == "1")
                                    .Where(t => t.totalAmount > t.frozenAmount)
                                    .ToList();
                                var proOutStock = dbContext.WmsProductOutstock
                                    .Where(t => t.outstockQty < t.applyQty)
                                    .Where(t => t.auditStatus == "1")
                                    .Where(t => t.warehouseId == 231)
                                    .Where(t => t.productType == "3")
                                    .Where(t => t.executeStatus == "0" || t.executeStatus == "1").ToList();
                                //获取最早入库时间
                                foreach (var item in proOutStock)
                                {
                                    task = dbContext.WcsTask.Where(t => t.nextPointId == 8 && t.taskStatus <= 7).Any();
                                    if (task) break;

                                    var wmsproStocks = proStock
                                               .Where(t => t.productId == item.productId && t.saleOrderId == (item.saleOrderId == null ? 0 : item.saleOrderId) && t.warehouseId == item.warehouseId)
                                               .Select(t => t.locationCode)
                                               .ToList();
                                    List<WmsBaseLocation> AllWmsBaseLocations = dbContext.WmsBaseLocation
                                              .Where(t => t.activeFlag == "1")
                                            .Where(t => t.delFlag == "0")
                                            .Where(t => t.locationScrapType == "1")
                                            .Where(t => t.locationStatus == "1")
                                            .Where(t => t.warehouseId == item.warehouseId)
                                        .Where(t => t.warehouseId == item.warehouseId).ToList();
                                    var wmsBaseLocations = AllWmsBaseLocations
                                        .Where(t => t.warehouseId == item.warehouseId)
                                        .Where(t => wmsproStocks.Contains(t.locationCode))
                                        .ToList();

                                    decimal needNumber = Convert.ToDecimal(item.applyQty - item.outstockQty);
                                    if (needNumber <= 0)
                                    {
                                        item.executeStatus = "2";
                                        dbContext.Update(item);
                                        dbContext.SaveChanges();
                                        continue;
                                    }

                                    var bill = from a in wmsBaseLocations
                                               from b in proStock
                                               where a.locationCode == b.locationCode
                                               select new { a, b };
                                    WmsBaseLocation? location = null;
                                    WmsProductStock? stock = null;
                                    BaseEquip agvEquip = StaticData.BaseEquip.First(t => t.objid == 8);
                                    BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == 1);
                                    foreach (var b in bill)
                                    {
                                        item.executeStatus = "1";
                                        location = b.a;
                                        stock = b.b;
                                        WcsTask wcsTask;
                                        stock.updateDate = DateTime.Now;
                                        MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.FirstOrDefault(t => t.palletInfoCode == stock.palletInfoCode);
                                        if (mesBasePalletInfo != null)
                                        {
                                            if (location.locDeep == 1)//如果是深库位
                                            {
                                                int? row = 0;
                                                if (location.locRow % 2 == 1)
                                                {
                                                    row = location.locRow + 1;
                                                }
                                                else
                                                {
                                                    row = location.locRow - 1;
                                                }
                                                var lowLocationBill = bill.Where(t => t.a.locRow == row).Where(t => t.a.locColumn == location.locColumn).Where(t => t.a.warehouseId == location.warehouseId).FirstOrDefault();
                                                if (lowLocationBill != null)
                                                {  //对应的浅库位满足条件，直接出浅库位
                                                    location = lowLocationBill.a;
                                                    stock = lowLocationBill.b;
                                                }
                                                else
                                                {

                                                    // 目标出库库位对应的浅库位
                                                    WmsBaseLocation? wmsBaseLocation = dbContext.WmsBaseLocation.Where(t => t.locRow == row)
                                                        .Where(t => t.locColumn == location.locColumn)
                                                        .Where(t => t.warehouseId == location.warehouseId).FirstOrDefault();

                                                    if (wmsBaseLocation != null && !string.IsNullOrEmpty(wmsBaseLocation.containerCode) && wmsBaseLocation.locationStatus == "1")
                                                    {//浅库位有库存
                                                        WmsProductStock? wmsProductStock = dbContext.WmsProductStock.FirstOrDefault(t => t.locationCode == wmsBaseLocation.locationCode);

                                                        #region 找寻移库目标库位
                                                        // 寻找移库目的库位
                                                        WmsBaseLocation? toLocation = null;


                                                        var moveLocationList = AllWmsBaseLocations.Where(t => t.warehouseId == location.warehouseId)
                                                            .Where(t => t.warehouseId != location.locationId)
                                                            .Where(t => string.IsNullOrEmpty(t.containerCode) && t.locationStatus == "1").OrderBy(t => t.locDeep).ToList();

                                                        foreach (WmsBaseLocation itemLocation in moveLocationList)
                                                        {

                                                            if (itemLocation.locDeep == 1)
                                                            {
                                                                bool hasLocation = AllWmsBaseLocations
                                                                .Where(t => t.locRow == (itemLocation.locRow % 2 == 1 ? (itemLocation.locRow + 1) : (itemLocation.locRow - 1)))
                                                                .Where(t => t.locColumn == itemLocation.locColumn)
                                                                .Where(t => t.locationStatus == "1" && string.IsNullOrEmpty(t.containerCode))
                                                                    .Any();
                                                                if (!hasLocation)
                                                                {
                                                                    Console.WriteLine(DateTime.Now + $":目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                    _logger.Info($"目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                    continue;
                                                                }
                                                                else
                                                                {
                                                                    // 找到可以移库的目标库位
                                                                    toLocation = itemLocation;
                                                                    break;
                                                                }

                                                            }
                                                            else
                                                            {
                                                                // 找到可以移库的目标库位
                                                                toLocation = itemLocation;
                                                                break;
                                                            }

                                                        }
                                                        if (toLocation == null)
                                                        {
                                                            // 找寻下一个可出库库存
                                                            continue;
                                                        }
                                                        var RemoveTask = new WcsTask()
                                                        {
                                                            objid = StaticData.SnowId.NextId(),
                                                            orderId = item.productOutstockId,
                                                            taskType = StaticTaskType.SecondRemove,
                                                            containerNo = wmsBaseLocation.containerCode,
                                                            createBy = "WCS",
                                                            createTime = DateTime.Now.AddSeconds(-10),
                                                            taskStatus = 0,
                                                            materialId = item.productId,
                                                            currPointId = wmsBaseLocation.locationId,
                                                            currPointNo = wmsBaseLocation.locationCode,
                                                            nextPointId = agvEquip.objid,
                                                            nextPointNo = agvEquip.equipNo,
                                                            endPointId = toLocation.locationId,
                                                            endPointNo = toLocation.locationCode,
                                                            equipmentNo = agvEquip.equipNo,
                                                            useFlag = 1,
                                                            qty = 1
                                                        };
                                                        SystemData.LockOutLocation(toLocation, dbContext);
                                                        SystemData.LockOutLocation(wmsBaseLocation, dbContext);
                                                        toLocation.locationStatus = "4";
                                                        toLocation.updateBy = "WCS";
                                                        toLocation.updateTime = DateTime.Now;
                                                        wmsBaseLocation.updateBy = "WCS";
                                                        wmsBaseLocation.updateTime = DateTime.Now;
                                                        wmsBaseLocation.locationStatus = "4";
                                                        dbContext.Update(toLocation);
                                                        dbContext.Update(wmsBaseLocation);
                                                        dbContext.Add(RemoveTask);
                                                        WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(RemoveTask);
                                                        dbContext.Add(wcsTaskLog);
                                                        #endregion
                                                    }
                                                    else if (wmsBaseLocation.locationStatus != "1")
                                                    {
                                                        // 浅库位状态异常,找寻下一个可出库库存
                                                        continue;
                                                    }

                                                }
                                            }

                                            wcsTask = new WcsTask()
                                            {
                                                objid = StaticData.SnowId.NextId(),
                                                orderId = item.productOutstockId,
                                                taskType = StaticTaskType.SecondStorageToLift,
                                                containerNo = stock.palletInfoCode,
                                                createBy = "WCS",
                                                createTime = DateTime.Now,
                                                taskStatus = 0,
                                                materialId = item.productId,
                                                currPointId = location.locationId,
                                                currPointNo = location.locationCode,
                                                nextPointId = agvEquip.objid,
                                                nextPointNo = agvEquip.equipNo,
                                                endPointId = endEquip.objid,
                                                endPointNo = endEquip.equipNo,
                                                equipmentNo = agvEquip.equipNo,
                                                useFlag = 1,
                                                qty = 1
                                            };
                                            WmsProductOutstockDetail detail = new()
                                            {
                                                productId = item.productId,
                                                productOutstockId = item.productOutstockId,
                                                locationCode = location.locationCode,
                                                executeStatus = "1",
                                                beginTime = DateTime.Now,
                                                warehouseId = item.warehouseId,
                                                erpAmount = 0,
                                                confirmAmount = 0,
                                                outstockAmount = 1,
                                                planAmount = 1,
                                                productBatch = item.productBatch,
                                                productOutstockDetailId = StaticData.SnowId.NextId(),
                                                productBarcode = mesBasePalletInfo.materialBarcode,
                                            };
                                            SystemData.LockOutLocation(location, dbContext);
                                            location.locationStatus = "6";
                                            location.updateBy = "WCS";
                                            location.updateTime = DateTime.Now;
                                            dbContext.Add(detail);
                                            dbContext.Update(location);
                                            dbContext.Add(wcsTask);
                                            dbContext.Update(stock);
                                            WcsTaskLog wcsTaskLog1 = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                            dbContext.Add(wcsTaskLog1);
                                            dbContext.SaveChanges();
                                            break;
                                        }
                                    }
                                    if (item.beginTime == null)
                                    {
                                        item.beginTime = DateTime.Now;
                                    }
                                    dbContext.Update(item);
                                    dbContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + ex.StackTrace);
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 原材料出库
        /// </summary>
        private void CreateRawTaskLogic()
        {
            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 rawOutStock = dbContext.WmsRawOutstock
                        .Where(t => t.executeStatus == "0" || t.executeStatus == "1")
                        .Where(t => t.outstockAmount > t.realOutstockAmount)
                        .Where(t => t.auditStatus == "1")
                        .ToList();
                    List<WcsTaskManual> wcsTaskManuals = dbContext.WcsTaskManual.Where(t => t.nextPointId == 11).OrderBy(t => t.createBy).ToList();
                    if (wcsTaskManuals.Count > 0)
                    {
                        int taskCount = dbContext.WcsTask.Where(t => t.nextPointId == 11).Count();
                        //if (taskCount == 0 && wcsOutstockLock.qty == 0 && wcsOutstockLock.boxStatus == 0)
                        if (taskCount == 0)
                        {
                            List<WcsTaskManual> list = wcsTaskManuals.Where(t => t.taskType == 100).ToList();
                            if (list.Count == 0)
                            {
                                list = wcsTaskManuals.Where(t => t.taskType == 30).ToList();
                            }
                            if (list.Count == 0)
                            {
                                list = wcsTaskManuals.Where(t => t.taskType == 102).ToList();
                            }
                            foreach (var wcs in list.Take(6))
                            {
                                WcsTask wcsTask = CoreMapper.Map<WcsTask>(wcs);
                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                dbContext.Add(wcsTask);
                                dbContext.Add(wcsTaskLog);
                                dbContext.WcsTaskManual.Where(t => t.objid == wcs.objid).Delete();
                            }
                            dbContext.SaveChanges();
                        }
                    }
                    foreach (var item in rawOutStock)
                    {
                        if (item.endStationCode == "BB_01")
                        {

                        }
                        decimal? RealOutNumber = item.realOutstockAmount;
                        var endEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipNo == item.endStationCode);
                        if (endEquip != null && endEquip.floorNo == 5)
                        {

                            #region CTU出库，没用背负Agv的逻辑
                            //if (endEquip.equipType == 8)//CTU出库
                            //{
                            //    var wcsOutstockLock = dbContext.WcsOutstockLock.Where(t => t.warehouseId == 512).First();
                            //    if (wcsOutstockLock.qty == 0 && wcsOutstockLock.boxStatus == 0)
                            //    {
                            //        var wmsRawStocks = rawStock
                            //           .Where(t => t.materialId == item.materialId)
                            //           .Where(t => t.warehouseId == item.warehouseId)
                            //           .Select(t => t.locationCode)
                            //           .ToList();

                            //        var wmsBaseLocations = dbContext.WmsBaseLocation
                            //            .Where(t => t.activeFlag == "1")
                            //            .Where(t => t.delFlag == "0")
                            //            .Where(t => t.locationScrapType == "1")
                            //            
                            //      
                            //            .Where(t => t.ContainerStatus == "1")
                            //            .Where(t => t.warehouseId == item.warehouseId)
                            //            .Where(t => wmsRawStocks.Contains(t.locationCode))
                            //            .ToList();

                            //        decimal? needNumber = item.outstockAmount - RealOutNumber;

                            //        var bill = from a in wmsBaseLocations
                            //                   from b in rawStock
                            //                   where a.locationCode == b.locationCode
                            //                   select new { a, b };
                            //        //如果第一列满足需求,则按第一列排序,否则按最后一列排序
                            //        if (bill.Where(t => t.a.locColumn == 1).Select(t => t.b.totalAmount - t.b.frozenAmount).Sum() > needNumber)
                            //        {
                            //            bill = bill.OrderBy(t => t.a.locColumn).ToList();
                            //        }
                            //        else
                            //        {
                            //            bill = bill.OrderByDescending(t => t.a.locColumn).ToList();
                            //        }
                            //        //做数量限制

                            //        //bill = bill.Take(5 - dbContext.WcsCmd.Where(t => t.cmdStatus < 3 && t.nextPointId == 20).Count());
                            //        bill = bill.Take(6);
                            //        BaseEquip ctuEquip = StaticData.BaseEquip.First(t => t.objid == 11);
                            //        BaseEquip lineEquip = StaticData.BaseEquip.First(t => t.objid == 20);
                            //        foreach (var b in bill)
                            //        {
                            //            needNumber = item.outstockAmount - RealOutNumber;
                            //            item.executeStatus = "1";
                            //            WmsBaseLocation location = b.a;
                            //            WmsRawStock stock = b.b;
                            //            WcsTask wcsTask;
                            //            int qty = 0;
                            //            if (stock.totalAmount - stock.frozenAmount <= needNumber)//该料箱全部出
                            //            {
                            //                RealOutNumber += stock.totalAmount - stock.frozenAmount;
                            //                qty = Convert.ToInt32(stock.totalAmount - stock.frozenAmount);
                            //                stock.updateDate = DateTime.Now;
                            //            }
                            //            else
                            //            {
                            //                RealOutNumber += needNumber;
                            //                qty = Convert.ToInt32(needNumber);
                            //                stock.updateDate = DateTime.Now;
                            //            }
                            //            wcsTask = new WcsTask()
                            //            {
                            //                objid = StaticData.SnowId.NextId(),
                            //                orderId = item.rawOutstockId,
                            //                taskType = 38,
                            //                containerNo = location.containerCode,
                            //                createBy = "WCS",
                            //                createTime = DateTime.Now,
                            //                taskStatus = -1,
                            //                materialId = item.materialId,
                            //                currPointId = location.locationId,
                            //                currPointNo = location.locationCode,
                            //                nextPointId = ctuEquip.objid,
                            //                nextPointNo = ctuEquip.equipNo,
                            //                endPointId = lineEquip.objid,
                            //                endPointNo = lineEquip.equipNo,
                            //                equipmentNo = ctuEquip.equipNo,
                            //                ud1 = location.locColumn,
                            //                useFlag = 1,
                            //                qty = qty
                            //            };
                            //            MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.Where(t => t.barcodeInfo == stock.instockBatch).FirstOrDefault();
                            //            if (mesBaseBarcodeInfo != null)
                            //            {
                            //                WmsRawOutstockDetail wmsProductOutstockDetail = new WmsRawOutstockDetail()
                            //                {
                            //                    rawOutstockDetailId = StaticData.SnowId.NextId(),
                            //                    rawOutstockId = item.rawOutstockId,
                            //                    materialId = item.materialId,
                            //                    createDate = DateTime.Now,
                            //                    createBy = "WCS",
                            //                    taskCode = wcsTask.objid.ToString(),
                            //                    executeStatus = "1",
                            //                    locationCode = location.locationCode,
                            //                    outstockAmount = qty,
                            //                    planAmount = item.outstockAmount,
                            //                    warehouseId = item.warehouseId,
                            //                    materialBarcode = mesBaseBarcodeInfo.barcodeInfo,
                            //                    instockBatch = mesBaseBarcodeInfo.batchCode,
                            //                    stackAmount = qty,
                            //                    outstockPerson = "WCS",
                            //                    outstockTime = DateTime.Now,
                            //                    outstockWay = "2",
                            //                    materialProductionDate = mesBaseBarcodeInfo.productionDate
                            //                };
                            //                location.outstockFlag = "1";
                            //                location.locationStatus = "6";
                            //                location.updateBy = "WCS";
                            //                location.updateTime = DateTime.Now;
                            //                wcsOutstockLock.boxStatus = 1;
                            //                dbContext.Add(wmsProductOutstockDetail);
                            //                dbContext.Update(location);
                            //                dbContext.Add(wcsTask);
                            //                dbContext.Update(stock);
                            //                if (qty >= needNumber)
                            //                {
                            //                    break;
                            //                }
                            //            }
                            //        }
                            //        if (item.beginTime == null)
                            //        {
                            //            item.beginTime = DateTime.Now;
                            //        }
                            //        dbContext.Update(wcsOutstockLock);
                            //        dbContext.Update(item);
                            //        dbContext.SaveChanges();
                            //    }
                            //}//CTU出库
                            #endregion
                            if (endEquip.equipType == 10)//CTU出库到装配区
                            {
                                lock (SystemData.outStockLock)
                                {
                                    //原材料库存
                                    var rawStock = dbContext.WmsRawStock
                                        .Where(t => t.activeFlag == "1").ToList();
                                    BaseEquip endStationCodeEquip = dbContext.BaseEquip.First(t => t.objid == 10);
                                    if (!string.IsNullOrEmpty(endStationCodeEquip.endStationCode) && endStationCodeEquip.IsOut == 1)
                                    {
                                        if (item.endStationCode != endStationCodeEquip.endStationCode)
                                        {
                                            continue;
                                        }
                                        bool CreateSuccess = false;
                                        bool hasTask = dbContext.WcsTask.Where(t => t.nextPointId == 11).Any();
                                        if (!hasTask)
                                        {
                                            var orderList = rawOutStock.Where(t => t.endStationCode == endStationCodeEquip.endStationCode).ToList();
                                            List<WcsTask> tasks = new();
                                            List<long?> canOut = orderList.Select(t => t.saleOrderId).ToList();
                                            rawStock = rawStock.Where(t => canOut.Contains(t.saleOrderId)).OrderByDescending(t => t.saleOrderId).ToList();
                                            //对物料和数量进行分组
                                            var list = orderList.GroupBy(t => new { t.materialId, t.saleOrderId }).Select(t => new
                                            {
                                                MaterialId = t.Key.materialId,
                                                SaleOrderId = t.Key.saleOrderId,
                                                TotalAmount = t.Sum(x => x.outstockAmount),
                                                realOutstockAmount = t.Sum(x => x.realOutstockAmount)
                                            }
                                            ).ToList();
                                            int? index = 1;
                                            foreach (var order in list)
                                            {
                                                if (tasks.Count >= 6)
                                                {
                                                    break;
                                                }
                                                var wmsRawStocks = rawStock
                                                   .Where(t => t.materialId == order.MaterialId && t.saleOrderId == (order.SaleOrderId == null ? 0 : order.SaleOrderId) && t.warehouseId == 512)
                                                   .Select(t => t.palletInfoCode)
                                                   .ToList();
                                                var AllWmsBaseLocations = dbContext.WmsBaseLocation.Where(t => t.warehouseId == 512).ToList();
                                                var wmsBaseLocations = AllWmsBaseLocations
                                                    .Where(t => t.activeFlag == "1")
                                                    .Where(t => t.delFlag == "0")
                                                    .Where(t => t.locationScrapType == "1")
                                                    .Where(t => t.locationStatus == "1")
                                                    .Where(t => t.warehouseId == 512)
                                                    .Where(t => t.ContainerStatus == "1")
                                                    .Where(t => wmsRawStocks.Contains(t.containerCode))
                                                    .ToList();

                                                decimal? needNumber = order.TotalAmount - order.realOutstockAmount;
                                                // 寻找已经创建任务的料箱中的是否含有当前物料（A物料在料箱A\B中，然后找B物料的时候是否在料箱A\B中）
                                                foreach (var task in tasks)
                                                {
                                                    var wmsRawStock = rawStock.Where(t => t.palletInfoCode == task.containerNo && t.materialId == order.MaterialId && t.saleOrderId == order.SaleOrderId).ToList();
                                                    decimal? total = wmsRawStock.Sum(t => t.totalAmount) - wmsRawStock.Sum(t => t.frozenAmount);
                                                    needNumber -= total;
                                                    WmsBaseLocation wmsBaseLocation = AllWmsBaseLocations.Where(t => t.locationCode == task.currPointNo).First();
                                                    index = wmsBaseLocation.locRow;
                                                }
                                                if (needNumber <= 0)
                                                {
                                                    continue;
                                                }
                                                var bill = from a in wmsBaseLocations
                                                           from b in rawStock
                                                           where a.containerCode == b.palletInfoCode && b.materialId == order.MaterialId && b.saleOrderId == (order.SaleOrderId == null ? 0 : order.SaleOrderId)
                                                           select new { a, b };
                                                //如果第一列满足需求,则按第一列排序,否则按最后一列排序
                                                if (bill.Where(t => t.a.locRow == index).Select(t => t.b.totalAmount - t.b.frozenAmount).Sum() >= needNumber)
                                                {
                                                    if (index == 1)
                                                    {
                                                        bill = bill.OrderBy(t => t.a.locRow).ThenBy(t => t.a.locColumn).ToList();
                                                        index = 2;
                                                    }
                                                    else
                                                    {
                                                        bill = bill.OrderByDescending(t => t.a.locRow).ThenBy(t => t.a.locColumn).ToList();
                                                        index = 1;
                                                    }
                                                }
                                                else
                                                {
                                                    bill = bill.OrderByDescending(t => t.a.locRow).ThenBy(t => t.a.locColumn).ToList();
                                                    if (index == 1)
                                                    {
                                                        bill = bill.OrderByDescending(t => t.a.locRow).ThenBy(t => t.a.locColumn).ToList();
                                                        index = 2;
                                                    }
                                                    else
                                                    {
                                                        bill = bill.OrderBy(t => t.a.locRow).ThenBy(t => t.a.locColumn).ToList();
                                                        index = 1;
                                                    }
                                                }
                                                BaseEquip ctuEquip = StaticData.BaseEquip.First(t => t.objid == 11);
                                                BaseEquip lineEquip = StaticData.BaseEquip.First(t => t.objid == 20);
                                                foreach (var b in bill)
                                                {
                                                    if (needNumber <= 0 || tasks.Count >= 6)
                                                    {
                                                        break;
                                                    }
                                                    if (tasks.Where(t => t.containerNo == b.a.containerCode).Any())//判读当前料箱是否存在出库任务
                                                    {
                                                        continue;
                                                    }
                                                    WmsBaseLocation location = b.a;
                                                    WmsRawStock stock = b.b;
                                                    int qty = 0;
                                                    if (stock.totalAmount - stock.frozenAmount <= needNumber)//该料箱全部出
                                                    {
                                                        needNumber -= (stock.totalAmount - stock.frozenAmount);
                                                        qty = Convert.ToInt32(stock.totalAmount - stock.frozenAmount);
                                                        stock.updateDate = DateTime.Now;
                                                    }
                                                    else
                                                    {
                                                        qty = Convert.ToInt32(needNumber);
                                                        needNumber = 0;
                                                        stock.updateDate = DateTime.Now;
                                                    }
                                                    WmsRawOutstock? wmsRawOutstock = orderList.Where(t => t.materialId == order.MaterialId).FirstOrDefault();
                                                    if (wmsRawOutstock != null)
                                                    {
                                                        var wcsTask = new WcsTask()
                                                        {
                                                            objid = StaticData.SnowId.NextId(),
                                                            orderId = wmsRawOutstock.rawOutstockId,
                                                            taskType = StaticTaskType.FiveAccessoryOut,
                                                            containerNo = location.containerCode,
                                                            createBy = "WCS",
                                                            createTime = DateTime.Now,
                                                            taskStatus = 0,
                                                            materialId = wmsRawOutstock.materialId,
                                                            currPointId = location.locationId,
                                                            currPointNo = location.locationCode,
                                                            nextPointId = ctuEquip.objid,
                                                            nextPointNo = ctuEquip.equipNo,
                                                            endPointId = lineEquip.objid,
                                                            endPointNo = lineEquip.equipNo,
                                                            equipmentNo = ctuEquip.equipNo,
                                                            ud1 = location.locColumn,
                                                            useFlag = 1,
                                                            qty = qty
                                                        };
                                                        tasks.Add(wcsTask);
                                                        location.locationStatus = "6";
                                                        location.updateBy = "WCS";
                                                       // location.ContainerStatus = "2";
                                                        location.updateTime = DateTime.Now;
                                                        dbContext.Update(location);
                                                        dbContext.Update(stock);
                                                        CreateSuccess = true;
                                                        if (tasks.Count >= 6)
                                                        {
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            if (CreateSuccess)
                                            {
                                                endStationCodeEquip.IsOut = 0;
                                                foreach (var orderItem in orderList)
                                                {
                                                    if (orderItem.beginTime == null)
                                                    {
                                                        orderItem.beginTime = DateTime.Now;
                                                    }
                                                    orderItem.executeStatus = "1";
                                                }
                                                BaseEquip startStationEquip = StaticData.BaseEquip.First(t => t.objid == 21);
                                                BaseEquip bearAgvEquip = StaticData.BaseEquip.First(t => t.objid == 10);
                                                BaseEquip endStationEquip = StaticData.BaseEquip.First(t => t.equipNo == endStationCodeEquip.endStationCode);
                                                hasTask = dbContext.WcsTask.Where(t => t.taskType == 32).Any();
                                                if (!hasTask)
                                                {
                                                    WcsTask bearAgvTask = new()
                                                    {
                                                        objid = StaticData.SnowId.NextId(),
                                                        orderId = item.rawOutstockId,
                                                        taskType = 32,
                                                        containerNo = null,
                                                        currPointId = startStationEquip.objid,
                                                        currPointNo = startStationEquip.equipNo,
                                                        nextPointId = bearAgvEquip.objid,
                                                        nextPointNo = bearAgvEquip.equipNo,
                                                        endPointId = endStationEquip.objid,
                                                        endPointNo = endStationEquip.equipNo,
                                                        serialNo = SystemData.GetSerialNo(dbContext),
                                                        taskStatus = 0,
                                                        createTime = DateTime.Now,
                                                        createBy = "WCS",
                                                        materialId = item.materialId,
                                                        qty = 1,
                                                        useFlag = 1,
                                                        equipmentNo = startStationEquip.equipNo,
                                                        remark = "组装出库",
                                                        floorNo = 5,
                                                        masterId = item.materialId,
                                                        fromFloorNo = 5,
                                                    };
                                                    dbContext.Add(bearAgvTask);
                                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(bearAgvTask);
                                                    dbContext.Add(wcsTaskLog);
                                                }

                                                if (item.beginTime == null)
                                                {
                                                    item.beginTime = DateTime.Now;
                                                }
                                                dbContext.UpdateRange(orderList);
                                                dbContext.Update(item);
                                            }
                                            dbContext.Update(endStationCodeEquip);
                                            if (tasks.Count > 0)
                                            {
                                                dbContext.AddRange(tasks);
                                            }
                                            dbContext.SaveChanges();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                lock (SystemData.FiveTaskLock)
                                {
                                    if (endEquip.equipType == 12)//原材料到柜体拆分区
                                    {
                                        var rawStock = dbContext.WmsRawStock
                                       .Where(t => t.activeFlag == "1").ToList();
                                        bool hasTask = dbContext.WcsTask.Where(t => t.currPointId == endEquip.objid || t.endPointId == endEquip.objid).Any();
                                        if (!hasTask)
                                        {
                                            if (endEquip.emptyCount == 0)
                                            {
                                                var wmsRawStocks = rawStock
                                                   .Where(t => t.materialId == item.materialId && t.warehouseId == item.warehouseId)
                                                   .WhereIf(endEquip.equipType == 12, t => t.completeFlag == "1")
                                                   .Where(t => t.saleOrderId == (item.saleOrderId == null ? 0 : item.saleOrderId))
                                                   .Where(t => t.totalAmount > t.frozenAmount)
                                                   .Select(t => t.palletInfoCode)
                                                   .ToList();
                                                List<WmsBaseLocation> AllWmsBaseLocations = dbContext.WmsBaseLocation.Where(t => t.warehouseId == item.warehouseId).ToList();
                                                var wmsBaseLocations = AllWmsBaseLocations
                                                    .Where(t => t.activeFlag == "1")
                                                    .Where(t => t.delFlag == "0")
                                                    .Where(t => t.locationScrapType == "1")
                                                    .Where(t => t.locationStatus == "1")
                                                    .Where(t => t.warehouseId == item.warehouseId)
                                                    .OrderByDescending(t => t.locDeep)
                                                    .Where(t => wmsRawStocks.Contains(t.containerCode))
                                                    .ToList();

                                                decimal? needNumber = item.outstockAmount - item.realOutstockAmount;

                                                var bill = from a in wmsBaseLocations
                                                           from b in rawStock
                                                           where a.locationCode == b.locationCode
                                                           select new { a, b };

                                                BaseEquip agvEquip = StaticData.BaseEquip.First(t => t.objid == 28);
                                                BaseEquip lineEquip = StaticData.BaseEquip.First(t => t.equipNo == item.endStationCode);
                                                foreach (var b in bill)
                                                {
                                                    item.executeStatus = "1";
                                                    WmsBaseLocation location = b.a;
                                                    WmsRawStock stock = b.b;
                                                    WcsTask wcsTask;
                                                    int qty = 0;
                                                    if (stock.totalAmount - stock.frozenAmount <= needNumber)//该料箱全部出
                                                    {
                                                        qty = Convert.ToInt32(stock.totalAmount - stock.frozenAmount);
                                                        stock.updateDate = DateTime.Now;
                                                    }
                                                    else
                                                    {
                                                        qty = Convert.ToInt32(needNumber);
                                                        stock.updateDate = DateTime.Now;
                                                    }
                                                    MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.Where(t => t.barcodeInfo == stock.instockBatch).FirstOrDefault();
                                                    if (mesBaseBarcodeInfo != null)
                                                    {
                                                        if (location.locDeep == 1)
                                                        {
                                                            int? row = 0;
                                                            if (location.locRow % 2 == 1)//五楼原材料与其他的深浅库位相反
                                                            {
                                                                row = location.locRow + 1;
                                                            }
                                                            else
                                                            {
                                                                row = location.locRow - 1;//5
                                                            }
                                                            var lowLocationBill = bill.Where(t => t.a.locRow == row).Where(t => t.a.locColumn == location.locColumn).Where(t => t.a.warehouseId == location.warehouseId).FirstOrDefault();
                                                            if (lowLocationBill != null)
                                                            {
                                                                location = lowLocationBill.a;
                                                                stock = lowLocationBill.b;
                                                            }
                                                            else
                                                            {
                                                                WmsBaseLocation? wmsBaseLocation = AllWmsBaseLocations
                                                                    .Where(t => t.locRow == row)
                                                                    .Where(t => t.locColumn == location.locColumn)
                                                                    .Where(t => t.warehouseId == location.warehouseId).FirstOrDefault();
                                                                if (!string.IsNullOrEmpty(wmsBaseLocation.containerCode) && wmsBaseLocation.locationStatus == "1")
                                                                {
                                                                    WmsRawStock? wmsRawStock = dbContext.WmsRawStock.FirstOrDefault(t => t.locationCode == wmsBaseLocation.locationCode);
                                                                    if (wmsRawStock != null)
                                                                    {
                                                                        #region
                                                                        // 寻找移库目的库位
                                                                        WmsBaseLocation? toLocation = null;


                                                                        var moveLocationList = AllWmsBaseLocations.Where(t => t.warehouseId == location.warehouseId)
                                                                            .Where(t => t.warehouseId != location.locationId)
                                                                            .Where(t => string.IsNullOrEmpty(t.containerCode) && t.locationStatus == "1").OrderBy(t => t.locDeep).ToList();

                                                                        foreach (WmsBaseLocation itemLocation in moveLocationList)
                                                                        {

                                                                            if (itemLocation.locDeep == 1)
                                                                            {
                                                                                bool hasLocation = AllWmsBaseLocations
                                                                                .Where(t => t.locRow == (itemLocation.locRow % 2 == 1 ? (itemLocation.locRow + 1) : (itemLocation.locRow - 1)))
                                                                                .Where(t => t.locColumn == itemLocation.locColumn)
                                                                                .Where(t => t.locationStatus == "1" && string.IsNullOrEmpty(t.containerCode))
                                                                                    .Any();
                                                                                if (!hasLocation)
                                                                                {
                                                                                    Console.WriteLine(DateTime.Now + $":目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                                    _logger.Info($"目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                                    continue;
                                                                                }
                                                                                else
                                                                                {
                                                                                    // 找到可以移库的目标库位
                                                                                    toLocation = itemLocation;
                                                                                    break;
                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                // 找到可以移库的目标库位
                                                                                toLocation = itemLocation;
                                                                                break;
                                                                            }

                                                                        }
                                                                        if (toLocation == null)
                                                                        {
                                                                            // TODO : 没有找到可以移库的目标库位，添加报警
                                                                            Console.WriteLine("5F原材料前往背板安装需要先移库，没有找到可以移库的目标库位，添加报警");
                                                                            Thread.Sleep(1000 * 5);
                                                                            continue;
                                                                        }
                                                                        var RemoveTask = new WcsTask()
                                                                        {
                                                                            objid = StaticData.SnowId.NextId(),
                                                                            orderId = item.rawOutstockId,
                                                                            taskType = StaticTaskType.FiveRemove,
                                                                            containerNo = wmsRawStock.palletInfoCode,
                                                                            createBy = "WCS",
                                                                            createTime = DateTime.Now.AddSeconds(-10),
                                                                            taskStatus = 0,
                                                                            materialId = item.materialId,
                                                                            currPointId = wmsBaseLocation.locationId,
                                                                            currPointNo = wmsBaseLocation.locationCode,
                                                                            nextPointId = agvEquip.objid,
                                                                            nextPointNo = agvEquip.equipNo,
                                                                            endPointId = toLocation.locationId,
                                                                            endPointNo = toLocation.locationCode,
                                                                            equipmentNo = agvEquip.equipNo,
                                                                            useFlag = 1,
                                                                            qty = qty
                                                                        };
                                                                        toLocation.locationStatus = "4";
                                                                        toLocation.updateBy = "WCS";
                                                                        toLocation.updateTime = DateTime.Now;
                                                                        wmsBaseLocation.updateBy = "WCS";
                                                                        wmsBaseLocation.updateTime = DateTime.Now;
                                                                        wmsBaseLocation.locationStatus = "4";
                                                                        dbContext.Update(toLocation);
                                                                        dbContext.Update(wmsBaseLocation);
                                                                        dbContext.Add(RemoveTask);
                                                                        WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(RemoveTask);
                                                                        dbContext.Add(wcsTaskLog);
                                                                        #endregion

                                                                    }
                                                                    else
                                                                    {
                                                                        continue;
                                                                    }
                                                                }
                                                                else if (wmsBaseLocation != null && wmsBaseLocation.locationStatus != "1")
                                                                {
                                                                    Console.WriteLine(DateTime.Now + $":{wmsBaseLocation.locationCode}库位状态异常，无法移库");
                                                                    _logger.Info($"{wmsBaseLocation.locationCode}库位状态异常，无法移库");
                                                                    continue;
                                                                }
                                                            }
                                                        }
                                                        wcsTask = new WcsTask()
                                                        {
                                                            objid = StaticData.SnowId.NextId(),
                                                            orderId = item.rawOutstockId,
                                                            taskType = StaticTaskType.FiveRawToSplit,//如果是12那么就是原材料到柜体验收区,如果是13那么就是原材料到背板安装区
                                                            containerNo = location.containerCode,
                                                            createBy = "WCS",
                                                            createTime = DateTime.Now,
                                                            taskStatus = 0,
                                                            materialId = item.materialId,
                                                            currPointId = location.locationId,
                                                            currPointNo = location.locationCode,
                                                            nextPointId = agvEquip.objid,
                                                            nextPointNo = agvEquip.equipNo,
                                                            endPointId = lineEquip.objid,
                                                            endPointNo = lineEquip.equipNo,
                                                            equipmentNo = agvEquip.equipNo,
                                                            useFlag = 1,
                                                            qty = qty
                                                        };
                                                        //location是出库的库位，mesBaseBarcodeInfo是条码信息表数据，item是出库申请单
                                                        WmsRawOutstockDetail wmsProductOutstockDetail = new WmsRawOutstockDetail()
                                                        {
                                                            rawOutstockDetailId = StaticData.SnowId.NextId(),
                                                            rawOutstockId = item.rawOutstockId,
                                                            materialId = item.materialId,
                                                            createDate = DateTime.Now,
                                                            createBy = "WCS",
                                                            taskCode = wcsTask.objid.ToString(),
                                                            executeStatus = "1",
                                                            locationCode = location.locationCode,
                                                            outstockAmount = qty,
                                                            planAmount = item.outstockAmount,
                                                            warehouseId = item.warehouseId,
                                                            materialBarcode = mesBaseBarcodeInfo.barcodeInfo,
                                                            instockBatch = mesBaseBarcodeInfo.batchCode,
                                                            stackAmount = qty,
                                                            outstockPerson = "WCS",
                                                            outstockTime = DateTime.Now,
                                                            outstockWay = "2",
                                                            materialProductionDate = mesBaseBarcodeInfo.productionDate
                                                        };
                                                        if (item.beginTime == null)
                                                        {
                                                            item.beginTime = DateTime.Now;
                                                        }
                                                        SystemData.LockOutLocation(location, dbContext);
                                                        dbContext.Add(wmsProductOutstockDetail);
                                                        location.locationStatus = "6";
                                                        location.updateBy = "WCS";
                                                        location.updateTime = DateTime.Now;
                                                        endEquip.emptyCount = 1;
                                                        dbContext.Update(endEquip);
                                                        dbContext.Update(location);
                                                        dbContext.Add(wcsTask);
                                                        dbContext.Update(item);
                                                        dbContext.Update(stock);
                                                        WcsTaskLog wcsTaskLog1 = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                                        dbContext.Add(wcsTaskLog1);
                                                        dbContext.SaveChanges();
                                                    }

                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    else if (endEquip.equipType == 13)  //原材料到背板安装
                                    {
                                        var stock = dbContext.WmsRawStock.Where(t => t.instockBatch == item.materialBatch).FirstOrDefault();
                                        if (stock != null)
                                        {
                                            var location = dbContext.WmsBaseLocation
                                            .Where(t => t.locationStatus == "1")
                                            .Where(t => t.locationCode == stock.locationCode).FirstOrDefault();
                                            if (location != null)
                                            {
                                                List<WmsBaseLocation> AllWmsBaseLocations = dbContext.WmsBaseLocation
                                                    .Where(t => t.warehouseId == item.warehouseId).ToList();
                                                decimal? needNumber = item.outstockAmount - item.realOutstockAmount;
                                                BaseEquip agvEquip = StaticData.BaseEquip.First(t => t.objid == 28);
                                                BaseEquip lineEquip = StaticData.BaseEquip.First(t => t.equipNo == item.endStationCode);
                                                WcsTask wcsTask;
                                                int qty = 0;
                                                if (stock.totalAmount - stock.frozenAmount <= needNumber)//该料箱全部出
                                                {
                                                    qty = Convert.ToInt32(stock.totalAmount - stock.frozenAmount);
                                                    stock.updateDate = DateTime.Now;
                                                }
                                                else
                                                {
                                                    qty = Convert.ToInt32(needNumber);
                                                    stock.updateDate = DateTime.Now;
                                                }
                                                MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.Where(t => t.barcodeInfo == stock.instockBatch).FirstOrDefault();
                                                if (mesBaseBarcodeInfo != null)
                                                {
                                                    if (location.locationStatus != "1")
                                                    {
                                                        Console.WriteLine(DateTime.Now + $":{location.locationCode}库位状态异常，无法出库");
                                                        _logger.Info($"{location.locationCode}库位状态异常，无法出库");
                                                        continue;
                                                    }
                                                    if (location.locDeep == 1)
                                                    {
                                                        int? row = 0;
                                                        if (location.locRow % 2 == 1)//五楼原材料与其他的深浅库位相反
                                                        {
                                                            row = location.locRow + 1;
                                                        }
                                                        else
                                                        {
                                                            row = location.locRow - 1;//5
                                                        }
                                                        //对应的浅库位
                                                        WmsBaseLocation? wmsBaseLocation = AllWmsBaseLocations
                                                            .Where(t => t.locRow == row)
                                                            .Where(t => t.locColumn == location.locColumn)
                                                            .Where(t => t.warehouseId == location.warehouseId).FirstOrDefault();

                                                        if (!string.IsNullOrEmpty(wmsBaseLocation.containerCode) && wmsBaseLocation.locationStatus == "1")
                                                        {
                                                            // 浅库位有库存
                                                            WmsRawStock? wmsRawStock = dbContext.WmsRawStock.FirstOrDefault(t => t.locationCode == wmsBaseLocation.locationCode);


                                                            // 寻找移库目的库位
                                                            WmsBaseLocation? toLocation = null;


                                                            var moveLocationList = AllWmsBaseLocations.Where(t => t.warehouseId == location.warehouseId)
                                                                .Where(t => t.warehouseId != location.locationId)
                                                                .Where(t => string.IsNullOrEmpty(t.containerCode) && t.locationStatus == "1").OrderBy(t => t.locDeep).ToList();

                                                            foreach (WmsBaseLocation itemLocation in moveLocationList)
                                                            {

                                                                if (itemLocation.locDeep == 1)
                                                                {
                                                                    bool hasLocation = AllWmsBaseLocations
                                                                    .Where(t => t.locRow == (itemLocation.locRow % 2 == 1 ? (itemLocation.locRow + 1) : (itemLocation.locRow - 1)))
                                                                    .Where(t => t.locColumn == itemLocation.locColumn)
                                                                    .Where(t => t.locationStatus == "1" && string.IsNullOrEmpty(t.containerCode))
                                                                        .Any();
                                                                    if (!hasLocation)
                                                                    {
                                                                        Console.WriteLine(DateTime.Now + $":目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                        _logger.Info($"目标库位{toLocation.locationCode}的浅库位库位状态异常，无法移库");
                                                                        continue;
                                                                    }
                                                                    else
                                                                    {
                                                                        // 找到可以移库的目标库位
                                                                        toLocation = itemLocation;
                                                                        break;
                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    // 找到可以移库的目标库位
                                                                    toLocation = itemLocation;
                                                                    break;
                                                                }

                                                            }
                                                            if (toLocation == null)
                                                            {
                                                                // TODO : 没有找到可以移库的目标库位，添加报警
                                                                Console.WriteLine("5F原材料前往背板安装需要先移库，没有找到可以移库的目标库位，添加报警");
                                                                continue;
                                                            }
                                                            var RemoveTask = new WcsTask()
                                                            {
                                                                objid = StaticData.SnowId.NextId(),
                                                                orderId = item.rawOutstockId,
                                                                taskType = StaticTaskType.FiveRemove,
                                                                containerNo = wmsRawStock.palletInfoCode,
                                                                createBy = "WCS",
                                                                createTime = DateTime.Now.AddSeconds(-10),
                                                                taskStatus = 0,
                                                                materialId = item.materialId,
                                                                currPointId = wmsBaseLocation.locationId,
                                                                currPointNo = wmsBaseLocation.locationCode,
                                                                nextPointId = agvEquip.objid,
                                                                nextPointNo = agvEquip.equipNo,
                                                                endPointId = toLocation.locationId,
                                                                endPointNo = toLocation.locationCode,
                                                                equipmentNo = agvEquip.equipNo,
                                                                useFlag = 1,
                                                                qty = qty
                                                            };
                                                            toLocation.locationStatus = "4";
                                                            toLocation.updateBy = "WCS";
                                                            toLocation.updateTime = DateTime.Now;
                                                            wmsBaseLocation.updateBy = "WCS";
                                                            wmsBaseLocation.updateTime = DateTime.Now;
                                                            wmsBaseLocation.locationStatus = "4";
                                                            dbContext.Update(toLocation);
                                                            dbContext.Update(wmsBaseLocation);
                                                            dbContext.Add(RemoveTask);
                                                            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(RemoveTask);
                                                            dbContext.Add(wcsTaskLog);

                                                        }
                                                        else if (wmsBaseLocation.locationStatus != "1")
                                                        {
                                                            Console.WriteLine("浅库位状态异常，禁止出库，请检查浅库位状态");
                                                            continue;
                                                        }
                                                    }

                                                    //else
                                                    //{
                                                    //    Console.WriteLine(DateTime.Now + $":{location.locationCode}浅库位状态异常，无法移库");
                                                    //    _logger.Info($"{location.locationCode}浅库位状态异常，无法移库");
                                                    //    continue;
                                                    //}
                                                }
                                                wcsTask = new WcsTask()
                                                {
                                                    objid = StaticData.SnowId.NextId(),
                                                    orderId = item.rawOutstockId,
                                                    taskType = StaticTaskType.FiveRawToBack,//如果是12那么就是原材料到柜体验收区,如果是13那么就是原材料到背板安装区
                                                    containerNo = location.containerCode,
                                                    createBy = "WCS",
                                                    createTime = DateTime.Now,
                                                    taskStatus = 0,
                                                    materialId = item.materialId,
                                                    currPointId = location.locationId,
                                                    currPointNo = location.locationCode,
                                                    nextPointId = agvEquip.objid,
                                                    nextPointNo = agvEquip.equipNo,
                                                    endPointId = lineEquip.objid,
                                                    endPointNo = lineEquip.equipNo,
                                                    equipmentNo = agvEquip.equipNo,
                                                    useFlag = 1,
                                                    qty = qty
                                                };
                                                //location是出库的库位，mesBaseBarcodeInfo是条码信息表数据，item是出库申请单
                                                //WmsRawOutstockDetail wmsProductOutstockDetail = new WmsRawOutstockDetail()
                                                //{
                                                //    rawOutstockDetailId = StaticData.SnowId.NextId(),
                                                //    rawOutstockId = item.rawOutstockId,
                                                //    materialId = item.materialId,
                                                //    createDate = DateTime.Now,
                                                //    createBy = "WCS",
                                                //    taskCode = wcsTask.objid.ToString(),
                                                //    executeStatus = "1",
                                                //    locationCode = location.locationCode,
                                                //    outstockAmount = qty,
                                                //    planAmount = item.outstockAmount,
                                                //    warehouseId = item.warehouseId,
                                                //    materialBarcode = mesBaseBarcodeInfo.barcodeInfo,
                                                //    instockBatch = mesBaseBarcodeInfo.batchCode,
                                                //    stackAmount = qty,
                                                //    outstockPerson = "WCS",
                                                //    outstockTime = DateTime.Now,
                                                //    outstockWay = "2",
                                                //    materialProductionDate = mesBaseBarcodeInfo.productionDate
                                                //};
                                                if (item.beginTime == null)
                                                {
                                                    item.beginTime = DateTime.Now;
                                                }
                                                SystemData.LockOutLocation(location, dbContext);
                                                //dbContext.Add(wmsProductOutstockDetail);
                                                location.locationStatus = "6";
                                                location.updateBy = "WCS";
                                                location.updateTime = DateTime.Now;
                                                endEquip.emptyCount = 1;
                                                dbContext.Update(endEquip);
                                                dbContext.Update(location);
                                                dbContext.Add(wcsTask);
                                                dbContext.Update(item);
                                                dbContext.Update(stock);
                                                WcsTaskLog wcsTaskLog1 = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                                dbContext.Add(wcsTaskLog1);
                                                dbContext.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message + "\n" + ex.StackTrace);
                }
                Thread.Sleep(3000);
            }

        }


    }
}
