using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Wpf.Scan;
using Khd.Core.Wpf.TaskForm.Inventory;
using Masuit.Tools.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Khd.Core.Wpf.TaskForm
{
    /// <summary>
    /// InventoryTaskForm.xaml 的交互逻辑
    /// </summary>
    public partial class InventoryTaskForm : Window
    {
       
        private readonly IHost _host;

        public InventoryTaskForm(IHost host)
        {
            InitializeComponent();
            _host = host;

            Thread scanThread = new Thread(ScanMessage);
            scanThread.IsBackground = true;
            scanThread.Start();
            UpdateAmountWindow.RefreshDelegateEvent += GetData;
        }



        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 void txtInBox_TextChanged(object sender, RoutedEventArgs e)
        {
            if(txtInBox.Text.Length == 15)
            {
                GetData(txtInBox.Text);
            }
            else
            {
                this.InventoryDataGrid.ItemsSource = null;
            }
        }
            private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                using var scope = _host.Services.CreateScope();
                var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var wcsTasks = dbContext.WcsTask.Where(t => t.taskType == 100 && t.taskStatus == 6).ToList();
                //if (wcsTasks.Count > 0)
                //{
                //    this.ContainerCodeBox.ItemsSource = wcsTasks.Distinct();
                //}
                //else
                //{
                //    HandyControl.Controls.MessageBox.Show("未找到盘库已完成的小车任务！");
                //    this.Close();
                //}
            }
            catch
            {

            }
        }

        private void GetData(string containerNo)
        {
                using var scope = _host.Services.CreateScope();
                var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var wcsTask = dbContext.WcsTask
                    .Where(t => t.taskType == 100)
                    .Where(t => t.containerNo == containerNo).FirstOrDefault();
                if (wcsTask != null)
                {
                WmsInventoryCheck check = dbContext.WmsInventoryCheck.Where(x => x.CheckStatus == "1").FirstOrDefault();
                if (check == null)
                {
                    HandyControl.Controls.MessageBox.Show("当前无正在执行的盘库任务");
                    return;
                }
                    var wmsInventoryCheckDetails = dbContext.WmsInventoryCheckDetail
                        .Where(t => t.InventoryCheckId == check.InventoryCheckId)
                        .Where(t => t.LocationCode == wcsTask.currPointNo)
                        .Where(t => t.CheckStatus == "1")
                        .ToList();
                    List<long?> list = wmsInventoryCheckDetails.Select(t => t.MaterialId).Distinct().ToList();
                    List<MesBaseMaterialInfo> mesBaseMaterialInfos = dbContext.MesBaseMaterialInfo.Where(t => list.Contains(t.MaterialId)).ToList();
                //this.InventoryDataGrid.ItemsSource = wmsInventoryCheckDetails.GroupBy(t => t.MaterialId).Select(t =>
                //    new
                //    {
                //        //ContainerNo = wcsTask.containerNo,
                //        MaterialBatch = t.FirstOrDefault(n => n.MaterialId == t.Key)?.MaterialBatch,
                //        MaterialSpec = mesBaseMaterialInfos.FirstOrDefault(m => m.MaterialId == t.Key)?.MaterialSpec,
                //        MaterialName = mesBaseMaterialInfos.FirstOrDefault(m => m.MaterialId == t.Key)?.MaterialName,
                //        StockAmount = t.Sum(n => n.StockAmount),
                //        LocationCode = wcsTask.currPointNo,
                //        MaterialId = t.Key,
                //        //RealAmount = (t.Sum(n => n.RealAmount)).ToString(),
                //    });

                this.InventoryDataGrid.ItemsSource = wmsInventoryCheckDetails.Select(t =>
                       new
                       {
                           //ContainerNo = wcsTask.containerNo,
                           MaterialBatch = t.MaterialBatch,
                           MaterialSpec = mesBaseMaterialInfos.FirstOrDefault(m => m.MaterialId == t.MaterialId)?.MaterialSpec,
                           MaterialName = mesBaseMaterialInfos.FirstOrDefault(m => m.MaterialId == t.MaterialId)?.MaterialName,
                           StockAmount = t.StockAmount,
                           LocationCode = wcsTask.currPointNo,
                           MaterialId = t.MaterialId,
                           //RealAmount = (t.Sum(n => n.RealAmount)).ToString(),
                       });


                this.InventoryDataGrid.Items.Refresh();
                    if (wmsInventoryCheckDetails.Count == 0)
                    {
                        HandyControl.Controls.MessageBox.Show("该料箱为空料箱");
                    }
            }
            else
            {
                HandyControl.Controls.MessageBox.Show("请扫描盘库任务里面的料箱");
            }
            
           
        }

        private void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {

            if (!string.IsNullOrEmpty(txtInBox.Text))
            {
                AddNewStockForm editForm = new AddNewStockForm(_host, txtInBox.Text);
               
                editForm.ShowDialog();
               
            }
            else
            {
                HandyControl.Controls.MessageBox.Show("请先选择料箱号！");
            }

        }

        private void Update_Click(object sender, RoutedEventArgs e)
        {
            if (this.InventoryDataGrid.SelectedItem != null)
            {
                dynamic item = this.InventoryDataGrid.SelectedItem;
                UpdateAmountWindow updateStockAmount = new UpdateAmountWindow(_host, item.MaterialBatch, item.LocationCode, txtInBox.Text);
                updateStockAmount.ShowDialog();

                //long materialId = item.MaterialId;
                //string containerNo = txtInBox.Text;
                //string materialName = item.MaterialName;
                //string locationCode = item.LocationCode;
                //string realAmount = item.RealAmount;

                //GetData(txtInBox.Text);
            }
        }

    }
}
