private void buttonDetail_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         AST_PalletTask astPalletTask = (AST_PalletTask)this.dataGrid.SelectedItem;
         if (astPalletTask != null)
         {
             PalletTaskItemsWindow dialog = new PalletTaskItemsWindow(astPalletTask.Id);
             dialog.ShowDialog();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                using (GeelyPtlEntities dbContext = new GeelyPtlEntities())
                {
                    AST_PalletTask astPalletTask = dbContext.AST_PalletTasks
                                                   .First(lt => lt.Id == this.astPalletTaskId);
                    List <AST_PalletTaskItem> astPalletTaskItems = dbContext.AST_PalletTaskItems
                                                                   .Include(lti => lti.CFG_WorkStation)
                                                                   .Where(lti => lti.AST_PalletTaskId == this.astPalletTaskId)
                                                                   .OrderBy(lti => lti.FromPalletPosition)
                                                                   .ToList();

                    this.Title = this.Title + ":" + astPalletTask.CFG_Pallet.Code;
                    this.dataGrid.ItemsSource = astPalletTaskItems;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
            }
        }
        /// <summary>
        /// 按托合并原始分拣任务。
        /// </summary>
        /// <param name="astPalletArrived">从接口解析还未持久化的托盘抵达记录。</param>
        /// <param name="dbContext">数据上下文。</param>
        public static void Generate(AST_PalletArrived astPalletArrived, GeelyPtlEntities dbContext)
        {
            List <AST_LesTask> astLesTasks = dbContext.AST_LesTasks
                                             .Where(lt => lt.BatchCode == astPalletArrived.BatchCode &&
                                                    lt.CFG_PalletId == astPalletArrived.CFG_PalletId &&
                                                    lt.CFG_ChannelId == astPalletArrived.CFG_ChannelId &&
                                                    astPalletArrived.PickBillIds.Contains(lt.BillCode) &&
                                                    !lt.TaskGenerated)
                                             .ToList();

            if (astLesTasks.Count > 0)
            {
                AST_LesTask mainAstLesTask = astLesTasks.First();

                AST_PalletTask astPalletTask = new AST_PalletTask();
                astPalletTask.CFG_PalletId  = astPalletArrived.CFG_PalletId;
                astPalletTask.BatchCode     = mainAstLesTask.BatchCode;
                astPalletTask.PickBillIds   = astPalletArrived.PickBillIds;
                astPalletTask.ProjectCode   = astPalletArrived.ProjectCode;
                astPalletTask.WbsId         = mainAstLesTask.WbsId;
                astPalletTask.ProjectStep   = astPalletArrived.ProjectStep;
                astPalletTask.CFG_ChannelId = astPalletArrived.CFG_ChannelId;
                astPalletTask.PickStatus    = PickStatus.New;
                astPalletTask.CreateTime    = DateTime.Now;

                dbContext.AST_PalletTasks.Add(astPalletTask);

                //提取当前目标工位、当前批次、当前巷道、当前托盘未合并的原始任务
                List <int> cfgWorkStationIds = astLesTasks
                                               .Select(lt => lt.CFG_WorkStationId)
                                               .Distinct()
                                               .ToList();
                foreach (int cfgWorkStationId in cfgWorkStationIds)
                {
                    ILookup <int, AST_LesTask> astLesTaskLookupByFromPalletPosition = astLesTasks
                                                                                      .Where(lt => lt.CFG_WorkStationId == cfgWorkStationId)
                                                                                      .OrderBy(lt => lt.FromPalletPosition)
                                                                                      .ToLookup(lt => lt.FromPalletPosition);

                    //明细的合并,特殊件单独拣
                    foreach (IGrouping <int, AST_LesTask> astLesTaskGroupingByFromPalletPosition in astLesTaskLookupByFromPalletPosition)
                    {
                        int         fromPalletPosition          = astLesTaskGroupingByFromPalletPosition.Key;
                        AST_LesTask mainAstLesTaskByWorkStation = astLesTaskGroupingByFromPalletPosition.First();

                        List <AST_LesTaskItem> normalAstLesTaskItems  = new List <AST_LesTaskItem>();
                        List <AST_LesTaskItem> specialAstLesTaskItems = new List <AST_LesTaskItem>();

                        foreach (AST_LesTask astLesTask in astLesTaskGroupingByFromPalletPosition)
                        {
                            normalAstLesTaskItems.AddRange(astLesTask.AST_LesTaskItems.Where(lti => !lti.IsSpecial));
                            specialAstLesTaskItems.AddRange(astLesTask.AST_LesTaskItems.Where(lti => lti.IsSpecial));
                        }

                        //普通件
                        if (normalAstLesTaskItems.Count > 0)
                        {
                            AST_LesTaskItem mainAstLesTaskItem  = normalAstLesTaskItems.First();
                            int             totalNormalQuantity = normalAstLesTaskItems.Sum(lti => lti.ToPickQuantity);

                            AST_PalletTaskItem astPalletTaskItem = new AST_PalletTaskItem();
                            astPalletTaskItem.AST_PalletTask     = astPalletTask;
                            astPalletTaskItem.CFG_WorkStationId  = cfgWorkStationId;
                            astPalletTaskItem.BoxCode            = mainAstLesTaskByWorkStation.BoxCode;
                            astPalletTaskItem.FromPalletPosition = fromPalletPosition;
                            astPalletTaskItem.MaterialCode       = mainAstLesTaskItem.MaterialCode;
                            astPalletTaskItem.MaterialName       = mainAstLesTaskItem.MaterialName;
                            astPalletTaskItem.MaterialBarcode    = mainAstLesTaskItem.MaterialBarcode;
                            astPalletTaskItem.ToPickQuantity     = totalNormalQuantity;
                            astPalletTaskItem.MaxQuantityInSingleCartPosition = mainAstLesTaskItem.MaxQuantityInSingleCartPosition;
                            astPalletTaskItem.IsSpecial  = false;
                            astPalletTaskItem.IsBig      = mainAstLesTaskItem.IsBig;
                            astPalletTaskItem.PickStatus = PickStatus.New;

                            dbContext.AST_PalletTaskItems.Add(astPalletTaskItem);

                            foreach (AST_LesTaskItem normalAstLesTaskItem in normalAstLesTaskItems)
                            {
                                normalAstLesTaskItem.AST_PalletTaskItem = astPalletTaskItem;
                            }
                        }

                        //特殊件
                        foreach (AST_LesTaskItem astLesTaskItem in specialAstLesTaskItems)
                        {
                            AST_PalletTaskItem astPalletTaskItem = new AST_PalletTaskItem();
                            astPalletTaskItem.AST_PalletTask     = astPalletTask;
                            astPalletTaskItem.CFG_WorkStationId  = cfgWorkStationId;
                            astPalletTaskItem.BoxCode            = mainAstLesTaskByWorkStation.BoxCode;
                            astPalletTaskItem.FromPalletPosition = fromPalletPosition;
                            astPalletTaskItem.MaterialCode       = astLesTaskItem.MaterialCode;
                            astPalletTaskItem.MaterialName       = astLesTaskItem.MaterialName;
                            astPalletTaskItem.MaterialBarcode    = astLesTaskItem.MaterialBarcode;
                            astPalletTaskItem.ToPickQuantity     = astLesTaskItem.ToPickQuantity;
                            astPalletTaskItem.MaxQuantityInSingleCartPosition = astLesTaskItem.MaxQuantityInSingleCartPosition;
                            astPalletTaskItem.IsSpecial  = true;
                            astPalletTaskItem.IsBig      = astLesTaskItem.IsBig;
                            astPalletTaskItem.PickStatus = PickStatus.New;

                            dbContext.AST_PalletTaskItems.Add(astPalletTaskItem);

                            astLesTaskItem.AST_PalletTaskItem = astPalletTaskItem;
                        }

                        //标记已合并按托任务
                        foreach (AST_LesTask astLesTask in astLesTaskGroupingByFromPalletPosition)
                        {
                            astLesTask.TaskGenerated = true;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 按巷道查询当前任务。
        /// </summary>
        /// <param name="cfgChannelId">巷道的主键。</param>
        public AssortingKanbanTaskInfo QueryCurrentTaskInfo(int cfgChannelId)
        {
            AssortingKanbanTaskInfo result = new AssortingKanbanTaskInfo();

            try
            {
                using (GeelyPtlEntities dbContext = new GeelyPtlEntities())
                {
                    AST_PalletTask astPalletTask = dbContext.AST_PalletTasks
                                                   .FirstOrDefault(pt => pt.CFG_ChannelId == cfgChannelId && pt.PickStatus != PickStatus.Finished);
                    //新增PDA拣料显示
                    if (astPalletTask == null)
                    {
                        AST_PalletTask lastPalletTask           = dbContext.AST_PalletTasks.Where(t => t.CFG_ChannelId == cfgChannelId).OrderByDescending(t => t.CreateTime).FirstOrDefault();
                        DateTime       dPtlPalletLastArriveTime = DateTime.MinValue;
                        if (lastPalletTask != null)
                        {
                            dPtlPalletLastArriveTime = lastPalletTask.CreateTime;
                        }

                        result = QueryPDACurrentTaskInfo(cfgChannelId, dPtlPalletLastArriveTime);
                        if (result != null)
                        {
                            return(result);
                        }
                        result = new AssortingKanbanTaskInfo();
                    }

                    AST_CartTask astCartTask = dbContext.AST_CartTaskItems
                                               .Where(cti => cti.AST_CartTask.CFG_ChannelId == cfgChannelId && cti.AssortingStatus != AssortingStatus.Finished)
                                               .Select(cti => cti.AST_CartTask)
                                               .FirstOrDefault();

                    string currentBatchCode;
                    if (astPalletTask == null)
                    {
                        currentBatchCode = dbContext.AST_LesTasks
                                           .Where(lt => lt.CFG_ChannelId == cfgChannelId && !lt.TaskGenerated)
                                           .Select(lt => lt.BatchCode)
                                           .FirstOrDefault();
                    }
                    else
                    {
                        currentBatchCode = astPalletTask.BatchCode;
                    }

                    if (!string.IsNullOrEmpty(currentBatchCode))
                    {
                        AST_LesTask currentBatchFirstAstLesTask = new AST_LesTask();
                        if (astPalletTask == null)
                        {
                            currentBatchFirstAstLesTask = dbContext.AST_LesTasks.First(lt => lt.BatchCode == currentBatchCode);
                        }
                        else
                        {
                            currentBatchFirstAstLesTask = dbContext.AST_LesTasks.First(lt => lt.BatchCode == currentBatchCode && lt.CFG_PalletId == astPalletTask.CFG_PalletId);
                        }

                        string projectCode = currentBatchFirstAstLesTask.ProjectCode;
                        string projectStep = currentBatchFirstAstLesTask.ProjectStep;

                        string[] codes = projectCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] steps = projectStep.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (codes.Length > 1 && codes[0] == codes[1])
                        {
                            projectCode = codes[0];
                        }
                        if (steps.Length > 1 && steps[0] == steps[1])
                        {
                            projectStep = steps[0];
                        }

                        result.CurrentBatchInfo.PickType = "P"; //PTL料架拣料
                        //result.CurrentBatchInfo.PickType = 1; //PTL料架拣料
                        result.CurrentBatchInfo.ProjectCode         = projectCode;
                        result.CurrentBatchInfo.ProjectStep         = projectStep;
                        result.CurrentBatchInfo.BatchCode           = currentBatchFirstAstLesTask.BatchCode;
                        result.CurrentBatchInfo.FinishedPalletCount = dbContext.AST_PalletResults
                                                                      .Count(pr => pr.CFG_ChannelId == cfgChannelId && pr.BatchCode == currentBatchCode);
                        result.CurrentBatchInfo.TotalPalletCount = dbContext.AST_LesTasks
                                                                   .Where(lt => lt.CFG_ChannelId == cfgChannelId && lt.BatchCode == currentBatchCode)
                                                                   .Select(lt => lt.CFG_PalletId)
                                                                   .Distinct()
                                                                   .Count();
                        //以下 4 个汇总界面不展示
                        result.CurrentBatchInfo.FinishedMaterialTypeCount = 0;
                        result.CurrentBatchInfo.TotalMaterialTypeCount    = 0;
                        result.CurrentBatchInfo.FinishedMaterialCount     = 0;
                        result.CurrentBatchInfo.TotalMaterialCount        = 0;

                        List <CFG_ChannelCurrentCart> cfgChannelCurrentCarts = dbContext.CFG_ChannelCurrentCarts
                                                                               .Where(ccc => ccc.CFG_ChannelId == cfgChannelId)
                                                                               .OrderBy(ccc => ccc.Position)
                                                                               .ToList();
                        foreach (CFG_ChannelCurrentCart cfgChannelCurrentCart in cfgChannelCurrentCarts)
                        {
                            CFG_ChannelCurrentCartDto cfgChannelCurrentCartDto = new CFG_ChannelCurrentCartDto();
                            cfgChannelCurrentCartDto.CFG_ChannelCurrentCartId = cfgChannelCurrentCart.Id;
                            cfgChannelCurrentCartDto.CFG_ChannelId            = cfgChannelCurrentCart.CFG_ChannelId;
                            cfgChannelCurrentCartDto.Position   = cfgChannelCurrentCart.Position;
                            cfgChannelCurrentCartDto.CFG_CartId = cfgChannelCurrentCart.CFG_CartId;
                            if (cfgChannelCurrentCart.CFG_Cart != null)
                            {
                                cfgChannelCurrentCartDto.CartCode = cfgChannelCurrentCart.CFG_Cart.Code;
                                cfgChannelCurrentCartDto.CartName = cfgChannelCurrentCart.CFG_Cart.Name;
                            }
                        }

                        if (astPalletTask != null)
                        {
                            AST_PalletTaskDto astPalletTaskDto = new AST_PalletTaskDto();
                            astPalletTaskDto.AST_PalletTaskId     = astPalletTask.Id;
                            astPalletTaskDto.CFG_PalletId         = astPalletTask.CFG_PalletId;
                            astPalletTaskDto.PalletCode           = astPalletTask.CFG_Pallet.Code;
                            astPalletTaskDto.PalletType           = astPalletTask.CFG_Pallet.PalletType;
                            astPalletTaskDto.PalletRotationStatus = astPalletTask.CFG_Pallet.PalletRotationStatus;

                            List <AST_PalletTaskItem> astPalletTaskItems = astPalletTask.AST_PalletTaskItems
                                                                           .OrderBy(pti => pti.FromPalletPosition)
                                                                           .ToList();
                            astPalletTaskItems.Sort(new PalletTaskSortComparer()); //正在拣选的排在最前面
                            foreach (AST_PalletTaskItem astPalletTaskItem in astPalletTaskItems)
                            {
                                AST_PalletTaskItemDto astPalletTaskItemDto = new AST_PalletTaskItemDto();
                                astPalletTaskItemDto.AST_PalletTaskItemId = astPalletTaskItem.Id;
                                astPalletTaskItemDto.FromPalletPosition   = astPalletTaskItem.FromPalletPosition;
                                astPalletTaskItemDto.WorkStationCode      = astPalletTaskItem.CFG_WorkStation.Code;
                                astPalletTaskItemDto.MaterialCode         = astPalletTaskItem.MaterialCode;
                                astPalletTaskItemDto.MaterialName         = astPalletTaskItem.MaterialName;
                                astPalletTaskItemDto.MaterialBarcode      = astPalletTaskItem.MaterialBarcode;
                                astPalletTaskItemDto.ToPickQuantity       = astPalletTaskItem.ToPickQuantity;
                                astPalletTaskItemDto.IsSpecial            = astPalletTaskItem.IsSpecial;
                                astPalletTaskItemDto.IsBig          = astPalletTaskItem.IsBig;
                                astPalletTaskItemDto.PickStatus     = astPalletTaskItem.PickStatus;
                                astPalletTaskItemDto.PickedQuantity = astPalletTaskItem.PickedQuantity;

                                astPalletTaskDto.Items.Add(astPalletTaskItemDto);
                            }

                            result.CurrentPalletTask = astPalletTaskDto;
                        }

                        if (astCartTask != null)
                        {
                            AST_CartTaskDto astCartTaskDto = new AST_CartTaskDto();
                            astCartTaskDto.AST_CartTaskId = astCartTask.Id;
                            astCartTaskDto.CFG_CartId     = astCartTask.CFG_CartId;
                            astCartTaskDto.CartCode       = astCartTask.CFG_Cart.Code;
                            astCartTaskDto.CartName       = astCartTask.CFG_Cart.Name;

                            List <AST_CartTaskItem> astCartTaskItems = astCartTask.AST_CartTaskItems
                                                                       .OrderBy(cti => cti.CartPosition)
                                                                       .ToList();
                            foreach (AST_CartTaskItem astCartTaskItem in astCartTaskItems)
                            {
                                AST_PalletTaskItem astPalletTaskItem = astCartTaskItem.AST_PalletTaskItem;

                                AST_CartTaskItemDto astCartTaskItemDto = new AST_CartTaskItemDto();
                                astCartTaskItemDto.AST_CartTaskItemId = astCartTaskItem.Id;
                                astCartTaskItemDto.CartPosition       = astCartTaskItem.CartPosition;
                                astCartTaskItemDto.WorkStationCode    = astCartTask.CFG_WorkStation.Code;
                                astCartTaskItemDto.MaterialCode       = astPalletTaskItem.MaterialCode;
                                astCartTaskItemDto.MaterialName       = astPalletTaskItem.MaterialName;
                                astCartTaskItemDto.MaterialBarcode    = astPalletTaskItem.MaterialBarcode;
                                astCartTaskItemDto.MaxQuantityInSingleCartPosition = astPalletTaskItem.MaxQuantityInSingleCartPosition;
                                astCartTaskItemDto.IsSpecial       = astPalletTaskItem.IsSpecial;
                                astCartTaskItemDto.IsBig           = astPalletTaskItem.IsBig;
                                astCartTaskItemDto.AssortingStatus = astCartTaskItem.AssortingStatus;
                                astCartTaskItemDto.PickedQuantity  = astCartTaskItem.AssortedQuantity;

                                astCartTaskDto.Items.Add(astCartTaskItemDto);
                            }

                            result.CurrentCartTask = astCartTaskDto;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                DbEntityValidationException dbEntityValidationException = ex as DbEntityValidationException;
                if (dbEntityValidationException != null)
                {
                    foreach (DbEntityValidationResult validationResult in dbEntityValidationException.EntityValidationErrors)
                    {
                        foreach (DbValidationError validationError in validationResult.ValidationErrors)
                        {
                            message += Environment.NewLine + validationError.ErrorMessage;
                        }
                    }
                }
                message += Environment.NewLine + ex.StackTrace;

                Logger.Log("ForAssortingKanbanService.QueryCurrentTaskInfo", DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine
                           + message + Environment.NewLine
                           + Environment.NewLine);
            }

            return(result);
        }
        /// <summary>
        /// 从分拣口解除小车绑定。
        /// </summary>
        /// <param name="cfgChannelId">分拣口的主键。</param>
        /// <param name="cfgCartId">待移出小车的主键。</param>
        /// <exception cref="System.ArgumentException">position 车位上的小车还未作业完成。</exception>
        public void UnDock(int cfgChannelId, int cfgCartId)
        {
            using (GeelyPtlEntities dbContext = new GeelyPtlEntities())
            {
                CFG_ChannelCurrentCart cfgChannelCurrentCart = dbContext.CFG_ChannelCurrentCarts
                                                               .FirstOrDefault(ccc => ccc.CFG_ChannelId == cfgChannelId && ccc.CFG_CartId == cfgCartId);
                if (cfgChannelCurrentCart != null && cfgChannelCurrentCart.CFG_CartId != null)
                {
                    CFG_Cart cfgCart = cfgChannelCurrentCart.CFG_Cart;
                    if (cfgCart.CartStatus == CartStatus.Assorting)
                    {
                        throw new ArgumentException("车位 " + cfgChannelCurrentCart.Position + " 上的小车 " + cfgCart.Code + " 还未作业完成。", "position");
                    }

                    //移出
                    cfgChannelCurrentCart.CFG_CartId = null;
                    cfgChannelCurrentCart.DockedTime = null;

                    //准备基础数据
                    AST_PalletTask  astPalletTask  = null;
                    CFG_WorkStation cfgWorkStation = null;
                    List <CFG_CartCurrentMaterial> cfgCartCurrentMaterials = cfgCart.CFG_CartCurrentMaterials
                                                                             .ToList();
                    CFG_CartCurrentMaterial firstNotEmptyCfgCartCurrentMaterial = cfgCartCurrentMaterials
                                                                                  .FirstOrDefault(ccm => ccm.AST_CartTaskItemId != null);
                    if (firstNotEmptyCfgCartCurrentMaterial != null)
                    {
                        AST_CartTaskItem astCartTask = firstNotEmptyCfgCartCurrentMaterial.AST_CartTaskItem;
                        astPalletTask  = astCartTask.AST_PalletTaskItem.AST_PalletTask;
                        cfgWorkStation = astCartTask.AST_PalletTaskItem.CFG_WorkStation;
                    }

                    dbContext.SaveChanges();

                    //设备控制
                    CartPtl cartPtl          = CartPtlHost.Instance.GetCartPtl(cfgCart.Id);
                    Ptl900U ptl900UPublisher = cartPtl.GetPtl900UPublisher();
                    Ptl900U ptl900ULight     = cartPtl.GetPtl900ULight();

                    ptl900UPublisher.Clear(true);
                    ptl900UPublisher.Unlock();

                    if (astPalletTask != null)
                    {
                        Display900UItem publisherDisplay900UItem = new Display900UItem();
                        publisherDisplay900UItem.Name        = "已分拣完成";
                        publisherDisplay900UItem.Description = string.Format(CultureInfo.InvariantCulture, @"项目:{0}
阶段:{1}
工位:{2}", astPalletTask.ProjectCode, astPalletTask.ProjectStep, cfgWorkStation.Code);
                        publisherDisplay900UItem.Count       = (ushort)cfgCartCurrentMaterials
                                                               .Where(ccm => ccm.Quantity != null)
                                                               .Select(ccm => ccm.Quantity.Value)
                                                               .Sum();
                        publisherDisplay900UItem.Unit = "个";

                        ptl900UPublisher.Lock();
                        ptl900UPublisher.Display(publisherDisplay900UItem, LightColor.Off);
                    }

                    foreach (CFG_CartCurrentMaterial cfgCartCurrentMaterial in cfgCartCurrentMaterials)
                    {
                        Ptl900U ptl900U = cartPtl.GetPtl900UByPosition(cfgCartCurrentMaterial.Position);

                        ptl900U.Clear(true);
                        ptl900U.Unlock();
                    }

                    ptl900ULight.Clear();
                }
            }
        }