using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Xml;
using System.Linq;
using Infrastructure;
using WebRepository;
using ServiceReference1;

namespace WebApp
{
    /// <summary>
    /// 堆垛机运行节点接口App
    /// </summary>

    public partial class IStackerStatusApp : ApiApp
    {
        public IRepository<ReceiptHeader> _apprh;
        public IRepository<Container> _appc;
        public IRepository<ReceiptDetail> _apprd;
        public IRepository<Inventory> _appi;
        private object obj = new object();
        public IStackerStatusApp(IUnitWork unitWork, IRepository<Inventory> inventory, IRepository<Container> Container, IAuth auth, BaseDBContext context, IRepository<ReceiptDetail> receiptDetail, IRepository<ReceiptHeader> receiptHeader) : base(unitWork, auth, context)
        {
            _apprd = receiptDetail;
            _apprh = receiptHeader;
            _appi = inventory;
            _appc = Container;

            //系统字段赋值
            _apprd._loginInfo = _apprh._loginInfo = _loginInfo;
            _appi._loginInfo = _apprh._loginInfo = _loginInfo;
            _appc._loginInfo = _apprh._loginInfo = _loginInfo;
        }

        public Response<TaskDetail> SetStackerStatus(STKStatusModel sTKStatusModel)
        {
            using (var tran = _context.Database.BeginTransaction())
            {
                Response<TaskDetail> Response = new Response<TaskDetail>();
                try
                {
                    TaskDetail td = null;
                    if (sTKStatusModel.Status == 30)
                    {
                        td = _unitWork.FindSingle<TaskDetail>(u => u.TaskNo == sTKStatusModel.TaskNo && u.Status >= TaskStatus.新建任务 && u.Status < TaskStatus.已经完成);
                    }
                    else if (sTKStatusModel.Status == 40)
                    {
                        td = _unitWork.FindSingle<TaskDetail>(u => u.TaskNo == sTKStatusModel.TaskNo && u.Status >= TaskStatus.新建任务 && u.Status < TaskStatus.已经完成);
                    }
                    //WCS回库 货物到Rgv上给一次反馈站台占用解除
                    else if (sTKStatusModel.Status == 10)
                    {
                        td = _unitWork.FindSingle<TaskDetail>(u => u.TaskNo == sTKStatusModel.TaskNo && u.Status >= TaskStatus.新建任务 && u.Status < TaskStatus.已经完成);
                        Station stationType = _unitWork.Find<Station>(n => n.Code == td.SourceLocation).FirstOrDefault();
                        if (td == null)
                        {
                            Response.Message = "重发";
                            return Response;
                        }
                        if (stationType != null)
                        {
                            if (stationType.Type == StationType.PP片上胶站台)
                            {
                                Station stationEmpty = (from se in _unitWork.Find<Station>(n => n.IsEmpty == 1 && n.IsStop == 0 && n.Containercode != "")
                                                        join sts in _unitWork.Find<StationToStation>(a => a.EndStation == td.SourceLocation)
                                                        on se.Code equals sts.StartStation
                                                        select se).FirstOrDefault();
                                if (stationEmpty != null)
                                {
                                    stationEmpty.Containercode = "";
                                    stationEmpty.UpdateBy = "wms";
                                    stationEmpty.UpdateTime = DateTime.Now;
                                    _unitWork.Update(stationEmpty);
                                }
                            }
                        }


                        //成品库入库
                        if (td.Roadway == 5)
                        {
                            StoreStation store = _unitWork.Find<StoreStation>(n => n.ContainerCode == td.ContainerCode && n.Status == StoreStationStatus.到达站台).FirstOrDefault();
                            if (store != null)
                            {
                                _unitWork.Delete(store);
                            }
                        }

                        if (td.Roadway == 2 && td.TaskType == TaskType.移库)
                        {
                            Location loc = _unitWork.Find<Location>(n => n.Code == td.SourceLocation && n.Status == LocationStatus.任务锁定中).FirstOrDefault();
                            if (loc == null)
                            {
                                Response.Code = 300;
                                Response.Status = false;
                                Response.Message = "移库初始仓位状态不正确!";
                                td.Error = "移库初始仓位状态不正确!";
                                _unitWork.Update(td);
                                return Response;
                            }
                            else
                            {
                                td.UpdateTime = DateTime.Now;
                                td.Error = "堆垛机已接任务:UpdateTime";
                                _unitWork.Update(td);
                            }
                        }
                        else if (td.Roadway == 1 && td.TaskType == TaskType.移库)
                        {
                            Location loc = _unitWork.Find<Location>(n => n.Code == td.SourceLocation && n.Status == LocationStatus.任务锁定中).FirstOrDefault();
                            if (loc == null)
                            {
                                Response.Code = 300;
                                Response.Status = false;
                                Response.Message = "移库初始仓位状态不正确!";
                                td.Error = "移库初始仓位状态不正确!";
                                _unitWork.Update(td);
                                return Response;
                            }
                            else
                            {
                                _unitWork.Update<Location>(n => n.Id == loc.Id && n.Version == loc.Version, n => new Location
                                {
                                    Status = LocationStatus.空仓位,
                                    ContainerCode = "",
                                    UpdateTime = DateTime.Now
                                });
                                td.UpdateTime = DateTime.Now;
                                td.Error = "堆垛机已接任务:UpdateTime";
                                _unitWork.Update(td);
                            }
                        }
                        else
                        {
                            Station station = _unitWork.Find<Station>(n => n.Code == td.SourceLocation && n.Containercode == td.ContainerCode && td.SourceLocation != "PP_SpecialPoint").FirstOrDefault();
                            if (station != null)
                            {
                                station.Containercode = "";
                                station.UpdateBy = "wms";
                                station.UpdateTime = DateTime.Now;
                            }
                            else if (_unitWork.IsExist<Station>(n => n.Containercode == td.SourceLocation))
                            {
                                station = _unitWork.Find<Station>(n => n.Code == td.SourceLocation).FirstOrDefault();
                                station.Containercode = "";
                                station.UpdateBy = "wms";
                                station.UpdateTime = DateTime.Now;
                            }
                            else
                            {
                                Response.Message = "重发";
                                return Response;
                            }
                            _unitWork.Update(station);
                        }

                        tran.Commit();
                        return Response;
                    }
                    //WCS回库仓位高度请求
                    else if (sTKStatusModel.Status == 20)
                    {
                        td = _unitWork.Find<TaskDetail>(u => u.TaskNo == sTKStatusModel.TaskNo && u.Status >= TaskStatus.新建任务 && u.Status < TaskStatus.已经完成 && (u.TaskType == TaskType.容器回库 || u.TaskType == TaskType.空容器入库)).FirstOrDefault();
                        StationRoadway stationRoadway = _unitWork.Find<StationRoadway>(n => n.StationCode == td.SourceLocation).FirstOrDefault();
                        Location loc = null;
                        if (stationRoadway == null)
                        {
                            Response.Code = 300;
                            Response.Status = false;
                            Response.Message = "未找到起始站台!";
                            return Response;
                        }
                        else if (td == null)
                        {
                            Response.Code = 300;
                            Response.Status = false;
                            Response.Message = "未找到回库任务!";
                            return Response;
                        }
                        else if (_unitWork.IsExist<Location>(n => n.ContainerCode == td.ContainerCode))
                        {
                            if (_unitWork.IsExist<Inventory>(n => n.ContainerCode == td.ContainerCode && n.TaskStatus == InventoryTaskType.有盘点任务))
                            {
                                loc = _unitWork.Find<Location>(n => n.ContainerCode == td.ContainerCode).FirstOrDefault();
                            }
                            else
                            {
                                Response.Result = td;
                                Response.Message = "已有仓位!";
                                return Response;
                            }
                        }

                        Container container = _unitWork.Find<Container>(n => n.Code == td.ContainerCode).FirstOrDefault();
                        if (loc == null && container != null)
                        {
                            if (sTKStatusModel.Height == -1)
                            {
                                sTKStatusModel.Height = (int)container.Height;
                            }
                            string error = "";
                            while (true)
                            {
                                if (td.Roadway == 3)
                                {
                                    if (td.TaskType == TaskType.容器回库 && td.Roadway == 3 && _unitWork.IsExist<Inventory>(n => n.IsFold == "isflod" && n.ContainerCode == td.ContainerCode))
                                    {
                                        loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位).OrderBy(n => n.DistributionType).ThenBy(b => b.Layer).ThenBy(a => a.MaxHeight).ThenByDescending(y => y.Row).FirstOrDefault();
                                    }
                                    else
                                    {
                                        List<LocationDistribution> locationDistributions = _unitWork.Find<LocationDistribution>(n => n.RoadWay == td.Roadway).ToList();
                                        if (locationDistributions.Count != 0)
                                        {
                                            Inventory inventory = _unitWork.Find<Inventory>(n => n.ContainerCode == td.ContainerCode && n.NameDescription != "").FirstOrDefault();
                                            if (inventory != null)
                                            {
                                                foreach (LocationDistribution locationDistribution in locationDistributions)
                                                {
                                                    if (inventory.NameDescription.Substring((int)locationDistribution.ContrastStart - 1, (int)locationDistribution.Length) == locationDistribution.ContrastName)
                                                    {
                                                        loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == ""
                                                               && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                               && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2)
                                                               .OrderBy(n => (n.Layer==1||n.Layer==2) ? 13 : n.Layer).ThenBy(a => a.MaxHeight).ThenBy(n => n.Row).FirstOrDefault();

                                                        if (loc != null)
                                                        {
                                                            break;
                                                        }
                                                        else if (loc == null && locationDistribution.Type == DistributionType.静态库位)
                                                        {
                                                            Response.Code = 300;
                                                            Response.Status = false;
                                                            Response.Message = "未找到仓位!";
                                                            td.Error = "未找到仓位(分配仓位为静态)";
                                                            _unitWork.Update(td);
                                                            tran.Commit();
                                                            return Response;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        if (loc == null)
                                        {
                                            if (stationRoadway.StationPlace == StationPlace.巷道北面)
                                            {
                                                loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位).OrderBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => (a.Layer == 1 || a.Layer == 2)? 13 : a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                            }
                                            else if (stationRoadway.StationPlace == StationPlace.巷道南面)
                                            {
                                                loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位).OrderBy(n => n.DistributionType).ThenBy(b => (b.Layer == 1||b.Layer == 2)? 13 : b.Layer).ThenBy(a => a.MaxHeight).ThenByDescending(y => y.Row).FirstOrDefault();
                                            }
                                        }
                                    }
                                }
                                //仓位高度不一致的巷道 避免无仓位移库
                                else if (td.Roadway == 2)
                                {
                                    List<LocationDistribution> locationDistributions = _unitWork.Find<LocationDistribution>(n => n.RoadWay == td.Roadway).ToList();
                                    int locationDistributionType = LocationDistributionType.普通库位;
                                    if (locationDistributions.Count != 0)
                                    {
                                        Inventory inventory = _unitWork.Find<Inventory>(n => n.ContainerCode == td.ContainerCode && n.NameDescription != "").FirstOrDefault();
                                        if (inventory != null)
                                        {
                                            foreach (LocationDistribution locationDistribution in locationDistributions)
                                            {
                                                if (inventory.NameDescription.Substring((int)locationDistribution.ContrastStart - 1, (int)locationDistribution.Length) == locationDistribution.ContrastName)
                                                {
                                                    //查找可用空仓位或者空容器仓位 
                                                    loc = _unitWork.Find<Location>(n => ((n.Status == LocationStatus.空仓位 && n.ContainerCode == "") || n.Status == LocationStatus.空容器) && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay
                                                               && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                               && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2)
                                                               .OrderBy(n => n.Layer).ThenBy(a => a.MaxHeight).ThenBy(n => n.Row).FirstOrDefault();

                                                    locationDistributionType = (int)locationDistribution.Type;
                                                    if (loc != null)
                                                    {
                                                        break;
                                                    }
                                                }
                                            }
                                            if (loc == null && locationDistributionType == DistributionType.静态库位)
                                            {
                                                Response.Code = 300;
                                                Response.Status = false;
                                                Response.Message = "未找到仓位!";
                                                td.Error = "未找到仓位(分配仓位为静态)";
                                                _unitWork.Update(td);
                                                tran.Commit();
                                                return Response;
                                            }
                                        }
                                    }
                                    if (loc == null)
                                    {
                                        if (stationRoadway.StationPlace == StationPlace.巷道北面)
                                        {
                                            loc = _unitWork.Find<Location>(n => n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && ((n.Status == LocationStatus.空仓位 && n.ContainerCode == "") || n.Status == LocationStatus.空容器) && n.DistributionType != LocationDistributionType.被分配库位静态库位).OrderBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                        }
                                        else if (stationRoadway.StationPlace == StationPlace.巷道南面)
                                        {
                                            loc = _unitWork.Find<Location>(n => n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && ((n.Status == LocationStatus.空仓位 && n.ContainerCode == "") || n.Status == LocationStatus.空容器) && n.DistributionType != LocationDistributionType.被分配库位静态库位).OrderBy(n => n.DistributionType).ThenBy(b => (b.Layer)).ThenBy(a => a.MaxHeight).ThenByDescending(y => y.Row).FirstOrDefault();
                                        }
                                    }

                                        if (loc != null) {
                                            //确定需要移库
                                            if (loc.Status == LocationStatus.空容器)
                                            {
                                                decimal? height = loc.MaxHeight;
                                                Location locEmpty = null;
                                                //根据空容器仓位的高度重新查找是否有符合高度的空仓位
                                                locEmpty = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight == height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType == locationDistributionType).OrderBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                if (locEmpty == null)
                                                {
                                                    //在所有数据中查询移库目的地空仓位
                                                    locEmpty = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "").OrderBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenByDescending(a => a.Layer).ThenByDescending(y => y.Row).FirstOrDefault();
                                                    if (locEmpty == null)
                                                    {
                                                        Response.Code = 300;
                                                        Response.Status = false;
                                                        Response.Message = loc.Code + "未找到移库仓位:" + td.ContainerCode + "不能入库!";
                                                        td.Error = loc.Code + "未找到移库仓位:" + td.ContainerCode + "不能入库!";
                                                        _unitWork.Update(td);
                                                        return Response;
                                                    }
                                                    else
                                                    {
                                                        _unitWork.Update<Location>(n => n.Id == locEmpty.Id && n.Version == locEmpty.Version, n => new Location
                                                        {
                                                            Status = LocationStatus.任务锁定中,
                                                            ContainerCode = loc.ContainerCode,
                                                            UpdateTime = DateTime.Now
                                                        });
                                                    }

                                                    //建立移库任务
                                                    Task task = new Task();
                                                    string taskNo;
                                                    TaskDetail taskDetail = new TaskDetail();
                                                    taskNo = loc.Code + _apprh.GetTaskNo(TaskNo.移库);
                                                    task.TaskNo = taskNo;
                                                    task.OrderCode = taskNo;
                                                    task.BusinessType = BusinessType.入库_其他入库单;
                                                    task.FirstStatus = TaskStatus.下达任务;
                                                    task.LastStatus = TaskStatus.下达任务;
                                                    task.CreateTime = DateTime.Now;
                                                    _unitWork.Add(task);

                                                    taskDetail.TaskNo = taskNo;
                                                    taskDetail.OrderCode = taskNo;
                                                    taskDetail.SourceCode = td.TaskNo;
                                                    taskDetail.TaskType = TaskType.移库;
                                                    taskDetail.ContainerCode = loc.ContainerCode;
                                                    taskDetail.SourceLocation = loc.Code;
                                                    taskDetail.DestinationLocation = locEmpty.Code;
                                                    taskDetail.OderQty = 0;
                                                    taskDetail.ContainerQty = 0;
                                                    taskDetail.HadQty = 0;
                                                    taskDetail.Roadway = td.Roadway;
                                                    taskDetail.Station = null;
                                                    taskDetail.Status = TaskStatus.下达任务;
                                                    taskDetail.Priority = 999;
                                                    taskDetail.MaterialName = "1";
                                                    taskDetail.CreateTime = DateTime.Now;
                                                    _unitWork.Add(taskDetail);
                                                    ApiRequest apiRequest = new ApiRequest("WCS");
                                                WCSResponse<WcsTask> _WCSResponse = apiRequest.Post<WCSResponse<WcsTask>>(JsonHelper.Instance.Serialize(taskDetail), "WcsWebApi/TaskAssign", "任务下发");
                                                //WCSResponse<WcsTask> _WCSResponse = apiRequest.Post<WCSResponse<WcsTask>>(JsonHelper.Instance.Serialize(taskDetail), "IWcsTaskTest/CreateWcsTask", "任务下发");
                                                if (_WCSResponse.Code != 200)
                                                    {
                                                        Response.Code = 300;
                                                        Response.Status = false;
                                                        Response.Message = "移库:" + loc.Code + "下发失败:" + Response.Message;
                                                        td.Error = loc.Code + "未找到移库仓位:" + td.ContainerCode + "不能入库!" + Response.Message;
                                                        _unitWork.Update(td);
                                                        return Response;
                                                    }
                                                }
                                                else if (locEmpty.Status == LocationStatus.空仓位 && locEmpty.ContainerCode == "")
                                                {
                                                    loc = locEmpty;
                                                }
                                            }
                                        }
                                        
                                    }
                                    else if (td.Roadway == 5)
                                    {
                                        List<LocationDistribution> locationDistributions = _unitWork.Find<LocationDistribution>(n => n.RoadWay == td.Roadway).ToList();
                                        if (locationDistributions.Count != 0)
                                        {
                                            Inventory inventory = _unitWork.Find<Inventory>(n => n.ContainerCode == td.ContainerCode && n.NameDescription != "").FirstOrDefault();
                                            if (inventory != null)
                                            {
                                                foreach (LocationDistribution locationDistribution in locationDistributions)
                                                {
                                                    if (inventory.NameDescription.Substring((int)locationDistribution.ContrastStart - 1, (int)locationDistribution.Length) == locationDistribution.ContrastName)
                                                    {
                                                        if (stationRoadway.StationPlace == StationPlace.五巷道北面)
                                                        {
                                                            if (container.Type == ContainerType.木栈板母板_2)
                                                            {
                                                                loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                                   && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2)
                                                                       join Cloca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                                                       on loca.ContiguousCode equals Cloca.Code
                                                                       select loca).OrderBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                            }
                                                            else
                                                            {
                                                                loc = (from loca in _unitWork.Find<Location>(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) && n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                                && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2)
                                                                       join Cloca in _unitWork.Find<Location>(n => n.Status != LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay)
                                                                       on loca.ContiguousCode equals Cloca.Code
                                                                       select loca).OrderBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();

                                                            if (loc == null)
                                                            {
                                                                loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                                && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2).OrderBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                            }
                                                        }
                                                    }
                                                    else if (stationRoadway.StationPlace == StationPlace.六巷道北面)
                                                    {
                                                        if (container.Type == ContainerType.木栈板母板_2)
                                                        {
                                                            loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                               && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2)
                                                                   join Cloca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                                                   on loca.ContiguousCode equals Cloca.Code
                                                                   select loca).OrderBy(n => (n.Code.Contains("EC-") || n.Code.Contains("ED-")) ? 0 : 1).ThenBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                        }
                                                        else
                                                        {
                                                            loc = (from loca in _unitWork.Find<Location>(n => (n.Code.Contains("EC-") || n.Code.Contains("ED-")) && n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                                   && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2)
                                                                   join Cloca in _unitWork.Find<Location>(n => n.Status != LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay)
                                                                   on loca.ContiguousCode equals Cloca.Code
                                                                   select loca).OrderBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                            if (loc == null)
                                                            {
                                                                loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                                && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2).OrderBy(n => (n.Code.Contains("EC-") || n.Code.Contains("ED-")) ? 0 : 1).ThenBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                            }
                                                        }
                                                    }
                                                    else if (stationRoadway.StationPlace == StationPlace.巷道南面)
                                                    {
                                                        if (container.Type == ContainerType.木栈板母板_2)
                                                        {
                                                            loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                               && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2)
                                                                   join Cloca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                                                   on loca.ContiguousCode equals Cloca.Code
                                                                   select loca).OrderBy(b => b.MaxHeight).ThenBy(n => n.DistributionType).ThenBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenByDescending(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                        }
                                                        else
                                                        {
                                                            loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                                   && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2)
                                                                   join Cloca in _unitWork.Find<Location>(n => n.Status != LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay)
                                                                   on loca.ContiguousCode equals Cloca.Code
                                                                   select loca).OrderBy(b => b.MaxHeight).ThenBy(n => n.DistributionType).ThenBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenByDescending(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                            if (loc == null)
                                                            {
                                                                loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.Line == locationDistribution.PointX && n.Row >= locationDistribution.PointY_1 && n.Row <= locationDistribution.PointY_2
                                                                && n.Layer >= locationDistribution.PointZ_1 && n.Layer <= locationDistribution.PointZ_2).OrderBy(b => b.MaxHeight).ThenBy(n => n.DistributionType).ThenBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenByDescending(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                            }
                                                        }
                                                    }

                                                    if (loc != null)
                                                    {
                                                        break;
                                                    }
                                                    else if (loc == null && locationDistribution.Type == DistributionType.静态库位)
                                                    {
                                                        Response.Code = 300;
                                                        Response.Status = false;
                                                        Response.Message = "未找到仓位!";
                                                        td.Error = "未找到仓位(分配仓位为静态)";
                                                        _unitWork.Update(td);
                                                        tran.Commit();
                                                        return Response;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    if (loc == null)
                                    {
                                        if (stationRoadway.StationPlace == StationPlace.五巷道北面)
                                        {
                                            if (container.Type == ContainerType.木栈板母板_2)
                                            {
                                                loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位)
                                                       join Cloca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                                       on loca.ContiguousCode equals Cloca.Code
                                                       select loca).OrderBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                            }
                                            else
                                            {
                                                loc = (from loca in _unitWork.Find<Location>(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) && n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位)
                                                       join Cloca in _unitWork.Find<Location>(n => n.Status != LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay)
                                                       on loca.ContiguousCode equals Cloca.Code
                                                       select loca).OrderBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                if (loc == null)
                                                {
                                                    loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位).OrderBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                }
                                            }
                                        }
                                        else if (stationRoadway.StationPlace == StationPlace.六巷道北面)
                                        {
                                            if (container.Type == ContainerType.木栈板母板_2)
                                            {
                                                loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位)
                                                       join Cloca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                                       on loca.ContiguousCode equals Cloca.Code
                                                       select loca).OrderBy(n => (n.Code.Contains("EC-") || n.Code.Contains("ED-")) ? 0 : 1).ThenBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                            }
                                            else
                                            {
                                                loc = (from loca in _unitWork.Find<Location>(n => (n.Code.Contains("EC-") || n.Code.Contains("ED-")) && n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位)
                                                       join Cloca in _unitWork.Find<Location>(n => n.Status != LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay)
                                                       on loca.ContiguousCode equals Cloca.Code
                                                       select loca).OrderBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                if (loc == null)
                                                {
                                                    loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位).OrderBy(n => (n.Code.Contains("EC-") || n.Code.Contains("ED-")) ? 0 : 1).ThenBy(n => n.DistributionType).ThenBy(b => b.MaxHeight).ThenBy(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                }
                                            }
                                        }
                                        else if (stationRoadway.StationPlace == StationPlace.巷道南面)
                                        {
                                            if (container.Type == ContainerType.木栈板母板_2)
                                            {
                                                loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位)
                                                       join Cloca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                                       on loca.ContiguousCode equals Cloca.Code
                                                       select loca).OrderBy(b => b.MaxHeight).ThenBy(n => n.DistributionType).ThenBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenByDescending(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                            }
                                            else
                                            {
                                                loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位)
                                                       join Cloca in _unitWork.Find<Location>(n => n.Status != LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay)
                                                       on loca.ContiguousCode equals Cloca.Code
                                                       select loca).OrderBy(b => b.MaxHeight).ThenBy(n => n.DistributionType).ThenBy(n => (n.Code.Contains("EA-") || n.Code.Contains("EB-")) ? 0 : 1).ThenByDescending(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                if (loc == null)
                                                {
                                                    loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.DistributionType != LocationDistributionType.被分配库位静态库位).OrderBy(b => b.MaxHeight).ThenBy(n => n.DistributionType).ThenByDescending(a => a.Row).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                                }
                                            }
                                        }
                                    }
                                }
                                else if (td.Roadway == 1)
                                {
                                    var tasks = _unitWork.Find<TaskDetail>(n => n.TaskNo != null).ToList();
                                    //if (_unitWork.GetCount<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "" && n.RowIndex == 2) < 8)
                                    //{
                                    //    loc = null;
                                    //    error = "仓位不足8个!";
                                    //    break;
                                    //}

                                    if (stationRoadway.StationPlace == StationPlace.巷道北面)
                                    {
                                        loc = (from loca in _unitWork.Find<Location>(n => !tasks.Select(a => a.DestinationLocation).Contains(n.ContiguousCode) && !tasks.Select(a => a.SourceLocation).Contains(n.ContiguousCode) && n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                               join cLoca in _unitWork.Find<Location>(n => n.Status != LocationStatus.任务锁定中 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay)
                                               on loca.ContiguousCode equals cLoca.Code
                                               select loca)
                                              .OrderBy(n => n.RowIndex == 1 ? 0 : n.RowIndex).ThenBy(b => b.MaxHeight).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                    }
                                    else if (stationRoadway.StationPlace == StationPlace.巷道南面)
                                    {
                                        loc = (from loca in _unitWork.Find<Location>(n => !tasks.Select(a => a.DestinationLocation).Contains(n.ContiguousCode) && !tasks.Select(a => a.SourceLocation).Contains(n.ContiguousCode) && n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                               join cLoca in _unitWork.Find<Location>(n => n.Status != LocationStatus.任务锁定中 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                                               on loca.ContiguousCode equals cLoca.Code
                                               select loca)
                                               .OrderBy(n => n.RowIndex == 1 ? 0 : n.RowIndex).ThenBy(b => b.MaxHeight).ThenBy(a => a.Layer).ThenByDescending(y => y.Row).FirstOrDefault();
                                    }
                                }
                                else
                                {
                                    if (stationRoadway.StationPlace == StationPlace.巷道北面)
                                    {
                                        loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "").OrderBy(b => b.MaxHeight).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                                    }
                                    else if (stationRoadway.StationPlace == StationPlace.巷道南面)
                                    {
                                        loc = _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= sTKStatusModel.Height && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "").OrderBy(b => (b.MaxHeight)).ThenBy(a => a.Layer).ThenByDescending(y => y.Row).FirstOrDefault();
                                    }
                                }


                                //更新仓位对应的容器,如果回库分配的不是原仓位则更新仓位且锁定
                                if (loc == null)
                                {
                                    Response.Code = 300;
                                    Response.Status = false;
                                    Response.Message = "未找到仓位!";
                                    td.Error = "未找到仓位!" + error;
                                    _unitWork.Update(td);
                                    tran.Commit();
                                    return Response;
                                }
                                else
                                {
                                    if (_unitWork.IsExist<TaskDetail>(a => (a.DestinationLocation == loc.ContiguousCode || a.SourceLocation == loc.ContiguousCode) && a.Roadway == 1))
                                    {
                                        continue;
                                    }
                                    int i = _unitWork.Update<Location>(n => n.Id == loc.Id && n.Version == loc.Version, n => new Location
                                    {
                                        Status = LocationStatus.任务锁定中,
                                        ContainerCode = td.ContainerCode,
                                        UpdateTime = DateTime.Now
                                    });

                                    container = _unitWork.Find<Container>(n => n.Code == td.ContainerCode).FirstOrDefault();
                                    if (container != null && loc != null)
                                    {
                                        if (container.Type == ContainerType.木栈板母板_2)
                                        {
                                            Location Cloc = _unitWork.Find<Location>(u => u.Code == loc.ContiguousCode).FirstOrDefault();
                                            if (Cloc != null)
                                            {
                                                int j = _unitWork.Update<Location>(n => n.Id == Cloc.Id && n.Version == Cloc.Version, n => new Location
                                                {
                                                    ContainerCode = td.ContainerCode,
                                                    Status = LocationStatus.任务锁定中,
                                                    UpdateBy = "wms",
                                                    UpdateTime = DateTime.Now
                                                });
                                                if (j != 1)
                                                {
                                                    Response.Code = 300;
                                                    Response.Status = false;
                                                    Response.Message = "邻仓位更改失败";
                                                    return Response;
                                                }
                                            }
                                        }
                                    }
                                    if (i == 1)
                                    {
                                        break;
                                    }
                                }
                            }
                        }

                        List<Inventory> inventories = _unitWork.Find<Inventory>(n => n.ContainerCode == td.ContainerCode).ToList();
                        if (container == null)
                        {
                            Response.Code = 300;
                            Response.Status = false;
                            Response.Message = "未找到该容器!";
                            td.Error = "未找到该容器!";
                            _unitWork.Update(td);
                            return Response;
                        }
                        else
                        {
                            //更改容器
                            container.Height = sTKStatusModel.Height;
                            container.LocationCode = loc.Code;
                            container.LocationId = loc.Id;
                            _unitWork.Update(container);
                        }

                        //更新同个容器中其它物料对应新的回库仓位
                        if (inventories.Count > 0)
                        {
                            foreach (Inventory inv in inventories)
                            {
                                if (inv.LocationCode != loc.Code)
                                {
                                    inv.LocationCode = loc.Code;
                                    _appi.Update(inv);
                                }
                            }
                        }
                        //更改任务终点
                        td.DestinationLocation = loc.Code;
                        td.Error = "";
                        _unitWork.Update(td);
                        //如果入库起始站台为PP片排版房入库口,那么在请求仓位后就直接清除站台占用
                        Station stationOne = _unitWork.Find<Station>(n => n.Code == td.SourceLocation).FirstOrDefault();
                        if (stationOne.Containercode == td.ContainerCode && td.SourceLocation == "EntranceStationY01")
                        {
                            stationOne.Containercode = "";
                            stationOne.UpdateBy = "wms";
                            stationOne.UpdateTime = DateTime.Now;
                            _unitWork.Update(stationOne);
                        }
                        tran.Commit();
                        Response.Result = td;
                        return Response;
                    }
                    //满入处理
                    else if (sTKStatusModel.Status == 50)
                    {
                        TaskDetail taskDel = _unitWork.Find<TaskDetail>(n => n.TaskNo == sTKStatusModel.TaskNo && n.Status == TaskStatus.下达任务).FirstOrDefault();
                        if (taskDel != null)
                        {
                            Container container = _unitWork.Find<Container>(n => n.Code == taskDel.ContainerCode).FirstOrDefault();
                            Location location = _unitWork.Find<Location>(n => n.ContainerCode == taskDel.ContainerCode).FirstOrDefault();
                            if (location != null && container != null)
                            {
                                List<Inventory> inventories = _unitWork.Find<Inventory>(n => n.ContainerCode == container.Code).ToList();
                                location.ContainerCode = location.Code + "Abnormal";
                                _unitWork.Update<Location>(n => n.Id == location.Id && n.Version == location.Version, n => new Location
                                {
                                    Status = LocationStatus.有货,
                                    ContainerCode = location.ContainerCode,
                                    UpdateTime = DateTime.Now
                                });
                                if (!_unitWork.IsExist<Container>(n => n.Code == location.ContainerCode))
                                {
                                    Container containerAbnormal = new Container();
                                    containerAbnormal.Code = location.ContainerCode;
                                    containerAbnormal.LocationCode = location.Code;
                                    containerAbnormal.IsLock = ContainerLock.任务锁;
                                    containerAbnormal.Status = ContainerStatus.有;
                                    containerAbnormal.Type = container.Type;
                                    containerAbnormal.PrintCount = 0;
                                    containerAbnormal.CreateTime = DateTime.Now;
                                    _unitWork.Add(containerAbnormal);

                                }
                                container.LocationCode = "Abnormal";
                                container.LocationId = 0;
                                _unitWork.Update(container);
                                container.LocationCode = "Abnormal";
                                container.UpdateTime = DateTime.Now;
                                if (inventories.Count > 0)
                                {
                                    foreach (Inventory inv in inventories)
                                    {
                                        inv.LocationCode = "Abnormal";
                                        _appi.Update(inv);
                                    }
                                }
                                taskDel.DestinationLocation = location.Type;
                                taskDel.Error = "满入:" + DateTime.Now;
                                _unitWork.Update(taskDel);
                            }
                        }
                        else
                        {
                            Response.Code = 500;
                            Response.Status = false;
                            Response.Message = "未找到该任务号任务" + sTKStatusModel.TaskNo;
                        }

                        tran.Commit();
                        return Response;
                    }
                    else
                    {
                        Response.Code = 500;
                        Response.Status = false;
                        Response.Message = "不识别的任务状态!";
                    }

                    if (td != null)
                    {
                        List<TaskDetail> taskDetails = _unitWork.Find<TaskDetail>(u => u.ContainerCode == td.ContainerCode && u.Status > TaskStatus.新建任务 && u.Status < TaskStatus.已经完成).ToList();
                        if (sTKStatusModel.Status == 30)   //堆垛机出库完成容器到达站台
                        {
                            foreach (TaskDetail t in taskDetails)
                            {
                                
                                if (t.TaskType == TaskType.容器出库 || t.TaskType == TaskType.空容器出库 || t.TaskType == TaskType.盘点)
                                {
                                    t.Status = TaskStatus.已经完成;   //更新托盘出库任务为已完成
                                    t.UpdateBy = "wms";
                                    t.UpdateTime = DateTime.Now;
                                    _unitWork.Update(t);

                                    //Task pouttask = _unitWork.FindSingle<Task>(u => u.TaskNo == t.TaskNo);
                                    //if (pouttask == null)
                                    //{
                                    //    throw new Exception("任务主表:" + t.TaskNo + "不存在!");
                                    //}
                                    //pouttask.FirstStatus = TaskStatus.已经完成;
                                    //pouttask.LastStatus = TaskStatus.已经完成;
                                    //pouttask.UpdateBy = "wms";
                                    //pouttask.UpdateTime = DateTime.Now;
                                    //_unitWork.Update(pouttask);

                                    ////已完成托盘出库任务迁移至历史任务表
                                    //TaskHistory taskHistory = new TaskHistory();
                                    //pouttask.CopyTo(taskHistory);
                                    //taskHistory.Id = null;
                                    //_unitWork.Add(taskHistory);
                                    //TaskDetailHistory taskDetailHistory = new TaskDetailHistory();
                                    //t.CopyTo(taskDetailHistory);
                                    //taskDetailHistory.Id = null;
                                    //_unitWork.Add(taskDetailHistory);

                                    ////删除已完成的容器出库任务
                                    //_unitWork.Delete(pouttask);
                                    //_unitWork.Delete(t);
                                }
                                else if (t.TaskType == TaskType.站台到站台)
                                {
                                    t.Status = TaskStatus.已经完成;   //更新托盘出库任务为已完成
                                    t.UpdateBy = "wms";
                                    t.UpdateTime = DateTime.Now;
                                    _unitWork.Update(t);

                                    //Task pouttask = _unitWork.FindSingle<Task>(u => u.TaskNo == t.TaskNo);
                                    //if (pouttask == null)
                                    //{
                                    //    throw new Exception("任务主表:" + t.TaskNo + "不存在!");
                                    //}

                                    Station stationSource = _unitWork.Find<Station>(n => n.Code == t.SourceLocation).FirstOrDefault();

                                    if (stationSource != null)
                                    {
                                        if (stationSource.Containercode == td.ContainerCode)
                                        {
                                            stationSource.Containercode = "";
                                            _unitWork.Update(stationSource);
                                        }
                                    }

                                    //pouttask.FirstStatus = TaskStatus.已经完成;
                                    //pouttask.LastStatus = TaskStatus.已经完成;
                                    //pouttask.UpdateBy = "wms";
                                    //pouttask.UpdateTime = DateTime.Now;
                                    //_unitWork.Update(pouttask);

                                    ////已完成托盘出库任务迁移至历史任务表
                                    //TaskHistory taskHistory = new TaskHistory();
                                    //pouttask.CopyTo(taskHistory);
                                    //taskHistory.Id = null;
                                    //_unitWork.Add(taskHistory);
                                    //TaskDetailHistory taskDetailHistory = new TaskDetailHistory();
                                    //t.CopyTo(taskDetailHistory);
                                    //taskDetailHistory.Id = null;
                                    //_unitWork.Add(taskDetailHistory);

                                    ////删除已完成的托盘出库任务
                                    //_unitWork.Delete(pouttask);
                                    //_unitWork.Delete(t);
                                }
                                else if (t.TaskType == TaskType.直接出库)
                                {
                                    t.Status = TaskStatus.已经完成;   //更新托盘出库任务为已完成
                                    t.UpdateBy = "wms";
                                    t.UpdateTime = DateTime.Now;
                                    _unitWork.Update(t);

                                    //Task pouttask = _unitWork.FindSingle<Task>(u => u.TaskNo == t.TaskNo);
                                    //if (pouttask == null)
                                    //{
                                    //    throw new Exception("任务主表:" + t.TaskNo + "不存在!");
                                    //}
                                    //pouttask.FirstStatus = TaskStatus.已经完成;
                                    //pouttask.LastStatus = TaskStatus.已经完成;
                                    //pouttask.UpdateBy = "wms";
                                    //pouttask.UpdateTime = DateTime.Now;
                                    //_unitWork.Update(pouttask);

                                    ////已完成托盘出库任务迁移至历史任务表
                                    //TaskHistory taskHistory = new TaskHistory();
                                    //pouttask.CopyTo(taskHistory);
                                    //taskHistory.Id = null;
                                    //_unitWork.Add(taskHistory);
                                    //TaskDetailHistory taskDetailHistory = new TaskDetailHistory();
                                    //t.CopyTo(taskDetailHistory);
                                    //taskDetailHistory.Id = null;
                                    //_unitWork.Add(taskDetailHistory);

                                    ////删除已完成的托盘出库任务
                                    //_unitWork.Delete(pouttask);
                                    //_unitWork.Delete(t);
                                }
                                else
                                {
                                    if (t.TaskType == TaskType.整盘出库 || t.TaskType == TaskType.分拣出库)//出库任务类型
                                    {
                                        //更新出库明细状态
                                        ShipmentDetail shipmentDetail = _context.Set<ShipmentDetail>().AsQueryable().Where(u => u.SourceCode == t.SourceCode && u.ShipmentCode == t.OrderCode && u.MaterialCode == t.MaterialCode && u.Status == ShipmentHeaderStatus.分配完成).SingleOrDefault();
                                        //  ShipmentDetail shipmentDetail = _unitWork.Find<ShipmentDetail>(u => u.SourceCode == t.SourceCode && u.ShipmentCode == t.OrderCode && u.MaterialCode == t.MaterialCode).FirstOrDefault();
                                        if (shipmentDetail != null)
                                        {
                                            shipmentDetail.Status = ShipmentHeaderStatus.过账;
                                            shipmentDetail.UpdateBy = "wms";
                                            shipmentDetail.UpdateTime = DateTime.Now;
                                            _unitWork.Update(shipmentDetail);
                                            //更新主出库单头尾状态
                                            //  ShipmentHeader shipmentHeader = _unitWork.Find<ShipmentHeader>(u => u.Code == t.OrderCode).FirstOrDefault();
                                            ShipmentHeader shipmentHeader = _context.Set<ShipmentHeader>().AsQueryable().Where(u => u.Code == t.OrderCode).SingleOrDefault();
                                            ShipmentDetail shipdt = _unitWork.Find<ShipmentDetail>(u => u.ShipmentCode == t.OrderCode).OrderBy(a => a.Status).FirstOrDefault();
                                            if (shipmentHeader.FirstStatus < shipmentDetail.Status)
                                            {
                                                shipmentHeader.FirstStatus = shipmentDetail.Status;
                                            }
                                            if (shipmentHeader.LastStatus < shipdt.Status)
                                            {
                                                shipmentHeader.LastStatus = shipdt.Status;
                                            }
                                            shipmentHeader.UpdateBy = "wms";
                                            shipmentHeader.UpdateTime = DateTime.Now;
                                            _unitWork.Update(shipmentHeader);

                                            //已完成的出库单据迁移至历史出库单据,暂以过账状态,后期与ERP对接后以回传状态
                                            if (shipmentHeader.LastStatus == ShipmentHeaderStatus.过账)
                                            {
                                                ShipmentHeaderHistory shipmentHeaderHistory = new ShipmentHeaderHistory();
                                                shipmentHeader.CopyTo(shipmentHeaderHistory);
                                                shipmentHeaderHistory.Id = null;
                                                _unitWork.Add(shipmentHeaderHistory);

                                                List<ShipmentDetail> shipdtls = _context.Set<ShipmentDetail>().AsQueryable().Where(u => u.ShipmentCode == shipmentHeader.Code).ToList();
                                                //  List<ShipmentDetail> shipdtls = _unitWork.Find<ShipmentDetail>(u => u.ShipmentCode == shipmentHeader.Code).ToList();
                                                foreach (ShipmentDetail sd in shipdtls)
                                                {
                                                    ShipmentDetailHistory shipmentDetailHistory = new ShipmentDetailHistory();
                                                    sd.CopyTo(shipmentDetailHistory);
                                                    shipmentDetailHistory.Id = null;
                                                    shipmentDetailHistory.ShipmentId = shipmentHeaderHistory.Id;
                                                    _unitWork.Add(shipmentDetailHistory);

                                                    _unitWork.Delete(sd);
                                                }
                                                _unitWork.Delete(shipmentHeader);
                                            }
                                        }
                                    }
                                    //t.Status = TaskStatus.已经到站台;  //更新任务状态为已到达站台
                                    //t.UpdateBy = "wms";
                                    //t.UpdateTime = DateTime.Now;
                                    //_unitWork.Update(t);

                                    ////更新主任务头尾状态
                                    //Task task = _context.Set<Task>().AsQueryable().Where(u => u.TaskNo == t.TaskNo).SingleOrDefault();
                                    //if (task == null)
                                    //{
                                    //    throw new Exception("任务主表:" + t.TaskNo + "不存在!");
                                    //}
                                    //// Task task = _unitWork.FindSingle<Task>(u => u.TaskNo == t.TaskNo);
                                    //TaskDetail tdel = _unitWork.Find<TaskDetail>(u => u.TaskNo == t.TaskNo).OrderBy(a => a.Status).FirstOrDefault();//同一个任务号下面最小的任务状态,包含其它容器的任务,用于更新主任务的尾状态
                                    //if (tdel == null)
                                    //{
                                    //    throw new Exception("任务子表:" + t.TaskNo + "不存在!");
                                    //}
                                    //if (task.FirstStatus < t.Status)
                                    //{
                                    //    task.FirstStatus = t.Status;
                                    //}
                                    //if (task.LastStatus < tdel.Status)
                                    //{
                                    //    task.LastStatus = tdel.Status;
                                    //}
                                    //task.UpdateBy = "wms";
                                    //task.UpdateTime = DateTime.Now;
                                    //_unitWork.Update(task);
                                }

                                t.Status = TaskStatus.已经完成;  //更新任务明细状态为已完成
                                t.UpdateBy = "wms";
                                t.UpdateTime = DateTime.Now;
                                _unitWork.Update(t);
                                //更新主任务头尾状态
                                Task task = _context.Set<Task>().AsQueryable().Where(u => u.TaskNo == t.TaskNo).SingleOrDefault();
                                if (task == null)
                                {
                                    throw new Exception("任务主表:" + t.TaskNo + "不存在!");
                                }
                                // Task task = _unitWork.FindSingle<Task>(u => u.TaskNo == t.TaskNo);
                                TaskDetail tdel = _unitWork.Find<TaskDetail>(u => u.TaskNo == t.TaskNo).OrderBy(a => a.Status).FirstOrDefault();//同一个任务号下面最小的任务状态,包含其它容器的任务,用于更新主任务的尾状态
                                if (tdel == null)
                                {
                                    throw new Exception("任务子表:" + t.TaskNo + "不存在!");
                                }
                                if (task.FirstStatus < t.Status)
                                {
                                    task.FirstStatus = t.Status;
                                }
                                if (task.LastStatus < tdel.Status)
                                {
                                    task.LastStatus = tdel.Status;
                                }
                                task.UpdateBy = "wms";
                                task.UpdateTime = DateTime.Now;
                                _unitWork.Update(task);


                                //已完成的单据任务迁移至历史任务表
                                if (task.LastStatus == TaskStatus.已经完成)
                                {
                                    TaskHistory taskhis = new TaskHistory();
                                    task.CopyTo(taskhis);
                                    taskhis.Id = null;
                                    _unitWork.Add(taskhis);

                                    List<TaskDetail> taskdtls = _context.Set<TaskDetail>().AsQueryable().Where(u => u.TaskNo == task.TaskNo).ToList();
                                    foreach (TaskDetail tdl in taskdtls)
                                    {
                                        TaskDetailHistory taskdthis = new TaskDetailHistory();
                                        tdl.CopyTo(taskdthis);
                                        taskdthis.Id = null;
                                        _unitWork.Add(taskdthis);

                                        _unitWork.Delete(tdl);
                                    }
                                    _unitWork.Delete(task);
                                }
                            }

                            if (td.TaskType == TaskType.直接出库 || td.TaskType == TaskType.空容器出库 || td.TaskType == TaskType.容器出库 || td.TaskType == TaskType.站台到站台 || td.TaskType == TaskType.盘点)
                            {
                                //托盘出库完成,容器占用站台
                                Station st = _unitWork.Find<Station>(u => u.Code == td.Station).FirstOrDefault();
                                if (st == null)
                                {
                                    throw new Exception("站台:" + td.Station + "不存在!");
                                }
                                else if (st.IsOccupy == 0 && td.IsOccupy != 1)
                                {
                                    st.Containercode = "";
                                    //if (cont != null && td.TaskType != TaskType.盘点)
                                    //{
                                    //    _appc.DeleteByTracking(cont);
                                    //}
                                }
                                else if (st.IsOccupy == 1 && td.IsOccupy != 0)
                                {
                                    st.Containercode = td.ContainerCode;
                                }

                                Container cont = _unitWork.Find<Container>(n => n.Code == td.ContainerCode && n.Code != "woodPallet").FirstOrDefault();
                                //成品库入库空板补给成功将板号给对应入库任务
                                TaskDetail detail = _unitWork.Find<TaskDetail>(n => n.TaskNo == td.OrderCode).FirstOrDefault();
                                if (td.TaskType == TaskType.空容器出库 && td.DestinationLocation == "OutStationE02")
                                {
                                    if (detail != null)
                                    {
                                        cont.Status = ContainerStatus.有;
                                        cont.LocationCode = st.Code;
                                        _unitWork.Update(cont);
                                        detail.ContainerCode = td.ContainerCode;
                                        _unitWork.Update(detail);
                                    }

                                    StoreStation store = _unitWork.Find<StoreStation>(n => n.ContainerCode == td.ContainerCode).FirstOrDefault();
                                    if (store != null)
                                    {
                                        store.Status = StoreStationStatus.到达站台;
                                        _unitWork.Update(store);
                                    }
                                }
                                else if (cont != null && td.TaskType != TaskType.盘点 && st.Type != StationType.暂存区站台)
                                {
                                    cont.Status = "empty";
                                    cont.Height = 0;
                                    cont.LocationCode = st.Code;
                                    _unitWork.Update(cont);
                                }

                                st.UpdateBy = "wms";
                                st.UpdateTime = DateTime.Now;
                                _unitWork.Update(st);
                                List<Inventory> inventories = _unitWork.Find<Inventory>(n => n.ContainerCode == td.ContainerCode && n.ContainerCode != "woodPallet").ToList();
                                if (td.TaskType == TaskType.空容器出库 && td.DestinationLocation == "OutStationE02")
                                {
                                    inventories = _unitWork.Find<Inventory>(n => n.ContainerCode == detail.SourceLocation).ToList();
                                    foreach (Inventory inv in inventories)
                                    {
                                        inv.ContainerCode = td.ContainerCode;
                                        inv.LocationCode = st.Code;
                                        _appi.UpdateByTracking(inv);
                                    }
                                }
                                else if ((st.Type == StationType.暂存区站台 || st.Type == StationType.木栈板补给站台w_1 || st.Type == StationType.木栈板补给站台w_2) || td.TaskType == TaskType.盘点)
                                {
                                    foreach (Inventory inv in inventories)
                                    {
                                        if (st.Type == StationType.暂存区站台)
                                        {
                                            inv.TaskStatus = InventoryTaskType.无任务;
                                        }
                                        inv.LocationCode = st.Code;
                                        _appi.UpdateByTracking(inv);
                                    }
                                }
                                else
                                {
                                    foreach (Inventory inv in inventories)
                                    {
                                        _unitWork.Delete(inv);
                                        InventoryTransaction inventoryTransaction = new InventoryTransaction
                                        {
                                            Type = TransactionType.出库,
                                            SourceCode = td.OrderCode,
                                            ContainerCode = inv.ContainerCode,
                                            MaterialCode = inv.MaterialCode,
                                            Batch = inv.Batch,
                                            Lot = inv.Lot,
                                            Qty = inv.Qty,
                                            Supplier = inv.Supplier,
                                            ResidualWeight = inv.ResidualWeight,
                                            Retreat = inv.Retreat,
                                            Specification = inv.Specification,
                                            NameDescription = inv.NameDescription,
                                            Unit = inv.Unit,
                                            Size = inv.Size,
                                            NumberofSheets = inv.NumberofSheets,
                                            Groupnum = inv.Groupnum,
                                            OldBatch = inv.OldBatch,
                                            Combo = inv.Combo,
                                            Status = inv.Status,
                                            LocationCode = td.SourceLocation,
                                            StackingNumber = inv.StackingNumber,
                                            CreateTime = inv.CreateTime,
                                            UpdateTime = DateTime.Now
                                        };
                                        _unitWork.Add(inventoryTransaction);
                                    }
                                }

                                if (td.TaskType != TaskType.盘点)
                                {
                                    //托盘出库完成,解锁并释放仓位
                                    Location loc = _unitWork.Find<Location>(u => u.Code == td.SourceLocation).FirstOrDefault();
                                    if (loc != null)
                                    {
                                        _unitWork.Update<Location>(n => n.Id == loc.Id && n.Version == loc.Version, n => new Location
                                        {
                                            ContainerCode = "",
                                            Status = "empty",
                                            UpdateBy = "wms",
                                            UpdateTime = DateTime.Now
                                        });
                                    }

                                    //成品库大板仓位解锁
                                    if (cont != null && loc != null)
                                    {
                                        if (cont.Type == ContainerType.木栈板母板_2)
                                        {
                                            Location Cloc = _unitWork.Find<Location>(u => u.Code == loc.ContiguousCode).FirstOrDefault();
                                            if (Cloc != null)
                                            {
                                                _unitWork.Update<Location>(n => n.Id == Cloc.Id && n.Version == Cloc.Version, n => new Location
                                                {
                                                    ContainerCode = "",
                                                    Status = "empty",
                                                    UpdateBy = "wms",
                                                    UpdateTime = DateTime.Now
                                                });
                                            }
                                        }
                                    }
                                }
                            }

                            //   Response.Result = td;

                            //空板补给
                            if (td.TaskType == TaskType.空容器出库)
                            {
                                StoreStation storeStation = _unitWork.Find<StoreStation>(n => n.ContainerCode == td.ContainerCode && n.Status == StoreStationStatus.任务中).FirstOrDefault();
                                if (storeStation != null)
                                {
                                    storeStation.Status = StoreStationStatus.到达站台;
                                    storeStation.CreateTime = DateTime.Now;
                                    _unitWork.Update(storeStation);
                                }
                                TaskDetail tdPP = _unitWork.Find<TaskDetail>(n => n.TaskType == TaskType.站台到站台 && n.Status == TaskStatus.新建任务 && n.SourceLocation == td.Station && n.ContainerCode == td.ContainerCode).FirstOrDefault();
                                if (tdPP != null)
                                {
                                    tdPP.Status = TaskStatus.待下发任务;
                                    _unitWork.Update(tdPP);
                                }
                            }

                            if (td.TaskType == TaskType.容器出库 && (td.DestinationLocation == "InStationE07" || td.DestinationLocation == "InStationE08"))
                            {
                                TaskDetail tdPP = _unitWork.Find<TaskDetail>(n => n.TaskType == TaskType.站台到站台 && n.Status == TaskStatus.新建任务 && n.SourceLocation == td.Station && n.ContainerCode == td.ContainerCode).FirstOrDefault();
                                if (tdPP != null)
                                {
                                    tdPP.Status = TaskStatus.待下发任务;
                                    _unitWork.Update(tdPP);
                                }
                            }

                            ////成品库木栈板补给逻辑
                            //if (td.Station == "InStationE07" || td.Station == "InStationE08")
                            //{
                            //    TaskDetail detail = null;
                            //    string conCode = "";
                            //    if (td.TaskType == TaskType.空容器出库)
                            //    {
                            //        detail = _unitWork.Find<TaskDetail>(n => n.Status == TaskStatus.新建任务 && n.TaskType == TaskType.容器回库 && n.TaskNo == td.TaskNo).OrderBy(n => n.Id).FirstOrDefault();
                            //        conCode = td.ContainerCode;
                            //    }
                            //    else if (td.TaskType == TaskType.容器出库)
                            //    {
                            //        detail = _unitWork.Find<TaskDetail>(n => n.Status == TaskStatus.新建任务 && n.TaskType == TaskType.空容器入库 && n.TaskNo == td.TaskNo).OrderBy(n => n.Id).FirstOrDefault();
                            //        conCode = "woodPallet";
                            //    }

                            //    if (detail != null)
                            //    {
                            //        StationRoadway stationRoadway = _unitWork.Find<StationRoadway>(n => n.StationCode == detail.Station).FirstOrDefault();
                            //        Location loc = new Location();
                            //        //成品库找仓位逻辑
                            //        while (true)
                            //        {
                            //            loc = (from loca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                            //                   join Cloca in _unitWork.Find<Location>(n => n.Status == LocationStatus.空仓位 && n.IsStop == false && n.MaxHeight >= 0 && n.Roadway == stationRoadway.RoadWay && n.ContainerCode == "")
                            //                   on loca.ContiguousCode equals Cloca.Code
                            //                   select loca).OrderBy(b => b.MaxHeight).ThenBy(a => a.Layer).ThenBy(y => y.Row).FirstOrDefault();
                            //            //更新仓位对应的容器,如果回库分配的不是原仓位则更新仓位且锁定
                            //            if (loc == null)
                            //            {
                            //                detail.Error = "库内无空仓位";
                            //                _unitWork.Update(detail);
                            //                break;
                            //            }
                            //            else
                            //            {
                            //                int i = _unitWork.Update<Location>(n => n.Id == loc.Id && n.Version == loc.Version, n => new Location
                            //                {
                            //                    Status = LocationStatus.任务锁定中,
                            //                    ContainerCode = td.ContainerCode,
                            //                    UpdateTime = DateTime.Now
                            //                });

                            //                Container container = _unitWork.Find<Container>(n => n.Code == td.ContainerCode).FirstOrDefault();
                            //                if (container != null && loc != null)
                            //                {
                            //                    if (container.Type == ContainerType.木栈板母板_2)
                            //                    {
                            //                        Location Cloc = _unitWork.Find<Location>(u => u.Code == loc.ContiguousCode).FirstOrDefault();
                            //                        if (Cloc != null)
                            //                        {
                            //                            _unitWork.Update<Location>(n => n.Id == Cloc.Id && n.Version == Cloc.Version, n => new Location
                            //                            {
                            //                                ContainerCode = td.ContainerCode,
                            //                                Status = LocationStatus.任务锁定中,
                            //                                UpdateBy = "wms",
                            //                                UpdateTime = DateTime.Now
                            //                            });
                            //                        }
                            //                    }
                            //                }

                            //                if (i == 1)
                            //                {
                            //                    break;
                            //                }
                            //            }
                            //        }

                            //        if (loc != null)
                            //        {
                            //            Container UpContainer = _unitWork.Find<Container>(n => n.Code == td.ContainerCode).FirstOrDefault();
                            //            if (td.TaskType == TaskType.空容器出库)
                            //            {
                            //                UpContainer.LocationCode = loc.Code;
                            //                UpContainer.Status = ContainerStatus.有;
                            //            }
                            //            _appc.UpdateByTracking(UpContainer);
                            //            List<Inventory> inventories = _unitWork.Find<Inventory>(n => (n.ContainerCode == td.ContainerCode) || (n.ContainerCode == ContainerStatus.空 && n.LocationCode == td.Station)).ToList();
                            //            //更新同个容器中其它物料对应新的回库仓位
                            //            if (inventories.Count > 0)
                            //            {
                            //                foreach (Inventory inv in inventories)
                            //                {
                            //                    if (inv.LocationCode != loc.Code)
                            //                    {
                            //                        if (td.TaskType == TaskType.空容器出库)
                            //                        {
                            //                            inv.LocationCode = loc.Code;
                            //                        }
                            //                        else if (td.TaskType == TaskType.容器出库)
                            //                        {
                            //                            inv.LocationCode = td.DestinationLocation;
                            //                        }

                            //                        if (td.TaskType == TaskType.空容器出库)
                            //                        {
                            //                            inv.ContainerCode = conCode;
                            //                        }
                            //                        else if (td.TaskType == TaskType.容器出库)
                            //                        {
                            //                            inv.ContainerCode = conCode;
                            //                        }
                            //                        inv.SourceCode = detail.OrderCode;
                            //                        _appi.UpdateByTracking(inv);
                            //                    }
                            //                }
                            //            }

                            //            detail.DestinationLocation = loc.Code;
                            //            detail.Status = TaskStatus.待下发任务;
                            //            _unitWork.Update(detail);
                            //        }
                            //    }
                            //}
                        }
                        else if (sTKStatusModel.Status == 40)  //堆垛机入库完成容器到达仓位
                        {
                            string locationStatus = ContainerStatus.有;
                            Container container = _unitWork.Find<Container>(u => u.Code == td.ContainerCode).FirstOrDefault();
                            foreach (TaskDetail t in taskDetails)
                            {
                                if (t.TaskType == TaskType.容器回库)
                                {
                                    t.Status = TaskStatus.已经完成;   //更新托盘入库任务为已完成
                                    t.UpdateBy = "wms";
                                    t.UpdateTime = DateTime.Now;
                                    _unitWork.Update(t);

                                    Task pintask = _unitWork.FindSingle<Task>(u => u.TaskNo == t.TaskNo);
                                    if (pintask == null)
                                    {
                                        throw new Exception("任务主表:" + t.TaskNo + "不存在!");
                                    }
                                    pintask.FirstStatus = TaskStatus.已经完成;
                                    pintask.LastStatus = TaskStatus.已经完成;
                                    pintask.UpdateBy = "wms";
                                    pintask.UpdateTime = DateTime.Now;
                                    _unitWork.Update(pintask);

                                    //更新库存交易仓位
                                    List<InventoryTransaction> inventoryTransactions = _unitWork.Find<InventoryTransaction>(u => u.ContainerCode == t.ContainerCode && u.SourceCode == t.TaskNo).ToList();
                                    foreach (InventoryTransaction i in inventoryTransactions)
                                    {
                                        i.LocationCode = t.DestinationLocation;
                                        _unitWork.Update(i);
                                    }

                                    //已完成的托盘入库任务迁移至历史任务表
                                    TaskHistory taskHistory = new TaskHistory();
                                    pintask.CopyTo(taskHistory);
                                    taskHistory.Id = null;
                                    _unitWork.Add(taskHistory);
                                    TaskDetailHistory taskDetailHistory = new TaskDetailHistory();
                                    t.CopyTo(taskDetailHistory);
                                    taskDetailHistory.Id = null;
                                    _unitWork.Add(taskDetailHistory);

                                    //删除已完成的托盘入库任务
                                    _unitWork.Delete(pintask);
                                    _unitWork.Delete(t);
                                }
                                else
                                {
                                    t.Status = TaskStatus.已经完成;  //更新任务明细状态为已完成
                                    t.UpdateBy = "wms";
                                    t.UpdateTime = DateTime.Now;
                                    _unitWork.Update(t);
                                    //更新主任务头尾状态
                                    Task task = _context.Set<Task>().AsQueryable().Where(u => u.TaskNo == t.TaskNo).SingleOrDefault();
                                    if (task == null)
                                    {
                                        throw new Exception("任务主表:" + t.TaskNo + "不存在!");
                                    }
                                    // Task task = _unitWork.FindSingle<Task>(u => u.TaskNo == t.TaskNo);
                                    TaskDetail tdel = _unitWork.Find<TaskDetail>(u => u.TaskNo == t.TaskNo).OrderBy(a => a.Status).FirstOrDefault();//同一个任务号下面最小的任务状态,包含其它容器的任务,用于更新主任务的尾状态
                                    if (tdel == null)
                                    {
                                        throw new Exception("任务子表:" + t.TaskNo + "不存在!");
                                    }
                                    if (task.FirstStatus < t.Status)
                                    {
                                        task.FirstStatus = t.Status;
                                    }
                                    if (task.LastStatus < tdel.Status)
                                    {
                                        task.LastStatus = tdel.Status;
                                    }
                                    task.UpdateBy = "wms";
                                    task.UpdateTime = DateTime.Now;
                                    _unitWork.Update(task);

                                    //已完成的单据任务迁移至历史任务表
                                    if (task.LastStatus == TaskStatus.已经完成)
                                    {
                                        TaskHistory taskhis = new TaskHistory();
                                        task.CopyTo(taskhis);
                                        taskhis.Id = null;
                                        _unitWork.Add(taskhis);

                                        List<TaskDetail> taskdtls = _context.Set<TaskDetail>().AsQueryable().Where(u => u.TaskNo == task.TaskNo).ToList();
                                        foreach (TaskDetail tdl in taskdtls)
                                        {
                                            TaskDetailHistory taskdthis = new TaskDetailHistory();
                                            tdl.CopyTo(taskdthis);
                                            taskdthis.Id = null;
                                            _unitWork.Add(taskdthis);

                                            _unitWork.Delete(tdl);
                                        }
                                        _unitWork.Delete(task);
                                    }

                                    if (t.TaskType == TaskType.整盘入库 || t.TaskType == TaskType.补充入库)//入库任务类型
                                    {
                                        //更新入库明细单据状态
                                        ReceiptDetail receiptDetail = _unitWork.Find<ReceiptDetail>(u => u.SourceCode == t.SourceCode && u.ReceiptCode == t.OrderCode && u.MaterialCode == t.MaterialCode && t.OderQty == t.HadQty).FirstOrDefault();
                                        if (receiptDetail != null)
                                        {
                                            receiptDetail.Status = ReceiptHeaderStatus.过账;
                                            receiptDetail.UpdateBy = "wms";
                                            receiptDetail.UpdateTime = DateTime.Now;
                                            _apprd.UpdateByTracking(receiptDetail);
                                            //更新入库主单据头尾状态
                                            // ReceiptHeader receiptHeader = _unitWork.Find<ReceiptHeader>(u => u.Code == t.OrderCode).FirstOrDefault();
                                            ReceiptHeader receiptHeader = _context.Set<ReceiptHeader>().AsQueryable().Where(u => u.Code == t.OrderCode).SingleOrDefault();
                                            ReceiptDetail recepdt = _unitWork.Find<ReceiptDetail>(u => u.ReceiptCode == t.OrderCode).OrderBy(a => a.Status).FirstOrDefault();
                                            if (receiptHeader.FirstStatus < receiptDetail.Status)
                                            {
                                                receiptHeader.FirstStatus = receiptDetail.Status;
                                            }
                                            if (receiptHeader.LastStatus < recepdt.Status)
                                            {
                                                receiptHeader.LastStatus = recepdt.Status;
                                            }
                                            receiptHeader.UpdateBy = "wms";
                                            receiptHeader.UpdateTime = DateTime.Now;
                                            _apprh.UpdateByTracking(receiptHeader);
                                            //已完成的入库单据迁移至历史入库单据,暂以过账状态,后期与ERP对接后以回传状态
                                            if (receiptHeader.LastStatus == ReceiptHeaderStatus.过账)
                                            {
                                                ReceiptHeaderHistory receiptHeaderHistory = new ReceiptHeaderHistory();
                                                receiptHeader.CopyTo(receiptHeaderHistory);
                                                receiptHeaderHistory.Id = null;
                                                _unitWork.Add(receiptHeaderHistory);

                                                List<ReceiptDetail> recepdtls = _context.Set<ReceiptDetail>().AsQueryable().Where(u => u.ReceiptCode == receiptHeader.Code).ToList();
                                                // List<ReceiptDetail> recepdtls = _unitWork.Find<ReceiptDetail>(u => u.ReceiptCode == receiptHeader.Code).ToList();
                                                foreach (ReceiptDetail rd in recepdtls)
                                                {
                                                    ReceiptDetailHistory receiptDetailHistory = new ReceiptDetailHistory();
                                                    rd.CopyTo(receiptDetailHistory);
                                                    receiptDetailHistory.Id = null;
                                                    receiptDetailHistory.ReceiptId = receiptHeaderHistory.Id;
                                                    _unitWork.Add(receiptDetailHistory);

                                                    _unitWork.Delete(rd);
                                                }
                                                _unitWork.Delete(receiptHeader);
                                            }
                                        }
                                    }
                                    else if (t.TaskType == TaskType.空容器入库) //空容器入库任务类型
                                    {
                                        locationStatus = LocationStatus.空容器;
                                    }
                                    else if (t.TaskType == TaskType.移库)
                                    {
                                        if (container.Status == ContainerStatus.空)
                                        {
                                            locationStatus = LocationStatus.空容器;
                                        }
                                    }
                                    else if (t.TaskType == TaskType.出库查看)
                                    {

                                    }
                                    //else if (t.TaskType == TaskType.盘点)
                                    //{
                                    //    Inventory inventory = _unitWork.Find<Inventory>(n => n.ContainerCode == t.ContainerCode).FirstOrDefault();
                                    //    List<Inventory> invs = _unitWork.Find<Inventory>(n => n.ContainerCode == inventory.ContainerCode).ToList();
                                    //    foreach (Inventory inv in invs)
                                    //    {
                                    //        inv.TaskStatus = "cyclecountLock";
                                    //        _appi.UpdateByTracking(inv);
                                    //    }
                                    //    CyclecountHeader cycher = _unitWork.Find<CyclecountHeader>(n => n.Code == t.OrderCode).FirstOrDefault();
                                    //    CyclecountDetail cycdel = _unitWork.Find<CyclecountDetail>(n => n.Status == ReceiptHeaderStatus.过账 && n.MaterialCode == t.MaterialCode && n.ContainerCode == t.ContainerCode && n.Code == t.OrderCode).FirstOrDefault();
                                    //    CyclecountDetail cycdelEnd = _unitWork.Find<CyclecountDetail>(n => n.Code == t.OrderCode && n.Id != cycdel.Id).OrderBy(n => n.Status).FirstOrDefault();
                                    //    if (cycdel != null)
                                    //    {
                                    //        cycdel.Status = ReceiptHeaderStatus.回传;
                                    //        _unitWork.Update(cycdel);
                                    //        if (cycdelEnd.Status >= cycdel.Status)
                                    //        {
                                    //            cycher.Status = (short)cycdel.Status;
                                    //            _unitWork.Update(cycher);
                                    //        }
                                    //        if (t.OderQty < t.HadQty)
                                    //        {
                                    //            //erp传数据
                                    //        }
                                    //        else if (t.OderQty > t.HadQty)
                                    //        {
                                    //            //erp传数据
                                    //        }
                                    //    }
                                    //}
                                    else
                                    {
                                        throw new Exception("未知任务类型:" + t.TaskType);
                                    }
                                }
                            }

                            //清除该托盘占用的站台
                            Station s = _unitWork.Find<Station>(n => n.Code == td.SourceLocation && n.Containercode == td.ContainerCode && (td.TaskType == TaskType.容器回库 || td.TaskType == TaskType.空容器入库)).FirstOrDefault();
                            if (s != null)
                            {
                                s.Containercode = "";
                                _unitWork.Update(s);
                            }
                            //托盘入库完成,解锁并释放仓位
                            Location loc = _unitWork.Find<Location>(u => u.Code == td.DestinationLocation).FirstOrDefault();
                            if (loc == null)
                            {
                                throw new Exception("仓位:" + td.DestinationLocation + "不存在!");
                            }

                            int iLoc = _unitWork.Update<Location>(n => n.Id == loc.Id && n.Version == loc.Version, n => new Location
                            {
                                ContainerCode = td.ContainerCode,
                                Status = locationStatus,
                                UpdateBy = "wms",
                                UpdateTime = DateTime.Now
                            });

                            //成品库大板仓位上锁
                            if (container != null && loc != null)
                            {
                                if (container.Type == ContainerType.木栈板母板_2)
                                {
                                    Location Cloc = _unitWork.Find<Location>(u => u.Code == loc.ContiguousCode).FirstOrDefault();
                                    if (Cloc != null)
                                    {
                                        _unitWork.Update<Location>(n => n.Id == Cloc.Id && n.Version == Cloc.Version, n => new Location
                                        {
                                            ContainerCode = td.ContainerCode,
                                            Status = locationStatus,
                                            UpdateBy = "wms",
                                            UpdateTime = DateTime.Now
                                        });
                                    }
                                }
                            }

                            List<Inventory> inventories = _unitWork.Find<Inventory>(n => n.ContainerCode == td.ContainerCode && n.Status != "cyclecountLock").ToList();
                            //更新同个容器中其它物料对应新的回库仓位
                            if (inventories.Count > 0)
                            {
                                foreach (Inventory inv in inventories)
                                {
                                    if (loc.Roadway == 1)
                                    {
                                        inv.WarehouseType = "YCL_WareCell";
                                    }
                                    if (loc.Roadway == 2)
                                    {
                                        inv.WarehouseType = "PPJ_WareCell";
                                    }
                                    else if (loc.Roadway == 3)
                                    {
                                        inv.WarehouseType = "PPP_WareCell";
                                    }
                                    else if (loc.Roadway == 4)
                                    {
                                        inv.WarehouseType = "TB_WareCell";
                                    }
                                    else if (loc.Roadway == 5)
                                    {
                                        inv.WarehouseType = "CP_WareCell";
                                    }

                                    if (inv.LocationCode != loc.Code)
                                    {
                                        inv.LocationCode = loc.Code;
                                    }

                                    if (inv.TaskStatus == InventoryTaskType.任务锁定中)
                                    {
                                        inv.TaskStatus = InventoryTaskType.无任务;
                                    }
                                    _appi.Update(inv);
                                }
                            }
                            //托盘入库完成,解锁并释放容器
                            if (container == null)
                            {
                                throw new Exception("容器:" + td.ContainerCode + "不存在!");
                            }
                            container.LocationCode = td.DestinationLocation;
                            container.IsLock = ContainerLock.未锁;
                            container.UpdateBy = "wms";
                            container.UpdateTime = DateTime.Now;
                            _unitWork.Update(container);

                            //成品库木栈板补给逻辑
                            if (td.Station == "InStationE07" || td.Station == "InStationE08")
                            {
                                TaskDetail detail = null;
                                if (td.TaskType == TaskType.空容器入库)
                                {
                                    detail = _unitWork.Find<TaskDetail>(n => n.Status == TaskStatus.新建任务 && n.TaskType == TaskType.站台到站台 && n.TaskNo == td.TaskNo).OrderBy(n => n.Id).FirstOrDefault();
                                    if (detail != null)
                                    {
                                        detail.Status = TaskStatus.待下发任务;
                                        _unitWork.Update(detail);
                                    }
                                }
                            }

                        }
                        else
                        {
                            Response.Code = 500;
                            Response.Status = false;
                            Response.Message = "不识别的任务状态!";
                        }
                    }
                    else
                    {
                        Response.Code = 500;
                        Response.Status = false;
                        Response.Message = "获取任务号错误,未找到此容器的任务!";
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Response.Code = 500;
                    Response.Status = false;
                    Response.Message = ex.Message;
                }

                return Response;
            }
        }
    }
}