using HandyControl.Tools.Extension;
using Jc.SnowId;
using Khd.Core.Domain.Auth;
using Khd.Core.Domain.Dto.webapi;
using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Library.Mapper;
using Khd.Core.Plc;
using Khd.Core.Plc.S7;
using Khd.Core.Wpf.dto;
using Khd.Core.Wpf.Scan;
using Khd.Core.Wpf.TaskForm;
using Khd.Core.Wpf.WindowPage;
using Masuit.Tools;
using Masuit.Tools.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
using Z.EntityFramework.Plus;
using static HandyControl.Tools.Interop.InteropValues;

namespace Khd.Core.Wpf.Form
{
    /// <summary>
    /// FormBoardT.xaml 的交互逻辑
    /// </summary>
    public partial class FormBoardT : Window
    {
        private List<long> productIds = new List<long>() { 231, 531, 521 };
        public static long? UserId = 1;
        public static readonly JcSnowId _jcSnowId = new JcSnowId();
        private readonly IHost _host;
        private Khd.Core.Plc.S7.Plc _plc;
        private DispatcherTimer ShowTimer;//刷新时间
        private DispatcherTimer PLCMessage;//呈现PLC机柜信息
        private DispatcherTimer UPMessageTimer;//刷新上件记录
        private DispatcherTimer ShowOrderMessage;//呈现PLC机柜信息
        private object order_code;
        private int UpState;//对应上件站点的状态,0为良好 1为损坏
        private SerialPortModel serialPortModel;
        private SerialPortHelper serialPortHelper;
        List<BasePlcpoint> basePlcpoints = new List<BasePlcpoint>();
        object timerjilu;
        Dictionary<long, bool> SelectedItem = new Dictionary<long, bool>();
        Dictionary<long, bool> InSelectedItem = new Dictionary<long, bool>();
        List<long?> CallSelectedItem = new List<long?>();
        public List<MesBaseBarcodeInfo> barcodeLsit = new List<MesBaseBarcodeInfo>();
        private int pageCount = 15;
        private object updateLock = new object();
        private readonly List<LocationDto> locationDtos = new List<LocationDto>();
        private ObservableCollection<SelectItemModel> itemsControlItems;

        //人工叫料选中类
        public class SelectItemModel
        {
            //料箱位置id
            public long baseLocationId { get; set; }
            //托盘号
            public string palletInfoCode { get; set; }
        }
        private void ScanMessage()
        {
            while (true)
            {
                try
                {
                    if (SystemData.isUpdate)
                    {
                        if (!string.IsNullOrEmpty(SystemData.message))
                        {
                            Dispatcher.Invoke(() =>
                            {
                                var focusedElement = FocusManager.GetFocusedElement(this);
                                if (focusedElement is TextBox textBox)
                                {
                                    textBox.Text = SystemData.message;
                                    SystemData.isUpdate = false;
                                }
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Error(ex);
                }
                Thread.Sleep(500);
            }
        }

        private string selectedId;
        //FormShowSelect formSelect;
        // public static int WeekNo = CommonHelper.WeekOfYear(DateTime.Now, new System.Globalization.CultureInfo("zh-CN"));
        public FormBoardT(IHost host)
        {
            InitializeComponent();
            this._host = host;
        }
        /// <summary>
        /// 页面加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormBoard_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeData(1);
            
            try
            {
                itemsControlItems = new ObservableCollection<SelectItemModel>();
                itemsControl.ItemsSource = itemsControlItems;
                Task.Run(() =>
                {
                    foreach (var plcConfig in SystemData.PlcConfigs)
                    {
                        if (!SystemData.PlcDic.Any(t => t.Key == plcConfig.Code))
                        {
                            Plc.S7.Plc plc;
                            plc = new Plc.S7.Plc(plcConfig.CpuType, plcConfig.IP, plcConfig.Port, plcConfig.Rack, plcConfig.Slot);
                            try
                            {
                                plc.Open();
                            }
                            catch (Exception ex)
                            {
                                LogManager.Error(ex);
                            }
                            SystemData.PlcDic.TryAdd(plcConfig.Code, plc);
                        }
                    };

                });
                GetMenu();
                GetTask();
                DispatcherTimer dispatcherTimer = new DispatcherTimer();
                dispatcherTimer.Tick += new EventHandler(ShowTime); //委托刷新时间方法
                dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
                dispatcherTimer.Start();

                Thread AgvStatusThread = new Thread(AgvStatus)
                {
                    IsBackground = true,
                };
                AgvStatusThread.Start();

                Thread ddjThread = new Thread(ddjTimer)
                {
                    IsBackground = true,
                };
                ddjThread.Start();
                Thread RefreshPlcThread = new Thread(RefreshPlc)
                {
                    IsBackground = true,
                };
                RefreshPlcThread.Start();

                Thread OutOrderThread = new Thread(OutOrderTimer)
                {
                    IsBackground = true
                };
                OutOrderThread.Start();

                Thread ReturnOrderThread = new Thread(ReturnOrderTimer)
                {
                    IsBackground = true
                };
                ReturnOrderThread.Start();

                //Thread ddjThread = new Thread(ddjTimer);
                //ddjThread.Start();
                //LogManager.Info($"--------------------------当前时间 :{DateTime.Now} >>> 客户端启动;");
                //设置显示任务栏
                if (WindowState == WindowState.Normal)
                {
                    MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
                    WindowState = WindowState.Maximized;
                }
                Task.Run(() =>
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    SystemData.BasePlcpoints = dbContext.BasePlcpoint.ToList();
                    SystemData.BaseDictionary = dbContext.BaseDictionary.ToList();
                    SystemData.BaseWareHouse = dbContext.WmsBaseWarehouse.ToList();
                    SystemData.MesBaseMaterialInfo = dbContext.MesBaseMaterialInfo.Take(100).ToList();
                    Dispatcher.Invoke(() =>
                    {
                        WarehourseId.ItemsSource = SystemData.BaseWareHouse.Where(t => t.warehouseFloor != 1 && t.warehouseFloor != 4).ToList();
                    });
                });

                //MaterialName.ItemsSource = SystemData.MesBaseMaterialInfo;

                try
                {
                    serialPortModel = new SerialPortModel();
                    serialPortModel.PortName = "COM1";
                    serialPortModel.BaudRate = 9600;
                    serialPortModel.DataBits = 8;
                    serialPortModel.Parity = Parity.None;
                    serialPortModel.StopBits = StopBits.One;
                    serialPortHelper = new SerialPortHelper();
                    serialPortHelper.OpenMyConn(serialPortModel);
                    Thread scanThread = new Thread(ScanMessage);
                    scanThread.IsBackground = true;
                    scanThread.Start();
                }
                catch (Exception ex)
                {
                    HandyControl.Controls.MessageBox.Error("条码枪连接失败");
                }


                Task.Run(() =>
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    while (true)
                    {
                        try
                        {
                            dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                            int waitCtuCount = dbContext.WcsTask.Where(t => t.taskType == 30).Where(t => t.useFlag == 0).Where(t => t.taskStatus == 0).Count();
                            Dispatcher.Invoke(() =>
                            {
                                outTaskCount.Text = waitCtuCount.ToString();
                            });
                        }
                        catch
                        {

                        }
                        Thread.Sleep(3000);
                    }
                });
                //加载dategrid信息
                //LoadMaterial_GetMessage("");
                //连接PLC判断
                // var plc = new Khd.Core.Plc.S7.Plc((CpuType)PlcConfig.CpuType, PlcConfig.IP, PlcConfig.Port,
                // PlcConfig.Rack, PlcConfig.Slot);
                // //plc.Open();
                // //if (!plc.IsConnected)
                // //{
                // //    HandyControl.Controls.MessageBox.Show("PLC连接失败,重新连接");
                // //}
                // //else
                // //{
                // //    this._plc = plc;
                // //}

                // using var scope = _host.Services.CreateScope();
                // using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                // basePlcpoints = dbContext.BasePlcpoint.Where(t => t.isDelete == 0).ToList();
                // //var baseMaterials = dbContext.BaseMaterial.Where(t => t.IsDelete == 0).ToList();
                ////

                // PLCMessage = new DispatcherTimer();
                // PLCMessage.Tick += new EventHandler(PLCmessage); //委托获取点位方法
                // PLCMessage.Interval = new TimeSpan(0, 0, 0, 0, 1000);
                // PLCMessage.Start();

                // UPMessageTimer = new DispatcherTimer();
                // UPMessageTimer.Tick += new EventHandler(UpMessage); //委托刷新上件记录
                // UPMessageTimer.Interval = new TimeSpan(0, 0, 0, 0, 2000);
                // UPMessageTimer.Start();
                // Button_Click_1(null, null);
                // SetTime();
                // List<string> list = new List<string>
                // {
                //     "101上件点",
                //     "102上件点",
                //     "103上件点"
                // };
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
            }

           
        }

        #region 库位状态可视化
        private void InitializeData(int rowPosition)
        {
            try
            {
                LocationsControl.ItemsSource = null;
                using var scope = _host.Services.CreateScope();

                var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                // 该侧所有库位
                var allLocationLists = dbContext.WmsBaseLocation.Where(x => x.warehouseId == 512 && x.locRow == rowPosition).ToList();
                allLocationLists = allLocationLists.OrderBy(x => x.layerNum).ThenBy(x => x.locColumn).ToList();
                //在库里的库位
                var inLocationList = allLocationLists.Where(x => x.ContainerStatus == "1").Select(x => x.locationCode).ToList();
                //在库里有库存的库位
                var withStockLocationList = dbContext.WmsRawStock.Where(x => x.warehouseId == 512 && inLocationList.Contains(x.locationCode)).Select(x => x.locationCode).Distinct().ToList();
                // 在库里无库存的库位
                var withoutStockLocationList = inLocationList
                    .Except(withStockLocationList)
                    .ToList();

                var locations = new List<Location>();
                for (int i = 0; i < 6 * 36; i++)
                {
                    LocationStatus status = LocationStatus.OutOfStock;
                    WmsBaseLocation targetLocation = allLocationLists[i];
                    if (withStockLocationList.Contains(targetLocation.locationCode))
                    {
                        status = LocationStatus.InAndStock;
                    }
                    if (withoutStockLocationList.Contains(targetLocation.locationCode))
                    {
                        status = LocationStatus.EmptyInStock;
                    }

                    Visibility isFreeze = targetLocation.locationStatus == "1" ? Visibility.Collapsed : Visibility.Visible;
                    locations.Add(new Location { LocationId = targetLocation.locationId, Code = targetLocation.locColumn.ToString(), Status = status, isFreeze = isFreeze });
                }

                LocationsControl.ItemsSource = locations;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LocationButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button != null)
            {
                var location = button.DataContext as Location;
                if (location != null)
                {
                    StockWindow window = new StockWindow(_host, location.LocationId);
                    window.Show();
                    // MessageBox.Show(location.LocationId.ToString());
                }
            }
        }

        private void QueryPositionCombox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 获取选中的 ComboBoxItem
            ComboBox comboBox = sender as ComboBox;
            ComboBoxItem selectedItem = comboBox.SelectedItem as ComboBoxItem;

            if (selectedItem != null)
            {
                // 获取选中项的内容和 Tag
                string content = selectedItem.Content.ToString();
                object tag = selectedItem.Tag;
                InitializeData(int.Parse(tag.ToString()));
            }
        }
        #endregion

        private void ReturnOrderTimer(object? obj)
        {
            using var scope = _host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            List<BaseEquip> baseEquips = dbContext.BaseEquip.Where(t => t.equipType == 10).ToList();
            var endStationCodes = baseEquips.Select(t => t.agvPositionCode).ToList();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    List<WmsRawReturn> wmsRawReturns = dbContext.WmsRawReturn.Where(t => endStationCodes.Contains(t.endStationCode))
                        .Where(t => t.auditStatus == "1")
                        .Where(t => t.executeStatus == "0" || t.executeStatus == "1")
                        .Where(t => t.returnAmount > t.planAmount)
                        .ToList();
                    List<string> list = wmsRawReturns.Select(t => t.endStationCode).ToList();
                    List<long?> orderIds = wmsRawReturns.Select(t => t.rawReturnId).ToList();
                    Dispatcher.Invoke(() =>
                    {
                        this.ReturnOrder.Text = "待退库单：\n" + list.Distinct().Join("\n");
                    });
                    var baseEquip = dbContext.BaseEquip.First(t => t.objid == 10);
                    if (!string.IsNullOrEmpty(baseEquip.endStationCode))
                    {
                        List<WcsTask> wcsTasks = dbContext.WcsTask.Where(t => t.taskType == 30).Where(t => orderIds.Contains(t.orderId)).ToList();
                        List<string> containerNos = wcsTasks.Select(t => t.containerNo).ToList();
                        List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock.Where(t => containerNos.Contains(t.palletInfoCode)).ToList();
                        var thisOutList = wmsRawStocks.GroupBy(t => new { t.materialId, t.saleOrderId })
                            .Select(t => new
                            {
                                materialId = t.Key.materialId,
                                saleOrderId = t.Key.saleOrderId,
                                thisOutAmount = t.Sum(x => x.totalAmount) - t.Sum(x => x.frozenAmount)
                            });
                        List<WmsRawReturn> endStationCodeOutRaw = wmsRawReturns.Where(t => t.endStationCode == baseEquip.endStationCode).ToList();
                        List<long?> materialIds = endStationCodeOutRaw.Select(t => t.materialId).ToList();
                        List<MesBaseMaterialInfo> mesBaseMaterialInfos = dbContext.MesBaseMaterialInfo.Where(t => materialIds.Contains(t.MaterialId)).ToList();
                        var bill = endStationCodeOutRaw.GroupBy(t => new { t.materialId })
                            .Select(t => new
                            {
                                materialId = t.Key.materialId,
                                outstockAmount = t.Sum(x => x.returnAmount),
                                realOutstockAmount = t.Sum(x => x.planAmount),
                            });
                        var orderNumber = from a in bill
                                          from b in thisOutList
                                          from c in mesBaseMaterialInfos
                                          where a.materialId == b.materialId
                                          select new
                                          {
                                              materialBatch = c.MaterialCode,
                                              saleOrderId = b.saleOrderId,
                                              outstockAmount = a.outstockAmount,
                                              materialSpec = c.MaterialSpec,
                                              realOutstockAmount = a.realOutstockAmount,
                                              thisOutAmount = b.thisOutAmount,
                                          };
                        Dispatcher.Invoke(() =>
                        {
                            this.ReturnTaskNumber.ItemsSource = orderNumber;
                            this.ReturnTaskNumber.Items.Refresh();
                        });
                    }
                    else
                    {
                        Dispatcher.Invoke(() =>
                        {
                            this.ReturnTaskNumber.ItemsSource = null;
                            this.ReturnTaskNumber.Items.Refresh();
                        });
                    }
                }
                catch
                {

                }
                Thread.Sleep(1000);
            }
        }

        private void OutOrderTimer(object? obj)
        {
            using var scope = _host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            List<BaseEquip> baseEquips = dbContext.BaseEquip.Where(t => t.equipType == 10).ToList();
            var endStationCodes = baseEquips.Select(t => t.agvPositionCode).ToList();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    List<WmsRawOutstock> wmsRawOutstocks = dbContext.WmsRawOutstock.Where(t => endStationCodes.Contains(t.endStationCode))
                        .Where(t => t.auditStatus == "1")
                        .Where(t => t.executeStatus == "0" || t.executeStatus == "1")
                        .Where(t => t.outstockAmount > t.realOutstockAmount)
                        .ToList();
                    List<string> list = wmsRawOutstocks.Select(t => t.endStationCode).ToList();
                    List<long?> orderIds = wmsRawOutstocks.Select(t => t.rawOutstockId).ToList();

                    BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 10);
                    string nowStationCode = baseEquip.endStationCode;
                    if (!string.IsNullOrEmpty(nowStationCode))
                    {
                        Dispatcher.Invoke(() =>
                        {
                            SelectOutButton.Content = "当前:" + nowStationCode;
                            //SelectOutButton.IsEnabled = false;
                        });
                    }
                    else
                    {
                        Dispatcher.Invoke(() =>
                        {
                            SelectOutButton.Content = "选择出库";
                            //SelectOutButton.IsEnabled = true;
                        });
                    }
                    Dispatcher.Invoke(() =>
                    {
                        this.OutOrder.Text = "待出库单：\n" + list.Distinct().Join("\n");
                    });


                    if (!string.IsNullOrEmpty(baseEquip.endStationCode))
                    {
                        #region 待测试
                        //找出本工位的申请单
                        List<WmsRawOutstock> RawOutstocks = wmsRawOutstocks.Where(t => t.endStationCode == baseEquip.endStationCode).ToList();

                        // 根据 materialId 分组，并计算 outstockAmount 和 realOutstockAmount 的总和
                        var targetRawOutstocks = RawOutstocks
                            .GroupBy(t => new { t.materialId, t.saleOrderId })
                            .Select(g => new
                            {
                                materialId = g.Key.materialId,
                                saleOrderId = g.Key.saleOrderId,
                                totalOutstockAmount = g.Sum(t => t.outstockAmount),
                                totalRealOutstockAmount = g.Sum(t => t.realOutstockAmount)
                            }).ToList();

                        //本次所有任务出来的托盘号
                        List<WcsTask> wcsTasks = dbContext.WcsTask.Where(t => t.taskType == 30).Where(t => orderIds.Contains(t.orderId)).ToList();
                        List<string> containerNos = wcsTasks.Select(t => t.containerNo).ToList();
                        //本次所有托盘携带的物料
                        List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock.Where(t => containerNos.Contains(t.palletInfoCode)).ToList();

                        // Step 3: 计算每个申请单物料在各个托盘中的数量
                        var palletMaterialSummary = wmsRawStocks
                            .GroupBy(t => new { t.materialId, t.palletInfoCode, t.saleOrderId })
                            .Select(g => new
                            {
                                MaterialId = g.Key.materialId,
                                saleOrderId = g.Key.saleOrderId,
                                PalletInfoCode = g.Key.palletInfoCode,
                                //携带总可用库存
                                canUseAmount = g.Sum(x => x.totalAmount) - g.Sum(x => x.frozenAmount)
                            })
                            .ToList();

                        // 汇总每个申请单在各个托盘的物料数量
                        var result = targetRawOutstocks
                            .Select(order => new
                            {
                                SaleOrderId = order.saleOrderId,
                                MaterialId = order.materialId,
                                //申请数量
                                RequestedAmount = order.totalOutstockAmount,
                                //实际已出数量
                                RealOutstockAmount = order.totalRealOutstockAmount,
                                // 托盘携带可用信息，用分号分隔
                                PalletDetails = string.Join("\n", palletMaterialSummary
            .Where(pallet => pallet.MaterialId == order.materialId)
            .Select(pallet => $"托盘{pallet.PalletInfoCode}数量{string.Format("{0:0.00}", pallet.canUseAmount)}")
        )
                            }).ToList();

                        List<long?> materialIds = RawOutstocks.Select(t => t.materialId).ToList();
                        List<MesBaseMaterialInfo> mesBaseMaterialInfos = dbContext.MesBaseMaterialInfo.Where(t => materialIds.Contains(t.MaterialId)).ToList();


                        var orderNumber = from r in result
                                          from m in mesBaseMaterialInfos
                                          where r.MaterialId == m.MaterialId
                                          select new
                                          {
                                              materiaName = m.MaterialName,
                                              materialSpec = m.MaterialSpec,
                                              saleOrderId = r.SaleOrderId,
                                              outstockAmount = string.Format("{0:0.00}", r.RequestedAmount),
                                              realOutstockAmount = string.Format("{0:0.00}", r.RealOutstockAmount),
                                              isSendOver = r.RequestedAmount <= r.RealOutstockAmount ? "已出完" : "未出完",
                                              thisOutAmount = r.PalletDetails
                                          };

                        #endregion

                        //List<WcsTask> wcsTasks = dbContext.WcsTask.Where(t => t.taskType == 30).Where(t => orderIds.Contains(t.orderId)).ToList();

                        //List<string> containerNos = wcsTasks.Select(t => t.containerNo).ToList();
                        //List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock.Where(t => containerNos.Contains(t.palletInfoCode)).ToList();
                        //var thisOutList = wmsRawStocks.GroupBy(t => new { t.materialId, t.saleOrderId,t.palletInfoCode })
                        //    .Select(t => new
                        //    {
                        //        palletInfoCode = t.Key.palletInfoCode,
                        //        materialId = t.Key.materialId,
                        //        saleOrderId = t.Key.saleOrderId,
                        //        thisOutAmount = t.Sum(x => x.totalAmount) - t.Sum(x => x.frozenAmount)
                        //    });
                        //List<WmsRawOutstock> endStationCodeOutRaw = wmsRawOutstocks.Where(t => t.endStationCode == baseEquip.endStationCode).ToList();


                        //List<long?> materialIds = endStationCodeOutRaw.Select(t => t.materialId).ToList();
                        //List<MesBaseMaterialInfo> mesBaseMaterialInfos = dbContext.MesBaseMaterialInfo.Where(t => materialIds.Contains(t.MaterialId)).ToList();
                        //var bill = endStationCodeOutRaw.GroupBy(t => new { t.materialId, t.materialBatch, t.saleOrderId })
                        //    .Select(t => new
                        //    {
                        //        materialId = t.Key.materialId,
                        //        materialBatch = t.Key.materialBatch,
                        //        saleOrderId = t.Key.saleOrderId,
                        //        outstockAmount = t.Sum(x => x.outstockAmount),
                        //        realOutstockAmount = t.Sum(x => x.realOutstockAmount),
                        //    });
                        //var orderNumber = from a in bill
                        //                  from b in thisOutList
                        //                  from c in mesBaseMaterialInfos
                        //                  where a.materialId == b.materialId && a.saleOrderId == b.saleOrderId && a.materialId ==c.MaterialId
                        //                  select new
                        //                  {
                        //                      palletInfoCode = b.palletInfoCode,
                        //                      materialBatch = a.materialBatch,
                        //                      saleOrderId = b.saleOrderId,
                        //                      outstockAmount = a.outstockAmount,
                        //                      materialSpec = c.MaterialSpec,
                        //                      realOutstockAmount = a.realOutstockAmount,
                        //                      thisOutAmount = b.thisOutAmount, 
                        //                      isSendOver = a.outstockAmount <= (a.realOutstockAmount + b.thisOutAmount) ? "已出完" : "未出完"
                        //                  };

                        Dispatcher.Invoke(() =>
                        {
                            this.OutTaskNumber.ItemsSource = orderNumber;
                            this.OutTaskNumber.Items.Refresh();
                        });
                    }
                    else
                    {
                        Dispatcher.Invoke(() =>
                        {
                            this.OutTaskNumber.ItemsSource = null;
                            this.OutTaskNumber.Items.Refresh();
                        });
                    }
                }
                catch
                {

                }
                Thread.Sleep(2000);
            }
        }

        Dictionary<string, string> agvDic = new Dictionary<string, string>
        {
            {"6011","五楼潜伏" },
            {"2034","五楼叉车" },
            {"8161","五楼CTU" },
            {"2032","三楼叉车" },
            {"2033","二楼叉车" },
        };
        private void AgvStatus()
        {
            using var scope = _host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    var wcsAgvStatuses = dbContext.WcsAgvStatus.ToList();
                    var list = wcsAgvStatuses.Select(
                     t => new
                     {
                         Battery = t.Battery,
                         Speed = t.Speed,
                         Status = t.Status,
                         Stop = t.Stop == "1" ? "停止" : "运行",
                         DateNow = t.DateNow?.ToString("yyyy-MM-dd HH:mm:ss"),
                         ExclType = t.ExclType,
                         MapCode = t.MapCode == "EE" ? "五楼" : t.MapCode == "BB" ? "三楼" : "二楼",
                         Online = t.Online.ToUpper() == "TRUE" ? "在线" : "离线",
                         robotIp = t.robotIp,
                         Path2 = t.Path2,
                         RobotCode = agvDic[t.RobotCode],
                         PosX = t.PosX,
                         PosY = t.PosY,
                         PodDir = t.PodDir,
                         RobotDir = t.RobotDir,
                         PodCode = t.PodCode,
                     }
                    ).ToList();
                    Dispatcher.Invoke(() =>
                    {
                        this.AgvDataGrid.ItemsSource = list;
                        this.AgvDataGrid.Items.Refresh();
                    });
                }
                catch
                {

                }
                Thread.Sleep(3000);
            }

        }

        private void ddjTimer()
        {
            using var scope = _host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    lock (updateLock)
                    {
                        dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                        SystemData.BaseEquip = dbContext.BaseEquip.ToList();
                        BaseEquip baseEquip = SystemData.BaseEquip.First(t => t.objid == 40);
                        Dispatcher.Invoke(() =>
                        {
                            EquipListSelectDy.ItemsSource = SystemData.BaseEquip.Where(t => t.equipType == 2 || t.equipType == 4 || t.equipType == 5 || t.equipType == 6 || t.equipType == 11);
                            this.firstRFID.Text = SystemData.BaseEquip.First(t => t.objid == 1).containerNo;
                            this.DDJEmptyCount.Text = baseEquip.emptyCount.ToString();
                            if (baseEquip.emptyCount == 0)
                            {
                                this.OneIn.IsEnabled = true;
                                this.SomeIn.IsEnabled = true;
                                this.OneOut.IsEnabled = false;
                                this.SomeOut.IsEnabled = false;
                            }
                            else if (baseEquip.emptyCount > 0 && baseEquip.emptyCount < 10)
                            {
                                this.OneIn.IsEnabled = true;
                                this.SomeIn.IsEnabled = false;
                                this.OneOut.IsEnabled = true;
                                this.SomeOut.IsEnabled = true;
                            }
                            else if (baseEquip.emptyCount >= 10)
                            {
                                this.OneIn.IsEnabled = false;
                                this.SomeIn.IsEnabled = false;
                                this.OneOut.IsEnabled = true;
                                this.SomeOut.IsEnabled = true;
                            }
                            this.EmptyEquip.ItemsSource = SystemData.BaseEquip.Where(t => t.equipType == 20 || t.equipType == 21 || t.equipType == 19).Select(
                                t => new BaseEquip
                                {
                                    objid = t.objid,
                                    equipName = t.equipName,
                                    emptyCount = t.emptyCount,
                                    equipType = t.equipType,
                                    ud3 = t.ud3 == "0" ? "空" : t.ud3 == "1" ? "托盘" : t.ud3 == "2" ? "废料" : "未知",
                                    equipNo = t.equipNo,
                                    floorNo = t.floorNo,
                                    containerNo = t.containerNo
                                }
                            ).OrderBy(t => t.equipNo);
                            this.EmptyEquip.Items.Refresh();
                        });
                    }
                }
                catch
                {

                }
                Thread.Sleep(3000);
            }
        }

        private void ShowTime(object? sender, EventArgs e)
        {
            try
            {
                this.LabDate.Text = DateTime.Now.Date.ToString("yyyy-MM-dd");
                this.LabTime.Text = DateTime.Now.ToString("HH:mm:ss");
            }
            catch
            {

            }
        }

        /// <summary>
        /// 显示序号事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgData_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        /// <summary>
        /// 点击退出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            if (HandyControl.Controls.MessageBox.Show("是否确认关闭程序", "提示信息", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                System.Environment.Exit(System.Environment.ExitCode);
            }
        }

        private void Close(object sender, EventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode);
        }
        public int i = 0;


        /// <summary>
        /// 查询任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetTask_Click(object sender, RoutedEventArgs e)
        {
            GetTask();
        }

        //private void GetTaskLog()
        //{
        //    try
        //    {
        //        using var scope = _host.Services.CreateScope();
        //        using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
        //        List<WcsTaskLog> wcsTaskLogs = new List<WcsTaskLog>();
        //        for (int i = 1; i <= 5; i++)
        //        {
        //            BasePlcpoint basePlcpoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "RFID00" + i);
        //            string? rifd = SystemData.PlcDic[0].ReadRFID(basePlcpoint.plcpointAddress);
        //            string floor = i.ToString();
        //            var wcsTaskLog = dbContext.WcsTaskLog.FirstOrDefault(t => t.ud3 == "1" && t.ud2 == floor && t.containerNo == rifd);
        //            if (wcsTaskLog != null)
        //            {
        //                wcsTaskLogs.Add(wcsTaskLog);
        //            }
        //        }
        //        this.WcsTaskLogDataGrid.ItemsSource = wcsTaskLogs;
        //        this.WcsTaskLogDataGrid.Items.Refresh();
        //        if (wcsTaskLogs.Count == 0)
        //        {
        //            HandyControl.Controls.MessageBox.Show("未查询到数据");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        if (ex is PlcException)
        //        {
        //            try
        //            {
        //                SystemData.PlcDic[0] = new Plc.S7.Plc(SystemData.PlcDic[0].CPU, SystemData.PlcDic[0].IP, SystemData.PlcDic[0].Port, SystemData.PlcDic[0].Rack, SystemData.PlcDic[0].Slot);
        //                SystemData.PlcDic[0].Open();
        //                GetTaskLog();
        //            }
        //            catch
        //            {
        //                HandyControl.Controls.MessageBox.Show("PLC连接失败,无法读取任务");
        //            }
        //        }
        //    }

        //}

        private void GetTask()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            var equipCode = lba_ThrifTtitle1.Text;
            var palletNo = lba_ThrifTtitle2.Text;
            long? nextPointId = 0;
            if (this.EquipListSelectDy.SelectedItem is BaseEquip baseEquip)
            {
                nextPointId = baseEquip.objid;
            }
            var data = dbContext.WcsTask
                .WhereIf(nextPointId != 0, t => t.nextPointId == nextPointId)
                .Where(t => t.IsDelete != 1)
                .Where(t => t.containerNo.Contains(palletNo) && t.equipmentNo.Contains(equipCode)).ToList();
            List<taskModel> taskModel = CoreMapper.Map<List<taskModel>>(data);
            SelectedItem.Clear();
            foreach (var item in taskModel)
            {
                SelectedItem.Add(item.objid, false);
                if (item.nextPointId == 6)
                {
                    item.isShow = Visibility.Visible;
                }
                else
                {
                    item.isShow = Visibility.Collapsed;
                }
            }
            this.LoadMaterial0.ItemsSource = null;
            this.LoadMaterial0.ItemsSource = taskModel;
            this.LoadMaterial0.Items.Refresh();
            //if (data.Count == 0)
            //{
            //    HandyControl.Controls.MessageBox.Show("未查询到数据");
            //}
        }
        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelTask_Click(object sender, RoutedEventArgs e)
        {
            if (LoadMaterial0.SelectedIndex == -1)
            {
                HandyControl.Controls.MessageBox.Show("请选择要删除的任务!");
            }
            else
            {
                MessageBoxResult MessageBoxResult = HandyControl.Controls.MessageBox.Show("确定要删除这些任务吗？", "提示信息", MessageBoxButton.YesNo);
                if (MessageBoxResult == MessageBoxResult.Yes)
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    List<long?> ids = new List<long?>();
                    foreach (var item in SelectedItem)
                    {
                        if (item.Value == true)
                        {
                            ids.Add(item.Key);
                        }
                    }
                    BaseEquip agvEquip = SystemData.BaseEquip.First(t => t.objid == 10);
                    List<WcsTask> wcsTasks = dbContext.WcsTask.Where(t => ids.Contains(t.objid)).ToList();
                    foreach (var item in wcsTasks)
                    {
                        item.IsDelete = 1;
                        dbContext.Update(item);
                        dbContext.SaveChanges();
                    }
                    GetTask();
                }
                else
                {

                }

            }
        }
        /// <summary>
        /// 完成任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFinishTask_Click(object sender, RoutedEventArgs e)
        {
            if (LoadMaterial0.SelectedIndex == -1)
            {
                HandyControl.Controls.MessageBox.Show("请选择要完成的任务!");
            }
            else
            {
                var Currentselected = LoadMaterial0.SelectedItem as WcsTask;
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                Currentselected.taskStatus = 5;
                dbContext.WcsTask.Update(Currentselected);
                dbContext.SaveChanges();
                GetTask();
            }
        }
        /// <summary>
        /// 查询设备信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetEquip_Click(object sender, RoutedEventArgs e)
        {

            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            var equipCode = lba_ThrifTtitle3.Text;
            var data = dbContext.BaseEquip.Where(t => t.useFlag == 1 && t.equipNo.Contains(equipCode)).ToList();
            this.LoadMaterial3.ItemsSource = null;
            this.LoadMaterial3.ItemsSource = data;
            this.LoadMaterial3.Items.Refresh();
            if (data.Count == 0)
            {
                HandyControl.Controls.MessageBox.Show("未查询到数据");
            }
        }
        /// <summary>
        /// 查询库存信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetStocK_Click(object sender, RoutedEventArgs e)
        {
            Pagination1.PageIndex = 1;
            this.EquipListSelectDy.SelectedIndex = -1;
            locationDtos.Clear();
            GetBaseLocations();
        }
        /// <summary>
        /// 获取库位信息
        /// </summary>
        private void GetBaseLocations()
        {
            if (WarehourseId.SelectedItem is WmsBaseWarehouse warehouse)
            {
                var scope = _host.Services.CreateScope();
                var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var locationCode = lba_ThrifTtitle6.Text;
                string sql;
                if (productIds.Contains(warehouse.warehouseId))
                {
                    sql = $@"select distinct t1.location_id      LocationId,
                                                       t1.location_code    LocationCode,
                                                       t1.location_status  LocationStatus,
                                                       t1.warehouse_floor  FloorNo,
                                                       t2.pallet_info_code ContainerCode,
                                                       t2.material_id       MaterialId,
                                                       t2.sale_order_id    SaleOrderId
                                            from wms_base_location t1
                                                     left join wms_raw_stock t2
                                                               on t1.location_code = t2.location_code
                                            where t1.warehouse_id = {warehouse.warehouseId}";
                }
                else
                {
                    sql = $@"select distinct t1.location_id      LocationId,
                                   t1.location_code    LocationCode,
                                   t1.warehouse_floor  FloorNo,
                                   t1.location_status  LocationStatus,
                                   t2.pallet_info_code ContainerCode,
                                   t2.product_id       MaterialId,
                                   t2.sale_order_id    SaleOrderId
                            from wms_base_location t1
                                     left join wms_product_stock t2
                                               on t1.location_code = t2.location_code
                            where t1.warehouse_id = {warehouse.warehouseId}";
                }
                if (!string.IsNullOrEmpty(locationCode))
                {
                    sql += " and t1.location_code like '%" + locationCode + "%'";
                }
                if (!string.IsNullOrEmpty(this.locationStatus.SelectedItem?.ToString()))
                {
                    if (this.locationStatus.SelectedItem is ComboBoxItem item && !string.IsNullOrEmpty(item.Tag?.ToString()))
                    {
                        sql += " and t1.location_status = " + item.Tag + "";
                    }
                }
                var data = dbContext.ExecuteSqlQuery<LocationDto>(sql);
                int sum = data.Count;
                data = data.Skip((this.Pagination1.PageIndex - 1) * this.pageCount).Take(this.pageCount).ToList();
                data.ForEach(t =>
                {
                    t.LocationStatus = SystemData.LocationStatusDic.GetValueOrDefault(t.LocationStatus, "未知");
                });
                Pagination1.MaxPageCount = (sum / pageCount) + (sum % pageCount == 0 ? 0 : 1);
                this.LoadMaterial1.ItemsSource = null;
                this.LoadMaterial1.ItemsSource = data;
                this.LoadMaterial1.Items.Refresh();
                if (data.Count == 0)
                {
                    HandyControl.Controls.MessageBox.Show("未查询到数据");
                }
            }
            else
            {
                HandyControl.Controls.MessageBox.Show("请选择仓库!");
                return;
            }
        }
        ///// <summary>
        ///// 查询指令信息
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnGetWcsCmd_Click(object sender, RoutedEventArgs e)
        //{
        //    GetWcsCmd();
        //}
        //private void GetWcsCmd()
        //{
        //    using var scope = _host.Services.CreateScope();
        //    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
        //    var equipCode = txtEquipNo.Text;
        //    var ContainNo = txtContainNo.Text;
        //    var data = dbContext.WcsCmd.Where(t => t.useFlag == 1 && t.containerNo.Contains(ContainNo) && t.equipmentNo.Contains(equipCode)).ToList();
        //    this.LoadMaterial.ItemsSource = null;
        //    this.LoadMaterial.ItemsSource = data;
        //    this.LoadMaterial.Items.Refresh();
        //    if (data.Count == 0)
        //    {
        //        HandyControl.Controls.MessageBox.Show("未查询到数据");
        //    }
        //}
        ///// <summary>
        ///// 删除指令
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnDelCmd_Click(object sender, RoutedEventArgs e)
        //{
        //    if (LoadMaterial.SelectedIndex == -1)
        //    {
        //        HandyControl.Controls.MessageBox.Show("请选择要删除的指令!");
        //    }
        //    else
        //    {
        //        var Currentselected = LoadMaterial.SelectedItem as WcsCmd;
        //        using var scope = _host.Services.CreateScope();
        //        using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
        //        Currentselected.useFlag = 0;
        //        dbContext.WcsCmd.Update(Currentselected);
        //        dbContext.SaveChanges();
        //        GetWcsCmd();
        //    }
        //}
        ///// <summary>
        ///// 重发指令
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnReSendCmd_Click(object sender, RoutedEventArgs e)
        //{
        //    if (LoadMaterial.SelectedIndex == -1)
        //    {
        //        HandyControl.Controls.MessageBox.Show("请选择要重发的指令!");
        //    }
        //    else
        //    {
        //        var Currentselected = LoadMaterial.SelectedItem as WcsCmd;
        //        using var scope = _host.Services.CreateScope();
        //        using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
        //        Currentselected.sendFlag = 0;
        //        dbContext.WcsCmd.Update(Currentselected);
        //        dbContext.SaveChanges();
        //        GetWcsCmd();
        //    }
        //}
        ///// <summary>
        ///// 呼叫料箱
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnCallBox_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(callMaterialId.Text))
        //        {
        //            using var scope = _host.Services.CreateScope();
        //            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

        //            if (int.TryParse(txtNum.Text, out int num))
        //            {
        //                WmsRawOutstock wmsRawOutstock = new WmsRawOutstock()
        //                {
        //                    rawOutstockId = _jcSnowId.NextId(),
        //                    taskCode = "task",
        //                    warehouseId = 512,
        //                    materialId = Convert.ToInt32(callMaterialId.Text),
        //                    outstockAmount = Convert.ToInt32(txtNum.Text),
        //                    realOutstockAmount = 0,
        //                    endStationCode = "FL052",
        //                    auditStatus = "0",
        //                    operationType = "1",
        //                    taskType = "1",
        //                    executeStatus = "0"
        //                };
        //                dbContext.Add(wmsRawOutstock);
        //                dbContext.SaveChanges();
        //                HandyControl.Controls.MessageBox.Show("料箱呼叫任务添加成功!");
        //            }
        //            else
        //            {
        //                HandyControl.Controls.MessageBox.Show("请输入有效的数字");
        //            }
        //        }
        //    }
        //    catch
        //    {

        //    }
        //}
        /// <summary>
        /// 料箱扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void txtBox_KeyDown(object sender, KeyEventArgs e)
        //{
        //    if (e.Key == Key.Enter)
        //    {
        //        txtBarCode.Focus();
        //    }
        //}
        ///// <summary>
        ///// 条码扫描
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void txtBarCode_KeyDown(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(txtBarCode.Text))
        //        {
        //            if (!(barcodeLsit.Where(t => t.barcodeInfo == txtBarCode.Text).Count() > 0))
        //            {
        //                using var scope = _host.Services.CreateScope();
        //                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
        //                var mesInfo = dbContext.MesBaseBarcodeInfo.Where(t => t.barcodeInfo == txtBarCode.Text).FirstOrDefault();
        //                if (mesInfo == null)
        //                {
        //                    HandyControl.Controls.MessageBox.Show("请扫描正确的条码");
        //                    return;
        //                }
        //                barcodeLsit.Add(mesInfo);
        //                txtBarCode.SelectAll();
        //                txtBarCode.Focus();
        //                txtScan.Text = $"{(mesInfo.batchFlag == "1" ? 1 : mesInfo.amount)}";
        //            }
        //        }
        //    }
        //    catch
        //    {

        //    }

        //}
        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfirmBox_Click(object sender, RoutedEventArgs e)
        {
            //try
            //{
            //    var box = txtBox.Text;
            //    if (string.IsNullOrEmpty(box))
            //    {
            //        HandyControl.Controls.MessageBox.Show("容器号不能为空!");
            //        return;
            //    }
            //    if (barcodeLsit.Count == 0)
            //    {
            //        HandyControl.Controls.MessageBox.Show("未扫描条码!");
            //        return;
            //    }
            //    using var scope = _host.Services.CreateScope();
            //    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            //    WmsBaseLocation? wmsBaseLocation = dbContext.WmsBaseLocation.Where(t => t.warehouseId == 512 && t.containerCode == box).FirstOrDefault();
            //    if (wmsBaseLocation == null)
            //    {
            //        HandyControl.Controls.MessageBox.Show("容器号不存在!,请重新扫描!");
            //        return;
            //    }
            //    if (cbxType.Text == "入库")
            //    {
            //        var batchCodes = barcodeLsit.Select(t => t.batchCode);
            //        List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock
            //            .Where(t => batchCodes.Contains(t.instockBatch))
            //            .Where(t => t.warehouseFloor == 5 && t.warehouseId == 512).ToList();
            //        if (wmsRawStocks.Count > 0)
            //        {
            //            HandyControl.Controls.MessageBox.Show("该批次已入库!");
            //            return;
            //        }
            //        foreach (var item in barcodeLsit)
            //        {
            //            WmsRawStock? wmsRawStock = dbContext.WmsRawStock
            //                .Where(t => t.palletInfoCode == box)
            //                .Where(t => t.instockBatch == item.batchCode).FirstOrDefault();
            //            if (wmsRawStock == null)
            //            {
            //                var newRawStock = new WmsRawStock()
            //                {
            //                    materialId = item.materialId,
            //                    supplierId = item.manufacturerId,
            //                    instockBatch = item.batchCode,
            //                    locationCode = wmsBaseLocation.locationCode,
            //                    stockType = "1",
            //                    palletInfoCode = box,
            //                    totalAmount = item.batchFlag == "1" ? 1 : item.amount,
            //                    activeFlag = "1",
            //                    occupyAmount = 0,
            //                    completeFlag = "1",
            //                    frozenAmount = 0,
            //                    instockDate = System.DateTime.Now,
            //                    rawStockId = Global.SnowId.NextId(),
            //                    saleOrderId = item.saleOrderId,
            //                    warehouseFloor = 5,
            //                    warehouseId = 512,
            //                    createBy = "扫描入库",
            //                    createDate = System.DateTime.Now
            //                };
            //                dbContext.WmsRawStock.Add(newRawStock);
            //            }
            //            else
            //            {
            //                HandyControl.Controls.MessageBox.Show("该批次已入库!");
            //                return;
            //            }
            //        }
            //        dbContext.SaveChanges();
            //        HandyControl.Controls.MessageBox.Show("入库成功!");
            //    }
            //    if (cbxType.Text == "出库")
            //    {
            //        long? materialId = barcodeLsit.FirstOrDefault().materialId;
            //        WmsRawOutstock? wmsRawOutstock = dbContext.WmsRawOutstock
            //            .Where(t => t.auditStatus == "1")
            //            .Where(t => t.executeStatus == "1")
            //            .Where(t => t.warehouseId == 512)
            //            .Where(t => t.realOutstockAmount < t.outstockAmount)
            //            .Where(t => t.materialId == materialId)
            //            .FirstOrDefault();
            //        if (wmsRawOutstock != null)
            //        {
            //            //从料箱里拿出来
            //            WmsRawStock? wmsRawStock = dbContext.WmsRawStock.Where(t => t.palletInfoCode == box).Where(t => t.materialId == materialId).FirstOrDefault();
            //            if (wmsRawStock != null)
            //            {
            //                dbContext.WmsRawStock.Where(t => t.rawStockId == wmsRawStock.rawStockId).Delete();
            //                wmsRawOutstock.realOutstockAmount += 1;
            //                if (wmsRawOutstock.realOutstockAmount >= wmsRawOutstock.outstockAmount)
            //                {
            //                    wmsRawOutstock.executeStatus = "2";
            //                    wmsRawOutstock.endTime = DateTime.Now;
            //                }
            //                dbContext.Update(wmsRawOutstock);
            //                dbContext.SaveChanges();
            //            }
            //            else
            //            {
            //                HandyControl.Controls.MessageBox.Show("当前容器不存在当前扫描物料");
            //            }
            //        }

            //    }
            //    if (cbxType.Text == "回库")
            //    {
            //        var batchCodes = barcodeLsit.Select(t => t.batchCode);
            //        List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock
            //            .Where(t => batchCodes.Contains(t.instockBatch))
            //            .Where(t => t.warehouseFloor == 5 && t.warehouseId == 512).ToList();
            //        if (wmsRawStocks.Count > 0)
            //        {
            //            HandyControl.Controls.MessageBox.Show("该批次已入库!");
            //            return;
            //        }
            //        foreach (var item in barcodeLsit)
            //        {
            //            WmsRawStock? wmsRawStock = dbContext.WmsRawStock
            //                .Where(t => t.palletInfoCode == box)
            //                .Where(t => t.instockBatch == item.batchCode).FirstOrDefault();
            //            if (wmsRawStock == null)
            //            {
            //                var newRawStock = new WmsRawStock()
            //                {
            //                    materialId = item.materialId,
            //                    supplierId = item.manufacturerId,
            //                    instockBatch = item.batchCode,
            //                    locationCode = wmsBaseLocation.locationCode,
            //                    stockType = "1",
            //                    palletInfoCode = box,
            //                    totalAmount = item.batchFlag == "1" ? 1 : item.amount,
            //                    activeFlag = "1",
            //                    occupyAmount = 0,
            //                    completeFlag = "1",
            //                    frozenAmount = 0,
            //                    instockDate = System.DateTime.Now,
            //                    rawStockId = Global.SnowId.NextId(),
            //                    saleOrderId = item.saleOrderId,
            //                    warehouseFloor = 5,
            //                    warehouseId = 512,
            //                    createBy = "扫描回库",
            //                    createDate = System.DateTime.Now
            //                };
            //                dbContext.WmsRawStock.Add(newRawStock);
            //            }
            //            else
            //            {
            //                HandyControl.Controls.MessageBox.Show("该批次已入库!");
            //                return;
            //            }
            //        }
            //        dbContext.SaveChanges();
            //        HandyControl.Controls.MessageBox.Show("回库成功!");
            //    }
            //    barcodeLsit.Clear();
            //    txtScan.Text = string.Empty;
            //    txtBarCode.Text = string.Empty;
            //}
            //catch
            //{

            //}

        }
        /// <summary>
        /// 退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowClose_Click(object sender, RoutedEventArgs e)
        {
            if (HandyControl.Controls.MessageBox.Show("是否确认关闭程序", "提示信息", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                Application.Current.Shutdown();
                System.Environment.Exit(System.Environment.ExitCode);
            }
        }
        /// <summary>
        /// 获取聚焦打开键盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBoxGetFocus()
        {
            try
            {
                Process process = new Process()
                {
                    StartInfo ={
                        UseShellExecute=true,
                        FileName="osk.exe"
                    }
                };
                process.Start();
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error("打开软键盘时出错: " + ex.Message);
            }
        }
        /// <summary>
        /// 失去焦点,关闭软键盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBoxLostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                //将打开的osk.exe进程关闭
                Process[] processes = Process.GetProcessesByName("osk");
                foreach (Process process in processes)
                {
                    process.Kill();
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error("打开软键盘时出错: " + ex.Message);
            }
        }
        /// <summary>
        /// 背负式小车确认完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBearConfirmBox_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show("是否确认捡料完成？", "提示信息", MessageBoxButton.YesNo, MessageBoxImage.Information);
                if (messageBoxResult == MessageBoxResult.Yes)
                {
                    //剩余出库单
                    int count = OutTaskNumber.Items.Count;
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

                    var wcsCmd = dbContext.WcsTask
                        .Where(t => t.taskStatus == 6 || t.taskStatus == 3)
                        .Where(t => t.nextPointId == 10)
                        .FirstOrDefault();
                    if (wcsCmd == null)
                    {
                        HandyControl.Controls.MessageBox.Error("未查询到当前有背负式Agv由装配区到捡料区任务");
                    }
                    else
                    {
                        if (wcsCmd.taskType == 32)//领料
                        {
                            if (count > 0)
                            {
                                MessageBoxResult messageBoxResult1 = HandyControl.Controls.MessageBox.Show("是否需要背负式小车返回？", "提示信息", MessageBoxButton.YesNoCancel, MessageBoxImage.Information);
                                if (messageBoxResult1 == MessageBoxResult.Yes)
                                {
                                    WcsTask wcsTask = CoreMapper.Map<WcsTask>(wcsCmd);
                                    wcsTask.taskStatus = 0;
                                    wcsTask.createTime = DateTime.Now;
                                    wcsTask.useFlag = 1;
                                    wcsTask.objid = Global.SnowId.NextId();
                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                    dbContext.Add(wcsTaskLog);
                                    dbContext.Add(wcsTask);
                                }
                                else
                                {
                                    BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 10);
                                    baseEquip.endStationCode = string.Empty;
                                    baseEquip.ud3 = null;
                                    dbContext.Update(baseEquip);

                                }

                            }
                            else
                            {
                                BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 10);
                                baseEquip.endStationCode = string.Empty;
                                baseEquip.ud3 = null;
                                dbContext.Update(baseEquip);
                                dbContext.SaveChanges();

                            }

                            if (wcsCmd.taskStatus == 3)
                            {
                                wcsCmd.taskStatus = 4;
                            }
                        }
                        else if (wcsCmd.taskType == 48)//返库
                        {
                            if (wcsCmd.taskStatus == 6)
                            {
                                wcsCmd.taskStatus = 7;
                            }
                        }
                        dbContext.Update(wcsCmd);
                        dbContext.SaveChanges();
                        HandyControl.Controls.MessageBox.Success("背负式Agv任务确认完成成功");
                    }
                }

            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
            }
        }
        /// <summary>
        /// 获取到所有控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 获取当前选中的TabItem
            var selectedTabItem = TabControl.SelectedItem as TabItem;


            //if (selectedTabItem != null && selectedTabItem.Name == "TaskManager")
            //{  //任务界面

            //    GetTask();
            //}
             if (selectedTabItem != null && selectedTabItem.Name == "CallPersonManager")
            { //人工叫料界面
                CallSelectedItem.Clear();
                await GetPersonCallMaterialData();
            }
            else if (selectedTabItem != null && selectedTabItem.Name == "InventoryManager")
            {  //盘库界面
                GetInvertoryData();
            }
        }
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddTaskButton_Click(object sender, RoutedEventArgs e)
        {
            AddTask addTask = new AddTask(_host);
            addTask.ShowDialog();
        }
        ///// <summary>
        ///// 清除RFID
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void clearRFID_Click(object sender, RoutedEventArgs e)
        //{
        //    txtBox.Text = string.Empty;
        //}
        ///// <summary>
        ///// 清除条码
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void clearBarCode_Click(object sender, RoutedEventArgs e)
        //{
        //    txtScan.Text = string.Empty;
        //    barcodeLsit.Clear();
        //    txtBarCode.Text = string.Empty;
        //}
        ///// <summary>
        ///// 人工叫料失去焦点
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void callMaterialId_LostFocus(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(callMaterialId.Text))
        //        {
        //            using var scope = _host.Services.CreateScope();
        //            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
        //            var material = dbContext.WmsRawStock.Where(t => t.instockBatch == callMaterialId.Text).FirstOrDefault();
        //            if (material == null)
        //            {
        //                HandyControl.Controls.MessageBox.Show("批次号不存在!");
        //                callMaterialId.Text = string.Empty;
        //            }
        //            else
        //            {

        //            }
        //        }
        //    }
        //    catch
        //    {

        //    }

        //}
        /// <summary>
        /// 开始任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditTask_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (LoadMaterial0.SelectedIndex == -1)
                {
                    HandyControl.Controls.MessageBox.Show("请选择要开始的任务!");
                }
                else
                {
                    var Currentselected = LoadMaterial0.SelectedItem as WcsTask;
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    List<WcsTask> wcsTasks = dbContext.WcsTask.ToList();
                    List<long> ids = new List<long>();
                    foreach (var item in SelectedItem)
                    {
                        if (item.Value == true)
                        {
                            WcsTask? wcsTask = wcsTasks.FirstOrDefault();
                            if (wcsTask != null && wcsTask.taskStatus <= 0)
                            {
                                ids.Add(item.Key);
                            }
                        }
                    }
                    dbContext.WcsTask.Where(t => ids.Contains(t.objid)).Update(t => new WcsTask { useFlag = 1 });
                    GetTask();
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
            }

        }
        /// <summary>
        /// 单选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox checkbox && LoadMaterial0.SelectedItem is taskModel Currentselected)
            {
                SelectedItem[Currentselected.objid] = checkbox.IsChecked ?? false;
            }
        }
        /// <summary>
        /// 单选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckPersonBox_Click(object sender, RoutedEventArgs e)
        {

            if (sender is CheckBox checkbox)
            {
                dynamic Currentselected = PersonCallMaterial.SelectedItem;
                if (checkbox.IsChecked != null && checkbox.IsChecked.Value)
                {
                    if (itemsControlItems != null && itemsControlItems.Count >= 6)
                    {
                        MessageBox.Show("最多只能选择6个");
                        checkbox.IsChecked = false;
                        return;
                    }
                    CallSelectedItem.Add(Currentselected.baseLocationId);

                    // 添加选中项
                    string selectedItem = Currentselected.palletInfoCode;

                    bool isIn = itemsControlItems.Any(t => t.baseLocationId == Currentselected.baseLocationId);
                    if (!isIn)
                    {
                        itemsControlItems.Add(new SelectItemModel
                        {
                            baseLocationId = Currentselected.baseLocationId,
                            palletInfoCode = Currentselected.palletInfoCode
                        });

                    }
                }
                else
                {
                    CallSelectedItem.Remove(Currentselected.baseLocationId);


                    // 删除选中项
                    SelectItemModel model = itemsControlItems.FirstOrDefault(x => x.baseLocationId == Currentselected.baseLocationId);
                    if (model != null)
                    {
                        itemsControlItems.Remove(model);
                    }
                }




            }
        }

        /// <summary>
        /// 删除选中的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            // 获取点击按钮的实例
            Button button = sender as Button;

            // 从按钮的 Tag 属性中获取当前数据项
            SelectItemModel itemToRemove = button.Tag as SelectItemModel;

            if (itemToRemove != null)
            {
                // 从集合中移除数据项
                itemsControlItems.Remove(itemToRemove);
            }
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshPlc()
        {
            while (true)
            {
                try
                {
                    var points = SystemData.BasePlcpoints.OrderBy(t => t.definefield3).ToList();
                    foreach (var item in points)
                    {
                        if (!string.IsNullOrEmpty(item.plcpointAddress))
                        {
                            TextBlock? textBlock = null;
                            Dispatcher.Invoke(() =>
                            {
                                textBlock = this.FindName(item.plcpointNo) as TextBlock;
                            });
                            if (textBlock != null)
                            {
                                var plc = SystemData.PlcDic.Values.Where(t => t.IP == item.definefield3).FirstOrDefault();
                                if (plc != null)
                                {
                                    try
                                    {
                                        string? result = "";
                                        if (item.plcpointNo.Contains("RFID"))
                                        {
                                            result = plc.ReadRFID(item.plcpointAddress)?.ToString();
                                        }
                                        else
                                        {
                                            result = plc.Read(item.plcpointAddress)?.ToString();
                                        }
                                        Dispatcher.Invoke(() =>
                                        {
                                            textBlock.Text = result == null ? "" : result;
                                        });
                                    }
                                    catch (Exception ex)
                                    {
                                        try
                                        {
                                            if (ex is PlcException)
                                            {
                                                foreach (var item2 in SystemData.PlcDic)
                                                {
                                                    if (item2.Value.IP == ex.Message)
                                                    {
                                                        SystemData.PlcDic[item2.Key] = new Plc.S7.Plc(item2.Value.CPU, item2.Value.IP, item2.Value.Port, item2.Value.Slot, item2.Value.Rack);
                                                        SystemData.PlcDic[item2.Key].Open();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        catch
                                        {
                                            points.RemoveAll(t => t.definefield3 == ex.Message);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
                Thread.Sleep(3000);
            }

        }
        /// <summary>
        /// 开始任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCtuInConfirmBox_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                WcsTask? wcsTask = dbContext.WcsTask.FirstOrDefault(t => t.nextPointId == 11 && t.taskType == 29);
                if (wcsTask == null)
                {
                    HandyControl.Controls.MessageBox.Info("未查询到当前有CTU入库任务!");
                }
                else
                {
                    wcsTask.CTUExecute = "1";
                    dbContext.WcsTask.Update(wcsTask);
                    dbContext.SaveChanges();
                    HandyControl.Controls.MessageBox.Info("CTU入库任务确认完成成功!");
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 页码改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pagination_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            GetBaseLocations();
        }
        /// <summary>
        /// 物料名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MaterialName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if(MaterialName.SelectedItem is MesBaseMaterialInfo Currentselected)
            //{
            //    MaterialSpec.ItemsSource = SystemData.MesBaseMaterialInfo.Where(t => t.MaterialName == Currentselected.MaterialName);
            //}
            //else
            //{
            //    MaterialSpec.ItemsSource = null;
            //}
            //MaterialSpec.Items.Refresh();
        }
        /// <summary>
        /// 入库扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InRawBaseLocaltion_Click(object sender, RoutedEventArgs e)
        {
            ScanInBox();
        }

        private void ScanInBox()
        {
            try
            {

                if (!string.IsNullOrEmpty(txtInBox.Text) && !string.IsNullOrEmpty(txtInBarCode.Text))
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    if (txtInScan.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Error("请先输入数量"); return;
                    }
                    decimal amount = decimal.Parse(txtInScan.Text);
                    // 计算入库后当前总数量，仅用来提示使用
                    decimal? totalMessage = 0;
                    if (amount <= 0)
                    {
                        HandyControl.Controls.MessageBox.Error("入库数量需大于0");
                        return;
                    }
                    var material = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == txtInBarCode.Text);

                    var container = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == txtInBox.Text && t.warehouseId == 512);
                    List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock
                        .Where(t => txtInBarCode.Text == t.instockBatch)
                        .Where(t => t.warehouseFloor == 5 && t.warehouseId == 512).ToList();
                    if (container == null)
                    {
                        MsgText.Text = "未查询到该容器!";
                        txtInBox.Focus();
                        txtInBox.Text = string.Empty;
                        txtInBarCode.Text = string.Empty;
                        txtInScan.Text = string.Empty;

                        return;
                    }
                    if (material == null)
                    {
                        MsgText.Text = "未查询到该条码内容!";
                        txtInBox.Text = string.Empty;
                        txtInBarCode.Text = string.Empty;
                        txtInScan.Text = string.Empty;
                        txtInBox.Focus();
                        return;
                    }

                    if (wmsRawStocks.Count > 0)
                    {
                        if (material.batchFlag != "1")
                        {
                            MsgText.Text = $"该条码已入库!料箱号为{wmsRawStocks.First().palletInfoCode},库位号为{wmsRawStocks.First().locationCode}";
                            txtInBox.Text = string.Empty;
                            txtInBarCode.Text = string.Empty;
                            txtInScan.Text = string.Empty;
                            txtInBox.Focus();
                            return;
                        }
                        else
                        {
                            WmsRawStock wmsRawStock = wmsRawStocks.First();
                            wmsRawStock.totalAmount += amount;
                            dbContext.WmsRawStock.Update(wmsRawStock);

                            var mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == txtInBarCode.Text);
                            WmsRawInstock wmsRawInstock = new WmsRawInstock()
                            {
                                taskCode = Global.SnowId.NextId().ToString(),
                                materialBarCode = mesBaseBarcodeInfo.barcodeInfo,
                                materialBatchCode = mesBaseBarcodeInfo.batchCode,
                                applyBy = "WPF",
                                applyDate = System.DateTime.Now,
                                purchaseOrderId = mesBaseBarcodeInfo.PurchaseOrderId,

                                beginTime = System.DateTime.Now,
                                endTime = DateTime.Now,
                                locationCode = container.locationCode,
                                executeStatus = "2",
                                instockAmount = amount,
                                instockType = "1",
                                materialId = material.materialId,
                                operationType = "1",
                                palletInfoCode = container.containerCode,
                                poNo = mesBaseBarcodeInfo.poNo,
                                warehouseId = 512
                            };

                            dbContext.WmsRawInstock.Add(wmsRawInstock);
                            dbContext.SaveChanges();
                            totalMessage = wmsRawStock.totalAmount;
                        }
                    }
                    else
                    {
                        var newRawStock = new WmsRawStock()
                        {
                            materialId = material.materialId,
                            supplierId = material.manufacturerId,
                            instockBatch = txtInBarCode.Text,
                            locationCode = container.locationCode,
                            stockType = "1",
                            palletInfoCode = container.containerCode,
                            totalAmount = material.batchFlag == "1" ? amount : 1,
                            activeFlag = "1",
                            occupyAmount = 0,
                            completeFlag = "1",
                            frozenAmount = 0,
                            instockDate = System.DateTime.Now,
                            rawStockId = Global.SnowId.NextId(),
                            saleOrderId = material.saleOrderId == null ? 0 : material.saleOrderId,
                            warehouseFloor = 5,
                            warehouseId = 512,
                            createBy = "扫描入库",
                            createDate = System.DateTime.Now,
                            safeFlag = material.safeFlag
                        };
                        dbContext.WmsRawStock.Add(newRawStock);

                        var mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == txtInBarCode.Text);
                        WmsRawInstock wmsRawInstock = new WmsRawInstock()
                        {
                            taskCode = Global.SnowId.NextId().ToString(),
                            materialBarCode = mesBaseBarcodeInfo.barcodeInfo,
                            materialBatchCode = mesBaseBarcodeInfo.batchCode,
                            applyBy = "WPF",
                            applyDate = System.DateTime.Now,
                            purchaseOrderId = mesBaseBarcodeInfo.PurchaseOrderId,

                            beginTime = System.DateTime.Now,
                            endTime = DateTime.Now,
                            locationCode = container.locationCode,
                            executeStatus = "2",
                            instockAmount = amount,
                            instockType = "1",
                            materialId = material.materialId,
                            operationType = "1",
                            palletInfoCode = container.containerCode,
                            poNo = mesBaseBarcodeInfo.poNo,
                            warehouseId = 512
                        };
                        dbContext.WmsRawInstock.Add(wmsRawInstock);
                        dbContext.SaveChanges();
                        totalMessage = newRawStock.totalAmount;
                    }


                    txtInBox.Focus();
                    MsgText.Text = $"入库成功!当前库存:{totalMessage}";
                    txtInBox.Text = string.Empty;
                    txtInBarCode.Text = string.Empty;
                    txtInScan.Text = string.Empty;

                }
                else
                {
                    MsgText.Text = "请先扫描容器号和条码!";
                }
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
                txtInBox.Text = string.Empty;
                txtInBarCode.Text = string.Empty;
                txtInScan.Text = string.Empty;
                MsgText.Text = "入库失败";
                txtInBarCode.Focus();
            }
        }

        private void rawSourceBoxClear_Click(object sender, RoutedEventArgs e)
        {
            this.rawSourceBox.Text = string.Empty;
        }
        private void removeSourceBoxClear_Click(object sender, RoutedEventArgs e)
        {
            this.removeSourceBox.Text = string.Empty;
        }

        private void rawSourceBarCodeClear_Click(object sender, RoutedEventArgs e)
        {
            this.rawSourceBarCode.Text = string.Empty;
        }

        private void removeSourceBarCodeClear_Click(object sender, RoutedEventArgs e)
        {
            this.removeSourceBarCode.Text = string.Empty;
        }
        /// <summary>
        /// 入库扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReturnRawBaseLocaltion_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(txtInBox.Text) && !string.IsNullOrEmpty(txtInBarCode.Text))
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    WmsRawReturn? wmsRawReturn = dbContext.WmsRawReturn.Where(t => t.executeStatus == "1").FirstOrDefault();
                    if (wmsRawReturn == null)
                    {
                        HandyControl.Controls.MessageBox.Show("未查询到退库任务!");
                        return;
                    }
                    var material = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == txtInBarCode.Text);
                    var container = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == txtInBox.Text && t.warehouseId == 512);
                    List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock
                        .Where(t => txtInBarCode.Text == t.instockBatch)
                        .Where(t => t.warehouseFloor == 5 && t.warehouseId == 512).ToList();
                    if (wmsRawStocks.Count > 0 && material.batchFlag != "1")
                    {
                        HandyControl.Controls.MessageBox.Info($"该条码已入库!料箱号为{wmsRawStocks.First().palletInfoCode},库位号为{wmsRawStocks.First().locationCode}");
                        txtInBarCode.Text = string.Empty;
                        txtInScan.Text = string.Empty;
                        return;
                    }
                    if (container == null)
                    {
                        HandyControl.Controls.MessageBox.Error("未查询到该容器!");
                        txtInBox.Text = string.Empty;
                        return;
                    }
                    if (material == null)
                    {
                        HandyControl.Controls.MessageBox.Error("未查询到该条码内容!");
                        txtInBarCode.Text = string.Empty;
                        txtInScan.Text = string.Empty;
                        return;
                    }

                    decimal amount = decimal.Parse(txtInScan.Text);
                    wmsRawReturn.returnAmount += amount;
                    if (wmsRawReturn.returnAmount >= wmsRawReturn.planAmount)
                    {
                        wmsRawReturn.executeStatus = "2";
                        wmsRawReturn.endTime = DateTime.Now;
                    }

                    WmsRawReturnDetail? wmsRawReturnDetail = new WmsRawReturnDetail();
                    wmsRawReturnDetail.RawReturnId = (long)wmsRawReturn.rawReturnId;
                    wmsRawReturnDetail.LocationCode = container.locationCode;
                    wmsRawReturnDetail.MaterialBarcode = txtInBarCode.Text;
                    wmsRawReturnDetail.MaterialId = (long)material.materialId;
                    wmsRawReturnDetail.InstockBatch = material.batchCode;
                    wmsRawReturnDetail.MaterialProductionDate = material.productionDate;
                    wmsRawReturnDetail.PlanAmount = wmsRawReturn.planAmount;
                    wmsRawReturnDetail.ReturnAmount = wmsRawReturn.returnAmount;
                    wmsRawReturnDetail.ExecuteStatus = "2";
                    wmsRawReturnDetail.ReturnAmount = wmsRawReturn.returnAmount;
                    wmsRawReturnDetail.ReturnPerson = "WPF";
                    wmsRawReturnDetail.ReturnTime = DateTime.Now;
                    wmsRawReturnDetail.ReturnWay = "2";
                    wmsRawReturnDetail.CreateBy = "WPF";
                    wmsRawReturnDetail.CreateDate = DateTime.Now;


                    if (wmsRawStocks.Count > 0)
                    {  // 批次条码并且有库存
                        var newRawStock = wmsRawStocks.First();
                        newRawStock.totalAmount += amount;
                        newRawStock.updateDate = DateTime.Now;
                        dbContext.WmsRawStock.Update(newRawStock);
                    }
                    else
                    { // 无库存
                        var newRawStock = new WmsRawStock()
                        {
                            materialId = material.materialId,
                            supplierId = material.manufacturerId,
                            instockBatch = txtInBarCode.Text,
                            locationCode = container.locationCode,
                            stockType = "1",
                            palletInfoCode = container.containerCode,
                            totalAmount = material.batchFlag == "1" ? amount : 1,
                            activeFlag = "1",
                            occupyAmount = 0,
                            completeFlag = "1",
                            frozenAmount = 0,
                            instockDate = System.DateTime.Now,
                            rawStockId = Global.SnowId.NextId(),
                            saleOrderId = material.saleOrderId == null ? 0 : material.saleOrderId,
                            warehouseFloor = 5,
                            warehouseId = 512,
                            createBy = "扫描退库",
                            createDate = System.DateTime.Now,
                            safeFlag = material.safeFlag
                        };
                        dbContext.WmsRawStock.Add(newRawStock);
                    }

                    dbContext.SaveChanges();
                    HandyControl.Controls.MessageBox.Success("入库成功!");
                    txtInBarCode.Text = string.Empty;
                    txtInScan.Text = string.Empty;
                    txtInBarCode.Focus();
                }
                else
                {
                    HandyControl.Controls.MessageBox.Info("请先扫描容器号和条码!");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
                HandyControl.Controls.MessageBox.Error("入库失败");
            }
        }
        /// <summary>
        /// 入库容器改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInBox_TextChanged(object sender, RoutedEventArgs e)
        {
            try
            {

                string containerCode = txtInBox.Text;
                if (containerCode.Length >= 1) MsgText.Text = string.Empty;
                if (containerCode.Length < 15)
                    return;
                if (!string.IsNullOrEmpty(containerCode))
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    var container = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == containerCode && t.warehouseId == 512);
                    if (container == null)
                    {
                        MsgText.Text = $"未查询到该容器{txtInBox.Text}!";
                        txtInBox.Text = string.Empty;
                        txtInBox.Focus();
                    }
                    else
                    {
                        txtInBarCode.Focus();
                    }
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 入库条码改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInBarCode_TextChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                materialName.Text = string.Empty;
                materialSpec.Text = string.Empty;
                string barCode = txtInBarCode.Text;
                if (barCode.Length < 19) return;


                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

                if (!string.IsNullOrEmpty(barCode))
                {


                    var material = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == barCode);
                    if (material == null)
                    {
                        MsgText.Text = "未查询到该条码内容!";
                        txtInBarCode.Text = string.Empty;
                        txtInScan.Text = string.Empty;
                        txtInBarCode.Focus();
                    }
                    else
                    {
                        var mesBaseMaterialInfo = dbContext.MesBaseMaterialInfo.FirstOrDefault(t => t.MaterialId == material.materialId);
                        if (mesBaseMaterialInfo == null)
                        {
                            MsgText.Text = "未查询到该条码绑定的物料信息!";
                            txtInBarCode.Text = string.Empty;
                            txtInScan.Text = string.Empty;
                            txtInBarCode.Focus();
                        }
                        else
                        {

                            txtInScan.Text = (material.batchFlag == "1") ? "" : "1.00";
                            materialName.Text = mesBaseMaterialInfo.MaterialName;
                            materialSpec.Text = mesBaseMaterialInfo.MaterialSpec;
                            if (mesBaseMaterialInfo.BatchFlag == "0")
                            {
                                txtInScan.IsReadOnly = true;
                            }
                            else
                            {
                                txtInScan.IsReadOnly = false;
                            }
                            txtInScan.Focus();
                        }
                    }
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 出库容器改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtReturnBox_TextChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                string containerCode = txtReturnBox.Text;
                if (!string.IsNullOrEmpty(containerCode))
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    var container = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == containerCode && t.warehouseId == 512);
                    if (container == null)
                    {
                        MsgText.Text = $"未查询到该容器{txtReturnBox.Text}!";
                        txtReturnBox.Text = string.Empty;
                        txtReturnBox.Focus();
                    }
                    else
                    {
                        txtReturnBarCode.Focus();
                    }
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 出库条码改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtReturnBarCode_TextChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                string barCode = txtReturnBarCode.Text;
                if (barCode.Length < 19) return;

                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

                if (!string.IsNullOrEmpty(barCode))
                {
                    var material = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == barCode);
                    if (material == null)
                    {
                        txtReturnBarCode.Text = string.Empty;
                        txtReturnScan.Text = string.Empty;
                        txtReturnBarCode.Focus();
                    }
                    else
                    {
                        var mesBaseMaterialInfo = dbContext.MesBaseMaterialInfo.FirstOrDefault(t => t.MaterialId == material.materialId);
                        if (mesBaseMaterialInfo == null)
                        {
                            txtReturnBarCode.Text = string.Empty;
                            txtReturnScan.Text = string.Empty;
                            txtReturnBarCode.Focus();
                        }
                        else
                        {

                            txtReturnScan.Text = (material.batchFlag == "1") ? "" : "1.00";


                            if (mesBaseMaterialInfo.BatchFlag == "0")
                            {
                                txtReturnScan.IsReadOnly = true;
                            }
                            else
                            {
                                txtReturnScan.IsReadOnly = false;
                            }
                        }
                    }
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 出库容器改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtOutBox_TextChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                string containerCode = txtOutBox.Text;

                if (containerCode.Length >= 1 && containerCode.Length < 15)
                {
                    scanOutMsg.Text = "";
                    return;
                }

                if (!string.IsNullOrEmpty(containerCode))
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    var container = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == containerCode && t.warehouseId == 512);
                    if (container == null)
                    {
                        scanOutMsg.Text = $"未查询到该容器{txtOutBox.Text}!";
                        txtOutBox.Text = string.Empty;
                        txtOutBox.Focus();
                    }
                    else
                    {
                        txtOutBarCode.Focus();
                    }
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 出库条码改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtOutBarCode_TextChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                txtTotalAmount.Text = "";
                outMaterialNameTxt.Text = "";
                outMaterialSpecTxt.Text = "";
                txtOutScan.Text = "";
                string barCode = txtOutBarCode.Text;
                string containerCode = txtOutBox.Text;
                if (barCode.Length < 19) return;
                if (!string.IsNullOrEmpty(containerCode))
                {
                    if (!string.IsNullOrEmpty(barCode))
                    {
                        using var scope = _host.Services.CreateScope();
                        using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                        var wmsRawStock = dbContext.WmsRawStock.FirstOrDefault(t => t.instockBatch == barCode && t.palletInfoCode == containerCode);
                        if (wmsRawStock == null)
                        {
                            scanOutMsg.Text = "未在该容器中查询到该条码!";
                            txtOutBarCode.Text = string.Empty;
                            txtOutScan.Text = string.Empty;
                            txtOutBarCode.Focus();
                        }
                        else
                        {
                            var mesBaseMaterialInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == wmsRawStock.instockBatch);
                            if (mesBaseMaterialInfo == null)
                            {
                                scanOutMsg.Text = "未查询到该条码绑定的物料信息!";
                                txtOutBarCode.Text = string.Empty;
                                txtOutScan.Text = string.Empty;
                                txtOutBarCode.Focus();
                            }


                            else
                            {
                                var materialInfo = dbContext.MesBaseMaterialInfo.FirstOrDefault(t => t.MaterialId == wmsRawStock.materialId);
                                if (materialInfo != null)
                                {
                                    outMaterialNameTxt.Text = materialInfo.MaterialName;
                                    outMaterialSpecTxt.Text = materialInfo.MaterialSpec;
                                }
                                txtTotalAmount.Text = string.Format("{0:0.00}", wmsRawStock.totalAmount - wmsRawStock.frozenAmount);
                                txtOutScan.Focus();
                                //txtOutScan.Text = string.Format("{0:0}", (mesBaseMaterialInfo.batchFlag == "1" ? (wmsRawStock.totalAmount - wmsRawStock.frozenAmount) : 1)) ;
                                //if (mesBaseMaterialInfo.batchFlag == "1")
                                //{
                                //    txtOutScan.IsReadOnly = false;
                                //}
                                //else
                                //{
                                //    txtOutScan.IsReadOnly = true;
                                //}
                            }
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(barCode))
                    {
                        scanOutMsg.Text = "请先扫描容器号!";
                        txtOutBarCode.Text = string.Empty;
                        txtOutScan.Text = string.Empty;
                    }
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 出库扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutRawBaseLocaltion_Click(object sender, RoutedEventArgs e)
        {
            OutRaw();
        }

        private void OutRaw()
        {
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 10);


                if (!string.IsNullOrEmpty(txtOutBox.Text) && !string.IsNullOrEmpty(txtOutBarCode.Text))
                {

                    var wmsRawStock = dbContext.WmsRawStock
                        .FirstOrDefault(t => t.instockBatch == txtOutBarCode.Text && t.palletInfoCode == txtOutBox.Text);
                    if (wmsRawStock == null)
                    {
                        scanOutMsg.Text = "库存已经被清空!";
                        return;
                    }
                    decimal outScan = Convert.ToDecimal(this.txtOutScan.Text);
                    if (outScan != 1 && outScan > wmsRawStock.totalAmount - wmsRawStock.frozenAmount)
                    {
                        scanOutMsg.Text = "出库数量不能大于库存数量!";
                        return;
                    }
                    var wcsTask = dbContext.WcsTask.Where(t => t.containerNo == txtOutBox.Text).FirstOrDefault();
                    if (wcsTask == null)
                    {
                        scanOutMsg.Text = "出库失败，非CTU出库任务，无法出库!";
                        return;
                    }
                    else
                    {
                        var mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == txtOutBarCode.Text);
                        if (mesBaseBarcodeInfo != null)
                        {
                            WmsRawOutstock? wmsRawOutstock = dbContext.WmsRawOutstock
                                .Where(t => t.materialId == mesBaseBarcodeInfo.materialId && t.realOutstockAmount < t.outstockAmount && t.saleOrderId == (mesBaseBarcodeInfo.saleOrderId == null ? 0 : mesBaseBarcodeInfo.saleOrderId) && t.endStationCode == baseEquip.endStationCode).FirstOrDefault();
                            if (wmsRawOutstock != null)
                            {
                                wmsRawOutstock.realOutstockAmount += outScan;
                                if (wmsRawOutstock.outstockAmount == wmsRawOutstock.realOutstockAmount)
                                {
                                    wmsRawOutstock.executeStatus = "2";
                                }
                                else if (wmsRawOutstock.realOutstockAmount > wmsRawOutstock.outstockAmount)
                                {
                                    scanOutMsg.Text = "出库数量不能大于申请单数量，当前出库数量为：" + (wmsRawOutstock.realOutstockAmount - outScan) + "，申请单数量为：" + wmsRawOutstock.outstockAmount + "!";
                                    return;
                                }
                                wmsRawStock.totalAmount -= outScan;
                                if (wmsRawStock.totalAmount <= 0)
                                {
                                    dbContext.Remove(wmsRawStock);
                                    dbContext.Update(wmsRawOutstock);
                                }
                                else
                                {
                                    dbContext.Update(wmsRawStock);
                                    dbContext.Update(wmsRawOutstock);
                                }
                                if (mesBaseBarcodeInfo != null)
                                {
                                    WmsRawOutstockDetail wmsProductOutstockDetail = new WmsRawOutstockDetail()
                                    {
                                        rawOutstockDetailId = Global.SnowId.NextId(),
                                        rawOutstockId = wmsRawOutstock.rawOutstockId,
                                        materialId = mesBaseBarcodeInfo.materialId,
                                        createDate = DateTime.Now,
                                        createBy = "WCS",
                                        taskCode = wcsTask.objid.ToString(),
                                        executeStatus = "2",
                                        locationCode = wcsTask.currPointNo,
                                        outstockAmount = outScan,
                                        planAmount = outScan,
                                        warehouseId = 512,
                                        materialBarcode = mesBaseBarcodeInfo.barcodeInfo,
                                        instockBatch = mesBaseBarcodeInfo.batchCode,
                                        stackAmount = outScan,
                                        outstockPerson = "WCS",
                                        outstockTime = DateTime.Now,
                                        outstockWay = "2",
                                        materialProductionDate = mesBaseBarcodeInfo.productionDate
                                    };
                                    dbContext.WmsRawOutstockDetail.Add(wmsProductOutstockDetail);
                                }
                                dbContext.SaveChanges();
                            }
                            else
                            {
                                // 没有申请单
                                // 如果选中了出库单，并且无需要出库的申请单，则禁止出库

                                if (!string.IsNullOrEmpty(baseEquip.endStationCode))
                                {
                                    scanOutMsg.Text = "申请单里该条码无需出库！";
                                    return;
                                }
                                if (wmsRawStock.safeFlag != "1")
                                {
                                    scanOutMsg.Text = "该条码不是安全库存，且无申请单，禁止出库！";
                                    return;
                                }
                                if (mesBaseBarcodeInfo.PurchaseOrderId == null)
                                {
                                    wmsRawStock.totalAmount -= outScan;
                                    if (wmsRawStock.totalAmount == 0)
                                    {
                                        dbContext.WmsRawStock.Remove(wmsRawStock);

                                    }
                                    else
                                    {
                                        dbContext.WmsRawStock.Update(wmsRawStock);

                                    }
                                    #region 插入rawOutstock
                                    string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                                    WmsRawOutstock newWmsRawOutstock = new WmsRawOutstock();
                                    newWmsRawOutstock.taskCode = timeStamp + "CTU" + Random.Shared.Next(10, 99);
                                    newWmsRawOutstock.warehouseId = 512;
                                    newWmsRawOutstock.locationCode = wcsTask.currPointNo;
                                    newWmsRawOutstock.stationId = 512;
                                    newWmsRawOutstock.materialId = mesBaseBarcodeInfo.materialId;
                                    newWmsRawOutstock.materialBatch = mesBaseBarcodeInfo.barcodeInfo;
                                    newWmsRawOutstock.palletInfoCode = wcsTask.containerNo;
                                    newWmsRawOutstock.outstockAmount = outScan;
                                    newWmsRawOutstock.realOutstockAmount = outScan;
                                    newWmsRawOutstock.operationType = "1";
                                    newWmsRawOutstock.taskType = "1";
                                    newWmsRawOutstock.auditStatus = "1";
                                    newWmsRawOutstock.applyBy = "CtuGun";
                                    newWmsRawOutstock.applyDate = DateTime.Now;
                                    newWmsRawOutstock.executeStatus = "2";
                                    newWmsRawOutstock.saleOrderId = mesBaseBarcodeInfo.saleOrderId;
                                    newWmsRawOutstock.updateDate = DateTime.Now;
                                    newWmsRawOutstock.beginTime = DateTime.Now;
                                    newWmsRawOutstock.endTime = DateTime.Now;
                                    dbContext.WmsRawOutstock.Add(newWmsRawOutstock);
                                    dbContext.SaveChanges();
                                    #endregion
                                    //if (mesBaseBarcodeInfo != null)
                                    //{
                                    //    WmsRawOutstockDetail wmsProductOutstockDetail = new WmsRawOutstockDetail()
                                    //    {
                                    //        rawOutstockDetailId = Global.SnowId.NextId(),
                                    //        rawOutstockId = 0,
                                    //        materialId = mesBaseBarcodeInfo.materialId,
                                    //        createDate = DateTime.Now,
                                    //        createBy = "WCS",
                                    //        taskCode = wcsTask.objid.ToString(),
                                    //        executeStatus = "2",
                                    //        locationCode = wcsTask.currPointNo,
                                    //        outstockAmount = outScan,
                                    //        planAmount = outScan,
                                    //        warehouseId = 512,
                                    //        materialBarcode = mesBaseBarcodeInfo.barcodeInfo,
                                    //        instockBatch = mesBaseBarcodeInfo.batchCode,
                                    //        stackAmount = outScan,
                                    //        outstockPerson = "WCS",
                                    //        outstockTime = DateTime.Now,
                                    //        outstockWay = "2",
                                    //        materialProductionDate = mesBaseBarcodeInfo.productionDate
                                    //    };
                                    //    dbContext.WmsRawOutstockDetail.Add(wmsProductOutstockDetail);
                                    //}
                                    // dbContext.SaveChanges();

                                }
                                else
                                {
                                    scanOutMsg.Text = "该条码的销售订单不正确";
                                    txtOutScan.Text = string.Empty;
                                    txtOutBarCode.Text = string.Empty;
                                    outMaterialSpecTxt.Text = string.Empty;
                                    outMaterialNameTxt.Text = string.Empty;
                                    txtOutBox.Text = string.Empty;
                                    txtOutBox.Focus();
                                    return;
                                }
                            }

                            scanOutMsg.Text = "出库成功!";
                            txtOutScan.Text = string.Empty;
                            txtOutBarCode.Text = string.Empty;
                            outMaterialSpecTxt.Text = string.Empty;
                            outMaterialNameTxt.Text = string.Empty;
                            txtOutBox.Text = string.Empty;
                            txtOutBox.Focus();
                        }
                        else
                        {
                            scanOutMsg.Text = "未查询到该条码信息!";
                        }
                    }
                }
                else
                {
                    scanOutMsg.Text = "请先扫描容器号和条码!";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SelectButton_Click(object sender, RoutedEventArgs e)
        {
            CallSelectedItem.Clear();
            await GetPersonCallMaterialData();
        }
        /// <summary>
        /// 获取人员呼叫的物料数据
        /// </summary>
        private async Task GetPersonCallMaterialData()
        {
            try
            {
                int pageNumber = this.Pagination2.PageIndex;
                // 计算跳过的记录数
                int skip = (pageNumber - 1) * pageCount;

                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                List<long?> materialIds = new List<long?>();
                List<MesBaseMaterialInfo> materialInfos = new List<MesBaseMaterialInfo>();
                if (!string.IsNullOrEmpty(MaterialName.Text))
                {
                    materialInfos = dbContext.MesBaseMaterialInfo.Where(t => t.MaterialName.Contains(MaterialName.Text) || t.MaterialCode.Contains(MaterialName.Text) || t.MaterialSpec.Contains(MaterialName.Text)).ToList();
                    materialIds = materialInfos.Select(t => t.MaterialId).ToList();
                }
                List<WmsRawStock> wmsRawStocks = null;

                wmsRawStocks = dbContext.WmsRawStock
               .Where(t => t.warehouseId == 512)
               .WhereIf(materialIds.Count > 0, t => materialIds.Contains(t.materialId))
               .ToList();


                var groupWmsRawStock = wmsRawStocks.GroupBy(t => new { t.materialId, t.palletInfoCode }).Select(t =>
                    new
                    {
                        materialId = t.Key.materialId,
                        palletInfoCode = t.Key.palletInfoCode,
                        totalAmount = t.Sum(x => x.totalAmount),
                        frozenAmount = t.Sum(x => x.frozenAmount),
                    });

                int totalRecords = groupWmsRawStock.Count();
                Pagination2.MaxPageCount = (totalRecords / pageCount) + (totalRecords % pageCount == 0 ? 0 : 1);
                groupWmsRawStock = groupWmsRawStock.Skip(skip).Take(pageCount);
                //.GroupBy(t => t.palletInfoCode)
                //.Select(t => new
                //{
                //    palletInfoCode = t.Key,
                //    totalAmount = string.Join("\n", t.Select(x => x.totalAmount)),
                //    frozenAmount = string.Join("\n", t.Select(x => x.frozenAmount)),
                //    materialId = string.Join("\n", t.Select(x => x.materialId)),
                //}).ToList(); 
                var palletInfoCodes = groupWmsRawStock.Select(t => t.palletInfoCode).Distinct().ToList();
                var wmsBaseLocations = await dbContext.WmsBaseLocation
                    .Where(t => t.ContainerStatus == "1")
                    .Where(t => t.warehouseId == 512)
                    .Where(t => palletInfoCodes.Contains(t.containerCode)).ToListAsync();
                if (string.IsNullOrEmpty(MaterialName.Text))
                {
                    var tempMaterialIds = groupWmsRawStock.Select(x => x.materialId).Distinct().ToList();
                    materialInfos = await dbContext.MesBaseMaterialInfo.Where(x => tempMaterialIds.Contains(x.MaterialId)).ToListAsync();
                }
                var bill = from a in wmsBaseLocations
                           from b in groupWmsRawStock
                           from c in materialInfos
                           where a.containerCode == b.palletInfoCode && b.materialId == c.MaterialId
                           select new
                           {
                               baseLocationId = a.locationId,
                               //wmsRawStocksId = b.rawStockId,
                               locationCode = a.locationCode,
                               materialId = b.materialId,
                               materialCode = c.MaterialCode,
                               materialName = c.MaterialName,
                               materialSpec = c.MaterialSpec,
                               palletInfoCode = b.palletInfoCode,
                               //instockDate = b.instockDate,
                               totalAmount = Math.Round((decimal)b.totalAmount, 2),
                               frozenAmount = Math.Round((decimal)b.frozenAmount, 2),
                               IsSelected = CallSelectedItem.Contains(a.locationId)
                           };



                var bills = bill.GroupBy(t => new { t.baseLocationId, t.palletInfoCode, t.locationCode, t.IsSelected })
                    .Select(t => new
                    {
                        baseLocationId = t.Key.baseLocationId,
                        palletInfoCode = t.Key.palletInfoCode,
                        locationCode = t.Key.locationCode,
                        IsSelected = t.Key.IsSelected,
                        totalAmount = string.Join("\n", t.Select(x => x.totalAmount)),
                        frozenAmount = string.Join("\n", t.Select(x => x.frozenAmount)),
                        materialId = string.Join("\n", t.Select(x => x.materialId)),
                        materialCode = string.Join("\n", t.Select(x => x.materialCode)),
                        materialName = string.Join("\n", t.Select(x => x.materialName[..(x.materialName.Length > 20 ? 20 : x.materialName.Length)])),
                        materialNameSrc = string.Join("\n", t.Select(x => x.materialName)),
                        materialSpec = string.Join("\n", t.Select(x => x.materialSpec[..(x.materialSpec.Length > 20 ? 20 : x.materialSpec.Length)])),
                        materialSpecSrc = string.Join("\n", t.Select(x => x.materialSpec))
                    }).ToList();
                bills = bills.OrderBy(t => t.palletInfoCode).ThenBy(t => t.materialId).ToList();
                // PersonCallMaterial.ItemsSource = bills.Skip((this.Pagination2.PageIndex - 1) * this.pageCount).Take(this.pageCount);
                PersonCallMaterial.ItemsSource = bills;
                int sum = bills.Count();
                // Pagination2.MaxPageCount = (sum / pageCount) + (sum % pageCount == 0 ? 0 : 1);

                if (bills.Count == 0)
                {
                    HandyControl.Controls.MessageBox.Show("未查询到数据");
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 页码改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Pagination2_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            await GetPersonCallMaterialData();
        }
        /// <summary>
        /// 页码改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pagination3_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            GetInvertoryData();
        }
        /// <summary>
        /// 开始盘点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartInventory(object sender, RoutedEventArgs e)
        {
            dynamic wmsInventoryCheck = this.InventoryMaterial.SelectedItem;
            long inventoryCheckId = wmsInventoryCheck.InventoryCheckId;
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            var InventoryCheck = dbContext.WmsInventoryCheck
                .Where(t => t.InventoryCheckId == inventoryCheckId).FirstOrDefault();
            if (InventoryCheck == null || InventoryCheck.CheckStatus == "2")
            {
                MessageBox.Show("盘点单不存在或已盘点");
                return;
            }
            BaseEquip agvEquip = SystemData.BaseEquip.First(t => t.objid == 11);
            BaseEquip lineEquip = SystemData.BaseEquip.First(t => t.objid == 20);

            if (InventoryCheck.InventoryingAmount != 0)
            {
                bool hasTask = dbContext.WcsTask.Where(t => t.taskType == 100).Any();
                if (!hasTask)
                {
                    hasTask = dbContext.WcsTaskManual.Where(t => t.taskType == 100).Any();
                    if (!hasTask)
                    {
                        InventoryCheck.InventoriedAmount += InventoryCheck.InventoryingAmount;
                        InventoryCheck.InventoryingAmount = 0;
                    }
                }
            }
            if (InventoryCheck.InventoryingAmount == 0)
            {
                bool hasTask = dbContext.WcsTask.Where(t => t.taskType == 100).Any();
                if (!hasTask)
                {
                    hasTask = dbContext.WcsTaskManual.Where(t => t.taskType == 100).Any();
                    if (!hasTask)
                    {
                        List<string>? locationCodeList = null;
                        if (InventoryCheck.MaterialId != null)
                        {  
                            // 盘点某个型号的物料库存的库位
                            locationCodeList =  dbContext.WmsRawStock.Where(t => t.warehouseId == 512 && t.materialId == InventoryCheck.MaterialId ).Select(x=>x.locationCode).ToList();
                         
                        }
                        //所有满足条件的需要盘库的库位
                        var wmsBaseLocations = dbContext.WmsBaseLocation
                             .Where(t => t.ContainerStatus == "1")
                             .Where(t => t.locationStatus == "1")
                             .OrderBy(t => t.locRow)
                             .ThenBy(t => t.locColumn)
                             .ToList();
                        if(locationCodeList != null && locationCodeList.Count > 0)
                        {
                            wmsBaseLocations = wmsBaseLocations.Where(x=>locationCodeList.Contains(x.locationCode)).ToList();
                        }

                        var wmsInventoryCheckDetails = dbContext.WmsInventoryCheckDetail
                            .Where(t => t.InventoryCheckId == InventoryCheck.InventoryCheckId).ToList();
                        // 已经盘点过的库位
                        List<string> locationCodes = wmsInventoryCheckDetails.Select(t => t.LocationCode).Distinct().ToList();
                        wmsBaseLocations.RemoveAll(t => locationCodes.Contains(t.locationCode));
                        if (wmsBaseLocations.Count > 0)
                        {
                            List<string> locations = wmsBaseLocations.Select(t => t.locationCode).ToList();

                            List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock.Where(t => t.warehouseId == 512)
                                .Where(t => locations.Contains(t.locationCode))
                                .WhereIf(InventoryCheck.MaterialId!=null,t => t.materialId == InventoryCheck.MaterialId).ToList();

                            // 过滤后需要满足条件的有库存的库位
                            List<string> codes = wmsRawStocks.Select(t => t.locationCode).Distinct().ToList();

                            var bill = from a in wmsBaseLocations
                                       from b in codes
                                       where a.locationCode == b
                                       select new { a };
                            var outLocation = bill.OrderBy(t => t.a.locRow).ThenBy(t => t.a.locColumn).Take(6);
                            List<WcsTaskManual> addList = new List<WcsTaskManual>();
                            foreach (var item in outLocation)
                            {
                                WmsBaseLocation startBaseLocation = item.a;
                                startBaseLocation.locationStatus = "6";
                                //startBaseLocation.ContainerStatus = "2";
                                
                                addList.Add(new WcsTaskManual()
                                {
                                    objid = Global.SnowId.NextId(),
                                    taskType = 100,
                                    containerNo = startBaseLocation.containerCode,
                                    currPointId = startBaseLocation.locationId,
                                    currPointNo = startBaseLocation.locationCode,
                                    nextPointId = agvEquip.objid,
                                    nextPointNo = agvEquip.equipNo,
                                    endPointId = lineEquip.objid,
                                    endPointNo = lineEquip.equipNo,
                                    createTime = DateTime.Now,
                                    ud1 = startBaseLocation.locColumn,
                                    taskStatus = 0,
                                    remark = "CTU盘点任务",
                                    floorNo = 5,
                                    fromFloorNo = 5,
                                    useFlag = 1
                                });
                                dbContext.Update(startBaseLocation);
                            }
                            //for (int i = addList.Count + 1; i <= 6; i++)
                            //{
                            //    List<long?> list = addList.Select(t => t.currPointId).ToList();
                            //    WmsBaseLocation? startBaseLocation = wmsBaseLocations.Where(t => !list.Contains(t.locationId)).FirstOrDefault();
                            //    if (startBaseLocation != null)
                            //    {
                            //        startBaseLocation.locationStatus = "6";
                            //        startBaseLocation.ContainerStatus = "2";
                            //        addList.Add(new WcsTaskManual()
                            //        {
                            //            objid = Global.SnowId.NextId(),
                            //            taskType = 100,
                            //            orderId = InventoryCheck.InventoryCheckId,
                            //            containerNo = startBaseLocation.containerCode,
                            //            currPointId = startBaseLocation.locationId,
                            //            currPointNo = startBaseLocation.locationCode,
                            //            nextPointId = agvEquip.objid,
                            //            nextPointNo = agvEquip.equipNo,
                            //            endPointId = lineEquip.objid,
                            //            endPointNo = lineEquip.equipNo,
                            //            createTime = DateTime.Now,
                            //            ud1 = startBaseLocation.locColumn,
                            //            taskStatus = 0,
                            //            remark = "CTU盘点任务",
                            //            floorNo = 5,
                            //            fromFloorNo = 5,
                            //            useFlag = 1,
                            //        });
                            //        dbContext.Update(startBaseLocation);
                            //    }
                            //}
                            List<WmsInventoryCheckDetail> addCheckDetail = new List<WmsInventoryCheckDetail>();
                            foreach (var item in addList)
                            {
                                List<WmsRawStock> itemList = wmsRawStocks.Where(t => t.locationCode == item.currPointNo).ToList();
                                foreach (var rawItem in itemList)
                                {
                                    addCheckDetail.Add(new WmsInventoryCheckDetail
                                    {
                                        InventoryCheckDetailId = Global.SnowId.NextId(),
                                        InventoryCheckId = inventoryCheckId,
                                        CheckStatus = "1",
                                        CreateBy = "WCS",
                                        CreateTime = DateTime.Now,
                                        StockAmount = rawItem.totalAmount,
                                        RealAmount = rawItem.totalAmount,
                                        InventoryCount = 0,
                                        LocationCode = rawItem.locationCode,
                                        StockId = 1,
                                        StockType = "1",
                                        MaterialId = rawItem.materialId,
                                        ErpStatus = "0",
                                        ErpAmount = 0,
                                    });
                                }
                            }
                            InventoryCheck.InventoryingAmount += addList.Count;
                            if (InventoryCheck.BeginTime == null)
                            {
                                InventoryCheck.BeginTime = DateTime.Now;
                                InventoryCheck.CheckStatus = "1";
                            }
                            dbContext.AddRange(addCheckDetail);
                            dbContext.AddRange(addList);
                            dbContext.SaveChanges();
                            HandyControl.Controls.MessageBox.Show("任务创建成功!");
                        }
                        else
                        {
                            HandyControl.Controls.MessageBox.Error("无可盘点库位!");
                        }
                    }
                    else
                    {
                        HandyControl.Controls.MessageBox.Info("当前有盘点任务正在出库");
                    }
                }
                else
                {
                    HandyControl.Controls.MessageBox.Info("当前有盘点任务正在出库");
                }
            }
            else
            {
                HandyControl.Controls.MessageBox.Info("盘点中,请等待本次盘点完成!");
            }

            GetInvertoryData();
        }

        /// <summary>
        /// 查看盘点详情界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenInventoryDetails(object sender, RoutedEventArgs e)
        {
            dynamic wmsInventoryCheck = this.InventoryMaterial.SelectedItem;
            long inventoryCheckId = wmsInventoryCheck.InventoryCheckId;
            InventoryDetails inventoryDetails = new InventoryDetails(_host, inventoryCheckId);
            inventoryDetails.ShowDialog();
        }

        /// <summary>
        /// 叫空料箱
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CallEmptyBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EmptyCountForm emptyCountForm = new EmptyCountForm(1, 6);
                emptyCountForm.ShowDialog();
                if (EmptyCountForm.IsSelect)
                {
                    var baseEquip = SystemData.BaseEquip.First(t => t.objid == 11);
                    BaseEquip endEquip = SystemData.BaseEquip.First(t => t.objid == 20);
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

                    //int taskCount = dbContext.WcsTask.Where(t => t.taskType == 30).Count();
                    //if (taskCount >= 6)
                    //{
                    //    HandyControl.Controls.HandyControl.Controls.MessageBox.Show("当前CTU入库任务已满6个,请等待任务完成后再叫空箱!");
                    //    return;
                    //}

                    #region 出库创建taskmanual，如果有之前的出库任务， 弹框提示有未完成的出库任务，是否继续出库，如果继续，删除之前的出库任务
                    var removeList = dbContext.WcsTask.Where(x => x.taskType == 30 && x.taskStatus == 6).ToList();
                    if (removeList.Count > 0)
                    {
                        StringBuilder stringContainers = new StringBuilder();
                        stringContainers.AppendLine("以下料箱有未完成的出库任务:");
                        removeList.ForEach(x => stringContainers.AppendLine($"料箱号{x.containerNo}\n"));
                        stringContainers.AppendLine("是否删除任务继续出库?");
                        MessageBoxResult isContinueCreateResult = HandyControl.Controls.MessageBox.Show(stringContainers.ToString(), "提示", MessageBoxButton.YesNo);
                        if (isContinueCreateResult == MessageBoxResult.Yes)
                        {
                            dbContext.WcsTask.RemoveRange(removeList);
                        }
                        else
                        {
                            return;
                        }
                    }
                    #endregion



                    var wmsBaseLocation = dbContext.WmsBaseLocation
                        .Where(t => t.locationStatus == "1")
                        .Where(t => t.warehouseId == 512 && t.ContainerStatus == "1")
                        .OrderBy(t => t.locColumn)
                        .ThenBy(t => t.locRow)
                        .ToList();
                    var wmsRawStock = dbContext.WmsRawStock.Where(t => t.warehouseId == 512).ToList();
                    List<string> palletInfoCodes = wmsRawStock.Select(t => t.palletInfoCode).ToList();
                    wmsBaseLocation.RemoveAll(t => palletInfoCodes.Contains(t.containerCode));
                    if (wmsBaseLocation.Count > 0 && EmptyCountForm.EmptyTaskCount <= wmsBaseLocation.Count)
                    {
                        List<WcsTaskManual> addList = new List<WcsTaskManual>();
                        for (int i = 0; i < EmptyCountForm.EmptyTaskCount; i++)
                        {
                            WmsBaseLocation startBaseLocation = wmsBaseLocation[i];
                            startBaseLocation.locationStatus = "6";
                            startBaseLocation.ContainerStatus = "2";
                            addList.Add(new WcsTaskManual()
                            {
                                objid = Global.SnowId.NextId(),
                                taskType = 30,
                                containerNo = startBaseLocation.containerCode,
                                startPointId = startBaseLocation.locationId,
                                startPointNo = startBaseLocation.locationCode,
                                currPointId = startBaseLocation.locationId,
                                currPointNo = startBaseLocation.locationCode,
                                nextPointId = baseEquip.objid,
                                nextPointNo = baseEquip.equipNo,
                                endPointId = endEquip.objid,
                                endPointNo = endEquip.equipNo,
                                createTime = DateTime.Now,
                                ud1 = startBaseLocation.locColumn,
                                taskStatus = 0,
                                remark = "CTU空库任务",
                                floorNo = 5,
                                fromFloorNo = 5,
                                useFlag = 1
                            });
                            dbContext.Update(startBaseLocation);
                        }
                        dbContext.AddRange(addList);
                        dbContext.SaveChanges();
                        HandyControl.Controls.MessageBox.Show("任务创建成功!");
                    }
                    else
                    {
                        HandyControl.Controls.MessageBox.Error($"没有足够的空箱库位库位，剩余空库位数量为{wmsBaseLocation.Count}!");
                    }
                }

            }
            catch
            {

            }
        }

        /// <summary>
        /// 叫托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CallTrayBtn_Click(object sender, RoutedEventArgs e)
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            using var transaction = dbContext.Database.BeginTransaction();
            try
            {
                BaseEquip ctuEquip = SystemData.BaseEquip.First(t => t.objid == 11);
                BaseEquip endEquip = SystemData.BaseEquip.First(t => t.objid == 20);
                if (itemsControlItems.Count == 0)
                {
                    HandyControl.Controls.MessageBox.Show("请选择料箱!");
                    return;
                }
                //int taskCount = dbContext.WcsTask.Where(t => t.nextPointId == 11).Count();
                //if (taskCount + ids.Count > 6)
                //{
                //    HandyControl.Controls.MessageBox.Show($"当前CTU只能有6个任务,当前任务数{taskCount}");
                //    return;
                //}
                //替换 var wmsBaseLocation = dbContext.WmsBaseLocation.Where(t => t.warehouseId == 512 && t.ContainerStatus == "1").Where(t => CallSelectedItem.Contains(t.locationId)).ToList();
                List<long> idList = itemsControlItems.Select(x => x.baseLocationId).ToList();

                var wmsBaseLocation = dbContext.WmsBaseLocation.Where(t => t.warehouseId == 512 && t.ContainerStatus == "1").Where(t => idList.Contains(t.locationId)).ToList();


                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("确认出库:");
                foreach (var item in wmsBaseLocation)
                {
                    stringBuilder.AppendLine($"库位号{item.locationCode},料箱号{item.containerCode}.");
                }
                MessageBoxResult MessageBoxResult = HandyControl.Controls.MessageBox.Show(stringBuilder.ToString(), "提示", MessageBoxButton.YesNo);
                if (MessageBoxResult == MessageBoxResult.Yes)
                {

                    #region 出库创建taskmanual，如果有之前的出库任务， 弹框提示有未完成的出库任务，是否继续出库，如果继续，删除之前的出库任务
                    var removeList = dbContext.WcsTask.Where(x => x.taskType == 30 && x.taskStatus == 6).ToList();
                    if (removeList.Count > 0)
                    {
                        StringBuilder stringContainers = new StringBuilder();
                        stringContainers.AppendLine("以下料箱有未完成的出库任务:");
                        removeList.ForEach(x => stringContainers.AppendLine($"料箱号{x.containerNo}\n"));
                        stringContainers.AppendLine("是否删除任务继续出库?");
                        MessageBoxResult isContinueCreateResult = HandyControl.Controls.MessageBox.Show(stringContainers.ToString(), "提示", MessageBoxButton.YesNo);
                        if (isContinueCreateResult == MessageBoxResult.Yes)
                        {
                            dbContext.WcsTask.RemoveRange(removeList);
                        }
                        else
                        {
                            return;
                        }
                    }
                    #endregion


                    List<WcsTaskManual> addList = new List<WcsTaskManual>();
                    foreach (var item in wmsBaseLocation)
                    {
                        addList.Add(new WcsTaskManual()
                        {
                            objid = Global.SnowId.NextId(),
                            taskType = 30,
                            containerNo = item.containerCode,
                            startPointId = item.locationId,
                            startPointNo = item.locationCode,
                            currPointId = item.locationId,
                            currPointNo = item.locationCode,
                            nextPointId = ctuEquip.objid,
                            nextPointNo = ctuEquip.equipNo,
                            endPointId = endEquip.objid,
                            endPointNo = endEquip.equipNo,
                            createTime = DateTime.Now,
                            ud1 = item.locColumn,
                            taskStatus = 0,
                            remark = "CTU托盘任务",
                            floorNo = 5,
                            fromFloorNo = 5,
                            useFlag = 1
                        });
                        item.ContainerStatus = "2";
                        item.locationStatus = "6";
                        dbContext.Update(item);
                    }
                    if (addList.Count < 6)
                    {
                        var messageBoxResult = HandyControl.Controls.MessageBox.Show($"已创建{addList.Count}个料箱的任务，是否需要创建出空箱的任务？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (messageBoxResult == MessageBoxResult.Yes)
                        {
                            EmptyCountForm emptyCountForm = new(1, 6 - addList.Count);
                            emptyCountForm.ShowDialog();
                            if (EmptyCountForm.IsSelect)
                            {
                                List<WmsBaseLocation> emptyLocations = dbContext.ExecuteSqlQuery<WmsBaseLocation>(@$"
                                        select t1.location_id locationId,
                                               t1.container_code containerCode,
                                               t1.location_code locationCode
                                        from wms_base_location t1
                                        left join wms_raw_stock t2
                                        on t1.location_code=t2.location_code
                                        where t2.location_code is null and t1.location_status=1
                                        and t1.container_status=1 and t1.warehouse_id=512
                                        order by t1.loc_column,t1.loc_row
                                ");
                                if (emptyLocations.Count < EmptyCountForm.EmptyTaskCount)
                                {
                                    messageBoxResult = HandyControl.Controls.MessageBox.Show("没有足够的空箱库位库位，剩余空库位数量为" + emptyLocations.Count + "!\n是否将现有的空箱全部出库？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information);
                                    if (messageBoxResult == MessageBoxResult.Yes)
                                    {
                                        foreach (var item in emptyLocations)
                                        {
                                            addList.Add(new WcsTaskManual()
                                            {
                                                objid = Global.SnowId.NextId(),
                                                taskType = 30,
                                                containerNo = item.containerCode,
                                                startPointId = item.locationId,
                                                startPointNo = item.locationCode,
                                                currPointId = item.locationId,
                                                currPointNo = item.locationCode,
                                                nextPointId = ctuEquip.objid,
                                                nextPointNo = ctuEquip.equipNo,
                                                endPointId = endEquip.objid,
                                                endPointNo = endEquip.equipNo,
                                                createTime = DateTime.Now,
                                                ud1 = item.locColumn,
                                                taskStatus = 0,
                                                remark = "CTU空库任务",
                                                floorNo = 5,
                                                fromFloorNo = 5,
                                                useFlag = 1
                                            });
                                            dbContext.WmsBaseLocation.Where(t => t.locationId == item.locationId)
                                                .Update(t => new WmsBaseLocation { locationStatus = "6", ContainerStatus = "2" });
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = 0; i < EmptyCountForm.EmptyTaskCount; i++)
                                    {
                                        addList.Add(new WcsTaskManual()
                                        {
                                            objid = Global.SnowId.NextId(),
                                            taskType = 30,
                                            containerNo = emptyLocations[i].containerCode,
                                            startPointId = emptyLocations[i].locationId,
                                            startPointNo = emptyLocations[i].locationCode,
                                            currPointId = emptyLocations[i].locationId,
                                            currPointNo = emptyLocations[i].locationCode,
                                            nextPointId = ctuEquip.objid,
                                            nextPointNo = ctuEquip.equipNo,
                                            endPointId = endEquip.objid,
                                            endPointNo = endEquip.equipNo,
                                            createTime = DateTime.Now,
                                            ud1 = emptyLocations[i].locColumn,
                                            taskStatus = 0,
                                            remark = "CTU空库任务",
                                            floorNo = 5,
                                            fromFloorNo = 5,
                                            useFlag = 1
                                        });
                                        dbContext.WmsBaseLocation.Where(t => t.locationId == emptyLocations[i].locationId)
                                              .Update(t => new WmsBaseLocation { locationStatus = "6", ContainerStatus = "2" });
                                    }
                                }
                            }
                        }
                    }
                    dbContext.AddRange(addList);
                    dbContext.SaveChanges();
                    transaction.Commit();
                    HandyControl.Controls.MessageBox.Show("创建出库任务成功!");
                    itemsControlItems.Clear();
                    CallSelectedItem.Clear();
                    GetPersonCallMaterialData();
                }
            }
            catch
            {
                try
                {
                    transaction.Rollback();
                }
                catch
                {

                }
            }
        }

        /// <summary>
        /// 叫托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemoveTrayBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BaseEquip ctuEquip = SystemData.BaseEquip.First(t => t.objid == 11);
                BaseEquip endEquip = SystemData.BaseEquip.First(t => t.objid == 20);
                List<WcsTaskManual> taskList = new List<WcsTaskManual>();
                if (itemsControlItems.Count == 0)
                {
                    HandyControl.Controls.MessageBox.Show("请选择料箱!");
                    return;
                }

                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                List<long> idList = itemsControlItems.Select(x => x.baseLocationId).ToList();
                if (idList.Count == 0)
                {
                    HandyControl.Controls.MessageBox.Error("请选择需要移库的料箱!");
                    return;
                }
                else
                {
                    if (idList.Count == 1)
                    {
                        List<WmsBaseLocation> emptyLocations = dbContext.ExecuteSqlQuery<WmsBaseLocation>(@$"
                                        select t1.location_id locationId,
                                               t1.container_code containerCode,
                                               t1.location_code locationCode
                               
                                        from wms_base_location t1
                                        left join wms_raw_stock t2
                                        on t1.location_code=t2.location_code
                                        where t2.location_code is null and t1.location_status=1
                                        and t1.container_status=1 and t1.warehouse_id=512
                                        order by t1.loc_column,t1.loc_row
                                ");


                        var wmsLocation = dbContext.WmsBaseLocation.FirstOrDefault(t => t.locationId == idList[0] && t.locationStatus == "1");
                        if (wmsLocation == null)
                        {
                            HandyControl.Controls.MessageBox.Error("选择的料箱错误，请重新选择!");
                            return;
                        }
                        if (emptyLocations.Count == 0)
                        {
                            HandyControl.Controls.MessageBox.Error("只选择了一个移库料箱，但是没有空箱库位库位，无法移库!");
                            return;
                        }
                        MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show("选择了一个移库料箱，需要出空料箱，是否确认？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (messageBoxResult == MessageBoxResult.Yes)
                        {
                            var emptyLocation = dbContext.WmsBaseLocation.FirstOrDefault(t => t.locationId == emptyLocations.First().locationId);
                            //WmsBaseLocation emptyLocation = emptyLocations.First();
                            emptyLocation.locationStatus = "4";
                            emptyLocation.ContainerStatus = "2";
                            wmsLocation.locationStatus = "4";
                            wmsLocation.ContainerStatus = "2";
                            taskList.Add(new WcsTaskManual()
                            {
                                objid = Global.SnowId.NextId(),
                                taskType = 102,
                                containerNo = wmsLocation.containerCode,
                                startPointId = wmsLocation.locationId,
                                startPointNo = wmsLocation.locationCode,
                                currPointId = wmsLocation.locationId,
                                currPointNo = wmsLocation.locationCode,
                                nextPointId = ctuEquip.objid,
                                nextPointNo = ctuEquip.equipNo,
                                endPointId = endEquip.objid,
                                endPointNo = endEquip.equipNo,
                                createTime = DateTime.Now,
                                ud1 = wmsLocation.locColumn,
                                taskStatus = 0,
                                remark = "CTU托盘任务",
                                floorNo = 5,
                                fromFloorNo = 5,
                                useFlag = 1
                            });
                            taskList.Add(new WcsTaskManual()
                            {
                                objid = Global.SnowId.NextId(),
                                taskType = 102,
                                containerNo = emptyLocation.containerCode,
                                startPointId = emptyLocation.locationId,
                                startPointNo = emptyLocation.locationCode,
                                currPointId = emptyLocation.locationId,
                                currPointNo = emptyLocation.locationCode,
                                nextPointId = ctuEquip.objid,
                                nextPointNo = ctuEquip.equipNo,
                                endPointId = endEquip.objid,
                                endPointNo = endEquip.equipNo,
                                createTime = DateTime.Now,
                                ud1 = emptyLocation.locColumn,
                                taskStatus = 0,
                                remark = "CTU托盘任务",
                                floorNo = 5,
                                fromFloorNo = 5,
                                useFlag = 1
                            });
                            dbContext.Update(wmsLocation);
                            dbContext.Update(emptyLocation);
                            dbContext.AddRange(taskList);
                            dbContext.SaveChanges();
                            HandyControl.Controls.MessageBox.Show("移库任务创建成功!");
                            itemsControlItems.Clear();
                            CallSelectedItem.Clear();
                            GetPersonCallMaterialData();
                        }
                    }
                    else if (idList.Count == 2)
                    {
                        List<WmsBaseLocation> wmsBaseLocations = dbContext.WmsBaseLocation.Where(t => idList.Contains(t.locationId))
                            .Where(t => t.ContainerStatus == "1")
                            .Where(t => t.locationStatus == "1")
                            .ToList();
                        if (wmsBaseLocations.Count != 2)
                        {
                            HandyControl.Controls.MessageBox.Error("选择的料箱库位状态异常，请重新选择!");
                            return;
                        }
                        foreach (var item in wmsBaseLocations)
                        {
                            taskList.Add(new WcsTaskManual()
                            {
                                objid = Global.SnowId.NextId(),
                                taskType = 102,
                                containerNo = item.containerCode,
                                startPointId = item.locationId,
                                startPointNo = item.locationCode,
                                currPointId = item.locationId,
                                currPointNo = item.locationCode,
                                nextPointId = ctuEquip.objid,
                                nextPointNo = ctuEquip.equipNo,
                                endPointId = endEquip.objid,
                                endPointNo = endEquip.equipNo,
                                createTime = DateTime.Now,
                                ud1 = item.locColumn,
                                taskStatus = 0,
                                remark = "CTU托盘任务",
                                floorNo = 5,
                                fromFloorNo = 5,
                                useFlag = 1
                            });
                            item.ContainerStatus = "2";
                            item.locationStatus = "6";
                            dbContext.Update(item);
                        }
                        dbContext.AddRange(taskList);
                        dbContext.SaveChanges();
                        HandyControl.Controls.MessageBox.Show("移库任务创建成功!");
                        itemsControlItems.Clear();
                        CallSelectedItem.Clear();
                        GetPersonCallMaterialData();
                    }
                    else if (idList.Count > 2)
                    {
                        HandyControl.Controls.MessageBox.Error("选择料箱不能超过2个！");
                        return;
                    }
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 执行CTU任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExecuteCtuTask_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (int.TryParse(outTaskCount.Text, out int count))
                {
                    if (count > 0)
                    {
                        using var scope = _host.Services.CreateScope();
                        using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                        var tasks = dbContext.WcsTask.Where(t => t.taskType == 30 && t.taskStatus == 0 && t.useFlag == 0).ToList();
                        foreach (var task in tasks)
                        {
                            task.taskStatus = 0;
                            task.useFlag = 1;
                            dbContext.Update(task);
                            dbContext.SaveChanges();
                        }
                        HandyControl.Controls.MessageBox.Show("任务执行成功!");
                    }
                    else
                    {
                        HandyControl.Controls.MessageBox.Error("没有可执行的任务!");
                    }
                }
            }
            catch
            {

            }
        }

        private void callPlc_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                BasePlcpoint basePlcpoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "canReceive");
                SystemData.PlcDic[1].WriteToPoint(basePlcpoint.plcpointAddress, "1", basePlcpoint.plcpointLength.ToString());
                MsgText.Text = "一键收料发送成功";
            }
            catch (Exception ex)
            {
                try
                {
                    if (ex is PlcException)
                    {
                        foreach (var item in SystemData.PlcDic)
                        {
                            if (item.Value.IP == ex.Message)
                            {
                                MsgText.Text = "PLC断开连接，正在重连!";
                                Task.Run(() =>
                                {
                                    SystemData.PlcDic[item.Key] = new Plc.S7.Plc(item.Value.CPU, item.Value.IP, item.Value.Port, item.Value.Rack, item.Value.Slot);
                                    SystemData.PlcDic[item.Key].Open();
                                });
                                break;
                            }
                        }
                    }
                }
                catch
                {
                    MsgText.Text = "PLC连接失败!";
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            TextBoxGetFocus();
        }

        #region 清除按钮
        private void barClear_Click(object sender, RoutedEventArgs e)
        {
            txtInBarCode.Text = string.Empty;
        }

        private void boxOutClear_Click(object sender, RoutedEventArgs e)
        {
            txtOutBox.Text = string.Empty;
        }

        private void boxClear_Click(object sender, RoutedEventArgs e)
        {
            txtInBox.Text = string.Empty;
        }

        private void barOutClear_Click(object sender, RoutedEventArgs e)
        {
            txtOutBarCode.Text = string.Empty;
        }


        private void boxReturnClear_Click(object sender, RoutedEventArgs e)
        {
            txtReturnBox.Text = string.Empty;
        }

        private void barReturnClear_Click(object sender, RoutedEventArgs e)
        {
            txtReturnBarCode.Text = string.Empty;
        }
        #endregion

        #region 托盘库进出
        private void OneIn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BasePlcpoint trayStatus = SystemData.BasePlcpoints.First(t => t.plcpointNo == "trayStatus");
                var trayStatusValue = SystemData.PlcDic[0].Read(trayStatus.plcpointAddress);
                if (trayStatusValue == null || Convert.ToInt32(trayStatusValue) == 0)
                {
                    HandyControl.Controls.MessageBox.Error("托盘库开启自动状态!");
                    return;
                }
                BasePlcpoint lineSignal = SystemData.BasePlcpoints.First(t => t.plcpointNo == "linesignal01");
                var lineSignalValue = SystemData.PlcDic[0].Read(lineSignal.plcpointAddress);
                if (lineSignalValue != null && Convert.ToInt32(lineSignalValue) == 1)
                {
                    if (!ReadEmptyLocation())
                    {
                        HandyControl.Controls.MessageBox.Show("有任务正在执行");
                        return;
                    }
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 40);
                    BasePlcpoint basePlcpoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "oneIn");
                    SystemData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "1", basePlcpoint.plcpointLength.ToString());
                    baseEquip.emptyCount += 1;
                    dbContext.Update(baseEquip);
                    dbContext.SaveChanges();
                    HandyControl.Controls.MessageBox.Show("下发成功");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error("未检测到托盘");
                }
            }
            catch (Exception ex)
            {
                if (ex is PlcException)
                {
                    foreach (var item in SystemData.PlcDic)
                    {
                        if (item.Value.IP == ex.Message)
                        {
                            HandyControl.Controls.MessageBox.Error("PLC断开连接，正在重连!");
                            Task.Run(() =>
                            {
                                SystemData.PlcDic[item.Key] = new Plc.S7.Plc(item.Value.CPU, item.Value.IP, item.Value.Port, item.Value.Rack, item.Value.Slot);
                                SystemData.PlcDic[item.Key].Open();
                            });
                        }
                    }
                }
                LogManager.Error(ex);
            }
        }

        private void OneOut_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BasePlcpoint trayStatus = SystemData.BasePlcpoints.First(t => t.plcpointNo == "trayStatus");
                var trayStatusValue = SystemData.PlcDic[0].Read(trayStatus.plcpointAddress);
                if (trayStatusValue == null || Convert.ToInt32(trayStatusValue) == 0)
                {
                    HandyControl.Controls.MessageBox.Error("托盘库开启自动状态!");
                    return;
                }
                BasePlcpoint lineSignal = SystemData.BasePlcpoints.First(t => t.plcpointNo == "linesignal01");
                var lineSignalValue = SystemData.PlcDic[0].Read(lineSignal.plcpointAddress);
                if (lineSignalValue != null && Convert.ToInt32(lineSignalValue) == 0)
                {
                    if (!ReadEmptyLocation())
                    {
                        HandyControl.Controls.MessageBox.Show("有任务正在执行");
                        return;
                    }
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 40);
                    BasePlcpoint basePlcpoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "oneOut");
                    SystemData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "1", basePlcpoint.plcpointLength.ToString());
                    baseEquip.emptyCount -= 1;
                    dbContext.Update(baseEquip);
                    dbContext.SaveChanges();
                    HandyControl.Controls.MessageBox.Show("下发成功");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Show("检测到外侧有托盘，无法出堆垛机");
                }
            }
            catch (Exception ex)
            {
                if (ex is PlcException)
                {
                    foreach (var item in SystemData.PlcDic)
                    {
                        if (item.Value.IP == ex.Message)
                        {
                            HandyControl.Controls.MessageBox.Show("PLC断开连接，正在重连!");
                            Task.Run(() =>
                            {
                                SystemData.PlcDic[item.Key] = new Plc.S7.Plc(item.Value.CPU, item.Value.IP, item.Value.Port, item.Value.Rack, item.Value.Slot);
                                SystemData.PlcDic[item.Key].Open();
                            });
                        }
                    }
                }
                LogManager.Error(ex);
            }
        }

        private void SomeIn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BasePlcpoint trayStatus = SystemData.BasePlcpoints.First(t => t.plcpointNo == "trayStatus");
                var trayStatusValue = SystemData.PlcDic[0].Read(trayStatus.plcpointAddress);
                if (trayStatusValue == null || Convert.ToInt32(trayStatusValue) == 0)
                {
                    HandyControl.Controls.MessageBox.Error("托盘库开启自动状态!");
                    return;
                }
                //BasePlcpoint lineSignal = SystemData.BasePlcpoints.First(t => t.plcpointNo == "linesignal01");
                //var lineSignalValue = SystemData.PlcDic[0].Read(lineSignal.plcpointAddress);
                //if (lineSignalValue != null && Convert.ToInt32(lineSignalValue) == 1)
                {
                    EmptyCountForm emptyCount = new EmptyCountForm(1, 10);
                    emptyCount.ShowDialog();
                    if (EmptyCountForm.IsSelect)
                    {
                        if (!ReadEmptyLocation())
                        {
                            HandyControl.Controls.MessageBox.Show("有任务正在执行");
                            return;
                        }
                        int emptyTaskCount = EmptyCountForm.EmptyTaskCount;
                        using var scope = _host.Services.CreateScope();
                        using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                        BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 40);
                        BasePlcpoint basePlcpoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "someIn");
                        SystemData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "1", basePlcpoint.plcpointLength.ToString());
                        baseEquip.emptyCount = emptyTaskCount;
                        dbContext.Update(baseEquip);
                        dbContext.SaveChanges();
                        HandyControl.Controls.MessageBox.Show("下发成功");
                    }
                }
                //else
                //{
                //    HandyControl.Controls.MessageBox.Show("未检测到托盘");
                //}
            }
            catch (Exception ex)
            {
                if (ex is PlcException)
                {
                    foreach (var item in SystemData.PlcDic)
                    {
                        if (item.Value.IP == ex.Message)
                        {
                            HandyControl.Controls.MessageBox.Show("PLC断开连接，正在重连!");
                            Task.Run(() =>
                            {
                                SystemData.PlcDic[item.Key] = new Plc.S7.Plc(item.Value.CPU, item.Value.IP, item.Value.Port, item.Value.Rack, item.Value.Slot);
                                SystemData.PlcDic[item.Key].Open();
                            });
                        }
                    }
                }
                LogManager.Error(ex);
            }
        }

        private void SomeOut_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BasePlcpoint trayStatus = SystemData.BasePlcpoints.First(t => t.plcpointNo == "trayStatus");
                var trayStatusValue = SystemData.PlcDic[0].Read(trayStatus.plcpointAddress);
                if (trayStatusValue == null || Convert.ToInt32(trayStatusValue) == 0)
                {
                    HandyControl.Controls.MessageBox.Error("托盘库开启自动状态!");
                    return;
                }
                if (!ReadEmptyLocation())
                {
                    HandyControl.Controls.MessageBox.Show("有任务正在执行");
                    return;
                }
                BasePlcpoint lineSignal = SystemData.BasePlcpoints.First(t => t.plcpointNo == "linesignal01");
                var lineSignalValue = SystemData.PlcDic[0].Read(lineSignal.plcpointAddress);
                if (lineSignalValue != null && Convert.ToInt32(lineSignalValue) == 0)
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 40);
                    BasePlcpoint basePlcpoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "someOut");
                    SystemData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "1", basePlcpoint.plcpointLength.ToString());
                    baseEquip.emptyCount = 0;
                    dbContext.Update(baseEquip);
                    dbContext.SaveChanges();
                    HandyControl.Controls.MessageBox.Show("下发成功");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Show("检测到外侧有托盘，无法出堆垛机");
                }
            }

            catch (Exception ex)
            {
                if (ex is PlcException)
                {
                    foreach (var item in SystemData.PlcDic)
                    {
                        if (item.Value.IP == ex.Message)
                        {
                            HandyControl.Controls.MessageBox.Show("PLC断开连接，正在重连!");
                            Task.Run(() =>
                            {
                                SystemData.PlcDic[item.Key] = new Plc.S7.Plc(item.Value.CPU, item.Value.IP, item.Value.Port, item.Value.Rack, item.Value.Slot);
                                SystemData.PlcDic[item.Key].Open();
                            });
                        }
                    }
                }
                LogManager.Error(ex);
            }
        }
        #endregion

        #region 修改托盘库
        private void UpdateEmpty_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //lock (updateLock)
                {
                    EmptyCountForm emptyCountForm = new EmptyCountForm(0, 10);
                    emptyCountForm.ShowDialog();
                    if (EmptyCountForm.IsSelect)
                    {
                        using var scope = _host.Services.CreateScope();
                        using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                        BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 40);
                        baseEquip.emptyCount = EmptyCountForm.EmptyTaskCount;
                        dbContext.Update(baseEquip);
                        dbContext.SaveChanges();
                        HandyControl.Controls.MessageBox.Show("修改成功");
                    }
                }
            }
            catch
            {

            }
        }
        #endregion

        private void WindowHidden_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void btnSendTrayToTurnover_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var baseEquip = dbContext.BaseEquip.First(t => t.objid == 38);
                var agvEquip = SystemData.BaseEquip.First(t => t.objid == 8);
                bool hasTask = dbContext.WcsTask.Where(t => t.endPointId == baseEquip.objid || t.currPointId == baseEquip.objid).Any();
                bool hasTaskManual = dbContext.WcsTaskManual.Where(t => t.endPointId == baseEquip.objid || t.currPointId == baseEquip.objid).Any();
                if (hasTask || hasTaskManual)
                {
                    HandyControl.Controls.MessageBox.Show("有任务正在执行，请等待任务完成后再执行此操作!");
                    return;
                }
                else
                {
                    var endEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipType == 20 && t.equipStatus == 0 && t.emptyCount == 0);
                    if (endEquip == null)
                    {
                        HandyControl.Controls.MessageBox.Show("没有空箱库位!");
                        return;
                    }
                    else
                    {
                        WcsTaskManual task = new()
                        {
                            objid = Global.SnowId.NextId(),
                            taskType = 56,
                            containerNo = baseEquip.containerNo,
                            currPointId = baseEquip.objid,
                            currPointNo = baseEquip.equipNo,
                            nextPointId = agvEquip.objid,
                            nextPointNo = agvEquip.equipNo,
                            endPointId = endEquip.objid,
                            endPointNo = endEquip.equipNo,
                            createTime = DateTime.Now,
                            taskStatus = 0,
                            useFlag = 1,
                            floorNo = 2,
                            fromFloorNo = 2,
                            createBy = "WPF",
                            isEmpty = "0",
                        };
                        dbContext.Add(task);
                        dbContext.SaveChanges();
                        HandyControl.Controls.MessageBox.Show("任务生成成功!");
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
            }
        }

        private void btnSendEmptyTray_Click(object sender, RoutedEventArgs e)
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            var baseEquip = SystemData.BaseEquip.First(t => t.objid == 38);
            var agvEquip = SystemData.BaseEquip.First(t => t.objid == 8);
            bool hasTask = dbContext.WcsTask.Where(t => t.endPointId == baseEquip.objid || t.currPointId == baseEquip.objid).Any();
            bool hasTaskManual = dbContext.WcsTaskManual.Where(t => t.endPointId == baseEquip.objid || t.currPointId == baseEquip.objid).Any();
            if (hasTask || hasTaskManual)
            {
                HandyControl.Controls.MessageBox.Show("有任务正在执行，请等待任务完成后再执行此操作!");
                return;
            }
            else
            {
                var startEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipType == 20 && t.equipStatus == 1 && t.emptyCount == 1);
                if (startEquip == null)
                {
                    BaseEquip firstEmptyEquip = dbContext.BaseEquip.First(t => t.objid == 40);
                    if (firstEmptyEquip.emptyCount > 0)
                    {
                        MessageBoxResult MessageBoxResult = HandyControl.Controls.MessageBox.Show("二楼未找到一个托盘的库位，是否从一楼调取？", "提示", MessageBoxButton.OKCancel);
                        if (MessageBoxResult == MessageBoxResult.OK)
                        {
                            if (ReadEmptyLocation())
                            {
                                BasePlcpoint oneOutPoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "oneOut");
                                SystemData.PlcDic[0].WriteToPoint(oneOutPoint.plcpointAddress, "1", oneOutPoint.plcpointLength.ToString());
                                firstEmptyEquip.emptyCount -= 1;
                                dbContext.Update(firstEmptyEquip);
                                dbContext.SaveChanges();
                                HandyControl.Controls.MessageBox.Show("下发成功");
                            }
                            else
                            {
                                HandyControl.Controls.MessageBox.Show("一楼托盘库忙碌中，请稍后再试!");
                            }
                        }
                    }
                    else
                    {
                        HandyControl.Controls.MessageBox.Show("未找到一个托盘的库位");
                        return;
                    }
                }
                else
                {
                    WcsTaskManual task = new()
                    {
                        objid = Global.SnowId.NextId(),
                        taskType = 54,
                        containerNo = startEquip.containerNo,
                        currPointId = startEquip.objid,
                        currPointNo = startEquip.equipNo,
                        nextPointId = agvEquip.objid,
                        nextPointNo = agvEquip.equipNo,
                        endPointId = baseEquip.objid,
                        endPointNo = baseEquip.equipNo,
                        createTime = DateTime.Now,
                        taskStatus = 0,
                        useFlag = 1,
                        floorNo = 2,
                        fromFloorNo = 2,
                        createBy = "WPF",
                        isEmpty = "0",
                    };
                    dbContext.Add(task);
                    dbContext.SaveChanges();
                    HandyControl.Controls.MessageBox.Show("任务生成成功!");
                }
            }
        }

        /// <summary>
        /// 读取一楼托盘库位是否空闲
        /// </summary>
        /// <returns></returns>
        private bool ReadEmptyLocation()
        {
            var oneOutPoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "oneOut");
            var someOutPoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "someOut");
            var oneInPoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "oneIn");
            var someInPoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == "someIn");
            var oneOutValue = SystemData.PlcDic[0].Read(oneOutPoint.plcpointAddress);
            var someOutValue = SystemData.PlcDic[0].Read(someOutPoint.plcpointAddress);
            var oneInValue = SystemData.PlcDic[0].Read(oneInPoint.plcpointAddress);
            var someInValue = SystemData.PlcDic[0].Read(someInPoint.plcpointAddress);
            if (oneOutValue != null && someOutValue != null && oneInValue != null && someInValue != null)
            {
                if (Convert.ToInt32(oneOutValue) == 0 && Convert.ToInt32(someOutValue) == 0 && Convert.ToInt32(oneInValue) == 0 && Convert.ToInt32(someInValue) == 0)
                {
                    return true;
                }
            }
            return false;
        }

        private void clearLocation_Click(object sender, RoutedEventArgs e)
        {
            if (this.EmptyEquip.SelectedItem is BaseEquip equip)
            {
                MessageBoxResult MessageBoxResult = HandyControl.Controls.MessageBox.Show($"是否清除{equip.equipName}的托盘信息？", "提示", MessageBoxButton.OKCancel);
                if (MessageBoxResult == MessageBoxResult.OK)
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == equip.objid);
                    baseEquip.emptyCount = 0;
                    baseEquip.equipStatus = 0;
                    dbContext.Update(baseEquip);
                    dbContext.SaveChanges();
                    HandyControl.Controls.MessageBox.Show("清除成功");
                }
            }
        }

        private void outLocation_Click(object sender, RoutedEventArgs e)
        {
            if (this.EmptyEquip.SelectedItem is BaseEquip equip)
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == equip.objid);
                bool hastask = dbContext.WcsTask.Where(t => t.endPointId == baseEquip.objid || t.currPointId == baseEquip.objid).Any();
                bool hasTaskManual = dbContext.WcsTaskManual.Where(t => t.currPointId == baseEquip.objid || t.endPointId == baseEquip.objid).Any();
                if (hastask || hasTaskManual)
                {
                    HandyControl.Controls.MessageBox.Show("已存在当前库位的任务");
                    return;
                }
                if (baseEquip.emptyCount > 0)
                {
                    FloorForm floorForm = new FloorForm(new List<int>() { 1, 3 });
                    floorForm.ShowDialog();
                    if (FloorForm.SelecetedFloorNo != 0)
                    {
                        WcsTaskManual task = new()
                        {
                            objid = Global.SnowId.NextId(),
                            taskType = 57,
                            containerNo = "00000000",
                            currPointId = baseEquip.objid,
                            currPointNo = baseEquip.equipNo,
                            nextPointId = 8,
                            qty = baseEquip.emptyCount,
                            endPointId = FloorForm.SelecetedFloorNo,
                            endPointNo = $"TSJ_0{FloorForm.SelecetedFloorNo}",
                            useFlag = 1,
                            taskStatus = 0,
                            fromFloorNo = 2,
                            floorNo = FloorForm.SelecetedFloorNo
                        };
                        dbContext.Add(task);
                        dbContext.SaveChanges();
                        HandyControl.Controls.MessageBox.Show("下发成功");
                    }
                }
                else
                {
                    HandyControl.Controls.MessageBox.Show("库位已空!");
                }
            }
        }
        /// <summary>
        /// 任务完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void taskCompeleted_Click(object sender, RoutedEventArgs e)
        {

        }

        private void querenruku_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.firstRFID.Text))
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                BaseEquip baseEquip = dbContext.BaseEquip.First(t => t.objid == 1);
                baseEquip.containerNo = null;
                dbContext.Update(baseEquip);
                dbContext.SaveChanges();
                HandyControl.Controls.MessageBox.Show("确认入库成功!");
            }
            else
            {
                HandyControl.Controls.MessageBox.Show("未扫描到RFID！");
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteUser(object sender, RoutedEventArgs e)
        {
            try
            {
                if (UserData.SelectedItem is SysUser user)
                {
                    if (user.OBJID == 1)
                    {
                        HandyControl.Controls.MessageBox.Show("不能删除根用户!");
                        return;
                    }
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    dbContext.SysUser.Remove(user);
                    dbContext.SaveChanges();
                    HandyControl.Controls.MessageBox.Show("删除成功!");
                    GetMenu();
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectUser_Click(object sender, RoutedEventArgs e)
        {
            GetUser();
        }

        private void GetUser()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            UserData.ItemsSource = dbContext.SysUser.WhereIf(!string.IsNullOrEmpty(LoginName.Text), t => t.UserName.Contains(LoginName.Text)).ToList();
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddUser_Click(object sender, RoutedEventArgs e)
        {

        }

        private void GetMenu()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            var sysMenus = dbContext.SysMenu.Where(t => t.MenuVisble == 1).ToList();
            var sysRoles = dbContext.SysRole.Where(t => t.UserId == UserId).ToList();
            List<long?> roleIds = sysRoles.Select(t => t.RoleId).ToList();
            foreach (var menu in sysMenus)
            {
                if (FindName(menu.MenuName) is TabItem tabItem)
                {
                    if (roleIds.Contains(menu.OBJID))
                    {
                        tabItem.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        tabItem.Visibility = Visibility.Collapsed;
                    }
                }
            }
            if (sysRoles.Count() == 0)
            {
                TabControl.SelectedIndex = 0;
            }
        }

        private void SelectUserRole(object sender, RoutedEventArgs e)
        {
            try
            {
                if (UserData.SelectedItem is SysUser user)
                {
                    //if (user.OBJID == 1)
                    //{
                    //    HandyControl.Controls.MessageBox.Show("不能修改根用户!");
                    //    return;
                    //}
                    MenuList menuList = new MenuList(_host, user.OBJID);
                    menuList.ShowDialog();
                    GetMenu();
                }
            }
            catch
            {

            }
        }

        private void SelectInventoryButton_Click(object sender, RoutedEventArgs e)
        {
            GetInvertoryData();
        }

        /// <summary>
        /// 添加盘库任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddInventoryButton_Click(object sender, RoutedEventArgs e)
        {
            InventoryMaterialWindow window = new InventoryMaterialWindow(_host);
            window.ShowDialog();
            return;
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var Orders = dbContext.WmsInventoryCheck.Where(t => t.CheckStatus == "0" || t.CheckStatus == "1").ToList();
                if (Orders != null && Orders.Count > 0)
                {
                    MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show("已经有盘库任务是否继续创建新盘库任务?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                    if (messageBoxResult == MessageBoxResult.OK)
                    {
                        Orders.ForEach(t =>
                        {
                            t.CheckStatus = "2";
                        });
                        dbContext.UpdateRange(Orders);
                        int locationCount = dbContext.WmsBaseLocation.Where(t => t.warehouseId == 512).Count();
                        dbContext.Add(new WmsInventoryCheck()
                        {
                            CreateTime = DateTime.Now,
                            CheckStatus = "0",
                            LocationAmount = locationCount,
                            InventoriedAmount = 0,
                            InventoryingAmount = 0,
                            WarehouseId = 512,
                            CreateBy = "WCS"
                        });
                        dbContext.SaveChanges();
                        HandyControl.Controls.Growl.Info("创建盘库任务成功!");
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show("是否创建一个盘库任务?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                    if (messageBoxResult == MessageBoxResult.OK)
                    {
                        int locationCount = dbContext.WmsBaseLocation.Where(t => t.warehouseId == 512).Count();
                        dbContext.Add(new WmsInventoryCheck()
                        {
                            CreateTime = DateTime.Now,
                            CheckStatus = "0",
                            LocationAmount = locationCount,
                            InventoriedAmount = 0,
                            InventoryingAmount = 0,
                            WarehouseId = 512,
                            CreateBy = "WCS"
                        });
                        dbContext.SaveChanges();
                        HandyControl.Controls.Growl.Info("创建盘库任务成功!");
                    }
                }
            }
            catch
            {

            }
            GetInvertoryData();
        }

        private void GetInvertoryData()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            try
            {
                var list = dbContext.WmsInventoryCheck
                    .Where(t => t.WarehouseId == 512)
                    .OrderByDescending(t => t.CreateTime).Skip((this.Pagination3.PageIndex - 1) * this.pageCount).Take(this.pageCount).ToList();
                this.InventoryMaterial.ItemsSource = list.Select(t =>
                    new
                    {
                        InventoryCheckId = t.InventoryCheckId,
                        InventoriedAmount = t.InventoriedAmount,
                        BeginTime = t.BeginTime,
                        CheckStatus = t.CheckStatus == "0" ? "未开始" : t.CheckStatus == "1" ? "盘点中" : t.CheckStatus == "2" ? "已完成" : "",
                        CreateBy = t.CreateBy,
                        CreateTime = t.CreateTime,
                        EndTime = t.EndTime,
                        InventoryCheckCode = t.InventoryCheckCode,
                        InventoryingAmount = t.InventoryingAmount,
                        LocationAmount = t.LocationAmount,
                        Remark = t.Remark,
                        UpdateBy = t.UpdateBy,
                        UpdateTime = t.UpdateTime,
                        WarehouseId = t.WarehouseId,
                    });

                this.InventoryMaterial.Items.Refresh();
                if (list.Count == 0)
                {
                    HandyControl.Controls.MessageBox.Show("没有数据!");
                }
            }
            catch
            {

            }
        }

        private void InventoryTaskButton_Click(object sender, RoutedEventArgs e)
        {
            InventoryTaskForm inventoryTaskForm = new InventoryTaskForm(this._host);
            inventoryTaskForm.ShowDialog();
        }

        //选择出库
        private void SelectOutBtn_Click(object sender, RoutedEventArgs e)
        {
            SelectOutRawForm selectOutRawForm = new SelectOutRawForm(this._host, "", 1);
            selectOutRawForm.ShowDialog();
        }
        //选择退库
        private void SelectReturnBtn_Click(object sender, RoutedEventArgs e)
        {
            SelectOutRawForm selectOutRawForm = new SelectOutRawForm(this._host, "1", 2);
            selectOutRawForm.ShowDialog();
        }

        private void ContineOutBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                BaseEquip baseEquip = dbContext.BaseEquip.Where(t => t.objid == 10).First();
                if (!string.IsNullOrEmpty(baseEquip.endStationCode))
                {
                    List<WcsTask> wcsTasks = dbContext.WcsTask.Where(t => t.taskType == 30).ToList();
                    if (wcsTasks != null && wcsTasks.Count > 0)
                    {
                        scanOutMsg.Text = "已经有出库任务请等待出库完成后，再进行继续出库!";
                        return;
                    }

                    baseEquip.IsOut = 1;
                    dbContext.Update(baseEquip);
                    dbContext.SaveChanges();
                    scanOutMsg.Text = "继续出库成功!";
                }
                else
                {
                    scanOutMsg.Text = "当前无正在出库单";
                }
            }
            catch
            {

            }
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                // 触发按钮的点击事件
                CallSelectedItem.Clear();
                GetPersonCallMaterialData();
            }
        }

        /// <summary>
        /// 扫描入库enter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScanInKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                // 触发按钮的点击事件
                ScanInBox();
            }
        }

        #region 移库方法
        private void rawSourceBox_TextChanged(object sender, RoutedEventArgs e)
        {
            if (this.rawSourceBox.Text.Length >= 1 && this.rawSourceBox.Text.Length < 15)
            {
                this.RemoveMsg.Text = "";
                return;
            }
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                //WcsTask? wcsTask = dbContext.WcsTask.Where(t => t.containerNo == this.rawSourceBox.Text).FirstOrDefault();
                //if (wcsTask == null)
                //{

                //    this.RemoveMsg.Text = $"未找到该托盘{this.rawSourceBox.Text}的移库任务!";
                //    this.rawSourceBox.Text = "";
                //    return;
                //}
                //else
                {
                    rawSourceBarCode.Focus();
                }
            }
            catch (Exception ex)
            {
                this.RemoveMsg.Text = ex.Message;
            }
        }

        private void rawSourceBarCode_TextChanged(object sender, RoutedEventArgs e)
        {
            if (this.rawSourceBarCode.Text.Length < 19)
            {
                rawSourceMaterialName.Text = "";
                rawSourceMaterialSpec.Text = "";
                removeScan.Text = "";
                return;
            }
            string barCode = rawSourceBarCode.Text;
            try
            {

                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

                WmsRawStock? wmsRawStock = dbContext.WmsRawStock.Where(t => t.palletInfoCode == this.rawSourceBox.Text)
                   .Where(t => t.instockBatch == barCode)
                   .FirstOrDefault();
                if (wmsRawStock == null)
                {
                    RemoveMsg.Text = $"未在{this.rawSourceBox.Text}托盘中找到{barCode}条码！";
                    rawSourceBarCode.Text = string.Empty;
                    rawSourceMaterialName.Text = "";
                    rawSourceMaterialSpec.Text = "";
                    return;
                }

                var material = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == barCode);
                if (material == null)
                {
                    RemoveMsg.Text = $"未查询{barCode}条码内容!";
                    rawSourceBarCode.Text = string.Empty;
                }
                else
                {
                    var mesBaseMaterialInfo = dbContext.MesBaseMaterialInfo.FirstOrDefault(t => t.MaterialId == material.materialId);
                    if (mesBaseMaterialInfo == null)
                    {
                        RemoveMsg.Text = $"未查询{barCode}绑定的物料信息!";
                        rawSourceBarCode.Text = string.Empty;
                    }
                    else
                    {
                        rawSourceMaterialName.Text = mesBaseMaterialInfo.MaterialName;
                        rawSourceMaterialSpec.Text = mesBaseMaterialInfo.MaterialSpec;
                        this.removeScan.Text = string.Format("{0:0.00}", wmsRawStock.totalAmount - wmsRawStock.frozenAmount);

                        removeSourceBox.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                RemoveMsg.Text = $"查询{barCode}条码内容异常!";
                rawSourceBarCode.Text = string.Empty;
                rawSourceMaterialName.Text = "";
                rawSourceMaterialSpec.Text = "";
            }
        }



        private void removeSourceBox_TextChanged(object sender, RoutedEventArgs e)
        {
            if (this.rawSourceBox.Text.Length >= 15)
            {
                removeSourceBarCode.Focus();
            }

        }


        private void removeSourceBarCode_TextChanged(object sender, RoutedEventArgs e)
        {
            if (this.removeSourceBarCode.Text.Length < 19)
            {
                removeSourceMaterialName.Text = "";
                removeSourceMaterialSpec.Text = "";
                this.removeTotalStock.Text = "";
                return;
            }
            string barCode = removeSourceBarCode.Text;
            try
            {

                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

                //WmsRawStock? wmsRawStock = dbContext.WmsRawStock.Where(t => t.palletInfoCode == this.removeSourceBox.Text)
                //   .Where(t => t.instockBatch == barCode)
                //   .FirstOrDefault();
                //if (wmsRawStock == null)
                //{
                //    RemoveMsg.Text = $"未在目标托盘中找到条码,请打印粘贴后重新扫描！";
                //    removeSourceBarCode.Text = string.Empty;
                //    removeSourceMaterialName.Text = "";
                //    removeSourceMaterialSpec.Text = "";
                //    return;
                //}

                var material = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == barCode);
                if (material == null)
                {
                    RemoveMsg.Text = $"未查询{barCode}条码信息!";
                    removeSourceBarCode.Text = string.Empty;
                }
                else
                {
                    var mesBaseMaterialInfo = dbContext.MesBaseMaterialInfo.FirstOrDefault(t => t.MaterialId == material.materialId);
                    if (mesBaseMaterialInfo == null)
                    {
                        RemoveMsg.Text = $"未查询{barCode}绑定的物料信息!";
                        removeSourceBarCode.Text = string.Empty;
                    }
                    else
                    {
                        removeSourceMaterialName.Text = mesBaseMaterialInfo.MaterialName;
                        removeSourceMaterialSpec.Text = mesBaseMaterialInfo.MaterialSpec;

                    }
                }
                //判断目标库位是否有该物料
                WmsRawStock? removeStock = dbContext.WmsRawStock.Where(t => t.instockBatch == this.removeSourceBarCode.Text).FirstOrDefault();
                if (removeStock != null)
                {
                    this.removeTotalStock.Text = string.Format("{0:0.00}", removeStock.totalAmount);
                }
            }
            catch (Exception ex)
            {
                RemoveMsg.Text = $"查询{barCode}条码内容异常!";
                removeSourceBarCode.Text = string.Empty;
                removeSourceMaterialName.Text = "";
                removeSourceMaterialSpec.Text = "";
            }
        }

        private void btnRemoveConfirmBox_Click(object sender, RoutedEventArgs e)
        {
            this.RemoveMsg.Text = "";
            if (string.IsNullOrEmpty(this.rawSourceBox.Text))
            {
                this.RemoveMsg.Text = "请先选择原托盘!";
                return;
            }
            if (string.IsNullOrEmpty(this.rawSourceBarCode.Text))
            {
                this.RemoveMsg.Text = "请先选择原条码!";
                return;
            }
            if (string.IsNullOrEmpty(this.removeSourceBox.Text))
            {
                this.RemoveMsg.Text = "请先选择移库目标托盘!";
                return;
            }
            if (string.IsNullOrEmpty(this.removeSourceBarCode.Text))
            {
                this.RemoveMsg.Text = "请先选择移库目标条码!";
                return;
            }
            decimal amount = decimal.Parse(this.removeScan.Text);
            if (amount <= 0)
            {
                this.RemoveMsg.Text = "移库数量需要大于0!";
                return;
            }


            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

            WmsRawStock? sourceWmsRawStock = dbContext.WmsRawStock
                       .Where(t => t.instockBatch == this.rawSourceBarCode.Text).FirstOrDefault();
            if (sourceWmsRawStock == null)
            {
                this.RemoveMsg.Text = "该条码无库存，请核查";
                return;
            }
            if (amount > (sourceWmsRawStock.totalAmount - sourceWmsRawStock.frozenAmount))
            {
                this.RemoveMsg.Text = "移库数量不能大于库存数量";
                return;
            }

            try
            {

                WmsBaseLocation removeLocation = dbContext.WmsBaseLocation.Where(t => t.containerCode == this.removeSourceBox.Text).First();
                WmsBaseLocation sourceLocation = dbContext.WmsBaseLocation.Where(t => t.containerCode == this.rawSourceBox.Text).First();

                //1.先校验物料类型是否一致
                var rawBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == this.rawSourceBarCode.Text);
                var removeBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == this.removeSourceBarCode.Text);
                if (rawBarcodeInfo.materialId != removeBarcodeInfo.materialId)
                {
                    this.RemoveMsg.Text = "两个条码物料类型不同，请更换移库目标条码!";
                    return;
                }
                if (rawBarcodeInfo.PurchaseOrderId != removeBarcodeInfo.PurchaseOrderId)
                {
                    this.RemoveMsg.Text = "两个条码采购订单不同，请更换移库目标条码!";
                    return;
                }
                //判断目标库位是否有该物料
                WmsRawStock? removeStock = dbContext.WmsRawStock.Where(t => t.instockBatch == this.removeSourceBarCode.Text).FirstOrDefault();
                if (removeStock != null)
                {
                    sourceWmsRawStock.totalAmount -= decimal.Parse(this.removeScan.Text);
                    removeStock.totalAmount += decimal.Parse(this.removeScan.Text);
                    dbContext.WmsRawStock.Update(removeStock);
                    dbContext.WmsRawStock.Update(sourceWmsRawStock);
                }
                else
                {
                    sourceWmsRawStock.totalAmount -= decimal.Parse(this.removeScan.Text);

                    removeStock = new WmsRawStock()
                    {
                        materialId = removeBarcodeInfo.materialId,
                        supplierId = removeBarcodeInfo.manufacturerId,
                        instockBatch = this.removeSourceBarCode.Text,
                        locationCode = removeLocation.locationCode,
                        stockType = "1",
                        palletInfoCode = removeLocation.containerCode,
                        totalAmount = decimal.Parse(this.removeScan.Text),
                        activeFlag = "1",
                        occupyAmount = 0,
                        completeFlag = "1",
                        frozenAmount = 0,
                        instockDate = System.DateTime.Now,
                        rawStockId = Global.SnowId.NextId(),
                        saleOrderId = removeBarcodeInfo.saleOrderId == null ? 0 : removeBarcodeInfo.saleOrderId,
                        warehouseFloor = 5,
                        warehouseId = 512,
                        createBy = "扫描入库",
                        createDate = System.DateTime.Now,
                        safeFlag = removeBarcodeInfo.safeFlag
                    };
                    dbContext.WmsRawStock.Add(removeStock);
                    dbContext.WmsRawStock.Update(sourceWmsRawStock);
                }

                if (sourceWmsRawStock.totalAmount == 0)
                {
                    dbContext.WmsRawStock.Remove(sourceWmsRawStock);
                }

                #region 插入移库记录
                WmsMove wmsMove = new WmsMove();
                wmsMove.MoveId = Global.SnowId.NextId();
                wmsMove.TaskCode = Global.SnowId.NextId().ToString();
                wmsMove.WarehouseId = removeLocation.warehouseId;
                wmsMove.OriLocationCode = sourceLocation.locationCode;
                wmsMove.TargetLocationCode = removeLocation.locationCode;
                wmsMove.InstockBatch = sourceWmsRawStock.instockBatch;
                wmsMove.MaterialId = sourceWmsRawStock.materialId;
                wmsMove.PlanAmount = decimal.Parse(this.removeScan.Text);
                wmsMove.RealOutstockAmount = decimal.Parse(this.removeScan.Text);
                wmsMove.RealInstockAmount = decimal.Parse(this.removeScan.Text);
                wmsMove.OperationType = "1";
                wmsMove.MoveWay = "1";
                wmsMove.MoveType = "1";
                wmsMove.AuditStatus = "1";
                wmsMove.ExecuteStatus = "2";
                wmsMove.UpdateBy = "WPF";
                wmsMove.UpdateDate = DateTime.Now;
                wmsMove.BeginTime = DateTime.Now;
                wmsMove.EndTime = DateTime.Now;

                WmsMoveDetail wmsMoveDetail = new WmsMoveDetail();
                wmsMoveDetail.MoveId = wmsMove.MoveId;
                wmsMoveDetail.MaterialBarcode = rawBarcodeInfo.barcodeInfo;
                wmsMoveDetail.InstockBatch = rawBarcodeInfo.batchCode;
                wmsMoveDetail.MaterialId = (long)rawBarcodeInfo.materialId;
                wmsMoveDetail.LocationCode = removeLocation.locationCode;
                wmsMoveDetail.PlanAmount = decimal.Parse(this.removeScan.Text);
                wmsMoveDetail.RealInstockAmount = decimal.Parse(this.removeScan.Text);
                wmsMoveDetail.RealAmount = decimal.Parse(this.removeScan.Text);
                wmsMoveDetail.ExecuteStatus = "2";
                wmsMoveDetail.ExecuteTime = DateTime.Now;
                wmsMoveDetail.ExecuteEndTime = DateTime.Now;
                wmsMoveDetail.ExecutePerson = "WPF";
                wmsMoveDetail.UpdateBy = "WPF";
                wmsMoveDetail.UpdateDate = DateTime.Now;

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

                dbContext.SaveChanges();

                this.RemoveMsg.Text = $"移库成功!,原料箱库存:{string.Format("{0:0.00}", sourceWmsRawStock.totalAmount)},新料箱库存:{string.Format("{0:0.00}", removeStock.totalAmount)}";
                removeSourceBarCode.Text = string.Empty;
                removeSourceMaterialName.Text = "";
                removeSourceMaterialSpec.Text = "";
                rawSourceBarCode.Text = string.Empty;
                rawSourceMaterialName.Text = "";
                rawSourceMaterialSpec.Text = "";
                this.removeScan.Text = "";
                this.removeTotalStock.Text = "";
            }
            catch (Exception ex)
            {
                Console.Write("移库失败!,异常:" + ex.Message);
            }
        }

        #endregion


        private void OutEnter(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                // 触发按钮的点击事件
                OutRaw();
            }

        }

        private void LocationPersonBox_Click(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox check)
            {
                if (check.IsChecked == true)
                {
                    if (LoadMaterial1.SelectedItem is LocationDto location)
                    {
                        locationDtos.Add(location);
                    }
                }
                else
                {
                    if (LoadMaterial1.SelectedItem is LocationDto location)
                    {
                        locationDtos.Remove(location);
                    }
                }
            }
        }

        private void LockLocation_Click(object sender, RoutedEventArgs e)
        {
            if (locationDtos.Count == 0)
            {
                HandyControl.Controls.MessageBox.Show("请选择库位!");
                return;
            }
            List<string> locationCodes = locationDtos.Select(t => t.LocationCode).ToList();
            MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show($"锁定库位{string.Join("\n", locationCodes)}", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (messageBoxResult == MessageBoxResult.OK)
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                using var transaction = dbContext.Database.BeginTransaction();
                try
                {
                    List<WmsBaseLocation> wmsBaseLocations = dbContext.WmsBaseLocation.Where(t => locationCodes.Contains(t.locationCode)).ToList();
                    foreach (var location in wmsBaseLocations)
                    {
                        location.locationStatus = "3";
                        location.ExceptionDesc = "人工锁定";
                        SystemData.AlarmLocation(location, dbContext);
                        dbContext.Update(location);
                    }
                    dbContext.SaveChanges();
                    transaction.Commit();
                    locationDtos.Clear();
                    GetBaseLocations();
                    HandyControl.Controls.MessageBox.Show("锁定成功!");

                }
                catch
                {
                    transaction.Rollback();
                }
            }
        }

        private void UnLockLocation_Click(object sender, RoutedEventArgs e)
        {
            if (locationDtos.Count == 0)
            {
                HandyControl.Controls.MessageBox.Show("请选择库位!");
                return;
            }
            List<string> locationCodes = locationDtos.Select(t => t.LocationCode).ToList();
            MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show($"解锁库位{string.Join("\n", locationCodes)}", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (messageBoxResult == MessageBoxResult.OK)
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                using var transaction = dbContext.Database.BeginTransaction();
                try
                {
                    List<WmsBaseLocation> wmsBaseLocations = dbContext.WmsBaseLocation.Where(t => locationCodes.Contains(t.locationCode)).ToList();
                    foreach (var location in wmsBaseLocations)
                    {
                        location.locationStatus = "1";
                        location.ExceptionDesc = "人工解锁";
                        SystemData.UnAlarmLocation(location, dbContext);
                        dbContext.Update(location);
                    }
                    dbContext.SaveChanges();
                    transaction.Commit();
                    locationDtos.Clear();
                    GetBaseLocations();
                    HandyControl.Controls.MessageBox.Show("解锁成功!");

                }
                catch
                {
                    transaction.Rollback();
                }
            }
        }


        /// <summary>
        /// 取消预调度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelPreScheduling_Click(object sender, RoutedEventArgs e)
        {
            // 调用取消预调度接口

            string executeResult = HttpHelper.SendPostMessage("172.16.12.100", 5001, "wcs/RecieveRcs/CancelPreScheduling", null, "application/Json");
            // string executeResult = HttpHelper.SendPostMessage("127.0.0.1", 5001, "wcs/RecieveRcs/CancelPreScheduling", null, "application/Json");
            var executeReponse = JsonConvert.DeserializeObject<ReponseMessage>(executeResult);
            if (executeReponse != null && executeReponse.code == "0")
            {
                MessageBox.Show("取消预调度成功!");
            }
            else
            {
                MessageBox.Show($"取消预调度失败!");
            }
        }
    }
}

