using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Wpf.TaskForm.Inventory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Media3D;

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

        public InventoryDetails(IHost host,long id)
        {
            InitializeComponent();
            _host = host;
            inventoryCheckId = id;
        }

        //在载入行的时候在行表头添加编号	
        private void dgvMH_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = (e.Row.GetIndex() + 1).ToString();
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                GetData(); 
            }
            catch
            {
                Console.WriteLine("InventoryDetails-Window_Loaded加载失败");
            }
        }

        private void GetData()
        {
            int amount = 0;
            if (inventoryCheckId == 0) return;
            using var scope = _host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

            List<WmsInventoryCheckDetail> wmsInventoryCheckDetails = dbContext.WmsInventoryCheckDetail
                .Where(t => t.InventoryCheckId == inventoryCheckId)
                .ToList();
            List<long?> list = wmsInventoryCheckDetails.Select(t => t.MaterialId).Distinct().ToList();
            List<MesBaseMaterialInfo> mesBaseMaterialInfos = dbContext.MesBaseMaterialInfo.Where(t => list.Contains(t.MaterialId)).ToList();
            this.InventoryDetailsDataGrid.ItemsSource = wmsInventoryCheckDetails.Select(t =>
                new
                {
                    Id  = ++amount,
                    LocationCode = t.LocationCode,
                    MaterialId   = t.MaterialId,
                    MaterialName = mesBaseMaterialInfos.FirstOrDefault(m => m.MaterialId == t.MaterialId)?.MaterialSpec, 
                    StockAmount = t.StockAmount,
                    RealAmount = t.RealAmount,
                    UpdateDate = t.UpdateTime,
                });
            this.InventoryDetailsDataGrid.Items.Refresh();
           

        }

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

     
    }
}
