using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Khd.Core.Wpf.WindowPage
{
    /// <summary>
    /// StockWindow.xaml 的交互逻辑
    /// </summary>
    public partial class StockWindow : Window
    {
        private IHost host = null;
        public StockWindow(IHost _host,long locationId)
        {
            host = _host;
            InitializeComponent();
            Init(locationId);
        }

        public async Task Init(long locationId)
        {
            using var scope = host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            var location = await dbContext.WmsBaseLocation.Where(x => x.locationId == locationId).FirstOrDefaultAsync();
            positionRowTxt.Text = location.locRow.ToString();
            positionColumnTxt.Text = location.locColumn.ToString();
            positionLayerTxt.Text = location.layerNum.ToString();
            locationTxt.Text = location.locationCode;
            palletTxt.Text = location.containerCode;
            
            var stockList = await dbContext.WmsRawStock.Where(x => x.palletInfoCode == location.containerCode).ToListAsync();
            if(stockList != null && stockList.Count > 0)
            {
                // 获取所有库存物料 ID
                var materialIds = stockList.Select(stock => stock.materialId).Distinct().ToList();
                var materialInfos = await dbContext.MesBaseMaterialInfo
          .Where(material => materialIds.Contains(material.MaterialId))
          .ToListAsync();

                // 将库存物料信息和物料详细信息合并
                var stockDetails = from stock in stockList
                                   from material in materialInfos
                                   where stock.materialId == material.MaterialId
                                   select new
                                   {
                                       materialCode = material.MaterialCode,
                                       materialName = material.MaterialName,
                                       materialSpec = material.MaterialSpec,
                                       totalAmount = stock.totalAmount,
                                       frozenAmount = stock.frozenAmount

                                   };


                StockDataGrid.ItemsSource = stockDetails;
            }
          
        }
    }
}
