using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Wpf.dto;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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.Media.Media3D;
using System.Windows.Shapes;
using static Khd.Core.Wpf.Form.FormBoardT;

namespace Khd.Core.Wpf.WindowPage
{
    /// <summary>
    /// StockWindow.xaml 的交互逻辑
    /// </summary>
    public partial class InventoryMaterialWindow : Window
    {
        private IHost host = null;

        private ObservableCollection<StockItem> itemsControlItems;

        /// <summary>
        /// 刷新盘库任务列表
        /// </summary>
        public delegate void RefreshInventoryList();
        public static event RefreshInventoryList? RefreshInventoryListEvent;


        public InventoryMaterialWindow(IHost _host)
        {
            host = _host;
            InitializeComponent();
            Init();
            itemsControlItems = new ObservableCollection<StockItem>();
            itemsControl.ItemsSource = itemsControlItems;
        }

        public async Task Init()
        {
            using var scope = host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            //var location = await dbContext.WmsBaseLocation.Where(x => x.locationId == locationId).FirstOrDefaultAsync();
    
            var stockList = await dbContext.WmsRawStock.Where(x => x.warehouseId ==512).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 = materialInfos.Select(material => new StockItem
                {
                    IsSelected = false,
                    materialId   = material.MaterialId.ToString(),
                    materialCode = material.MaterialCode,
                    materialName = material.MaterialName,
                    materialSpec = material.MaterialSpec,
                }).ToList();


                StockDataGrid.ItemsSource = stockDetails;
            }
          
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            string searchStr = SearchTxt.Text;
            if (string.IsNullOrEmpty(searchStr))
            {
                Init();
            }
            else
            {
                var target = StockDataGrid.ItemsSource.Cast<dynamic>().Where(x => x.materialCode.Contains(searchStr) || x.materialName.Contains(searchStr) || x.materialSpec.Contains(searchStr)).ToList();
                StockDataGrid.ItemsSource = target;
            }
           
        }




        public class StockItem
        {
            public bool IsSelected { get; set; }
            public string materialId { get; set; }
            public string  materialCode { get; set; }
            public string  materialName { get; set; }
            public string  materialSpec { get; set; }
        }

      

        private void CreateInventoryTask_Click(object sender, RoutedEventArgs e)
        {
           
            try
            {
                
                using var scope = host.Services.CreateScope();
                var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

                int locationCount = 0;
                if(itemsControlItems.Count == 0)
                {
                    locationCount = dbContext.WmsBaseLocation.Where(t => t.warehouseId == 512 && t.ContainerStatus == "1" && t.locationStatus=="1").Count();
                }
                else
                {
                    var materialIdList = itemsControlItems.Select(t => long.Parse(t.materialId)).ToList();
                    var locations = dbContext.WmsRawStock.Where(t => materialIdList.Contains((long)t.materialId)).ToList().Select(t=>t.locationCode).Distinct();
                    locationCount = locations.Count();
                }
                string materialIds = null;
                if (itemsControlItems.Count > 0)
                {
                    materialIds = string.Join(";", itemsControlItems.Select(t => t.materialId));
                }

                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.EndTime = DateTime.Now;
                            t.CheckStatus = "2";
                        });
                        dbContext.UpdateRange(Orders);
                        
                        dbContext.Add(new WmsInventoryCheck()
                        {
                            CreateTime = DateTime.Now,
                            CheckStatus = "0",
                            LocationAmount = locationCount,
                            InventoriedAmount = 0,
                            InventoryingAmount = 0,
                            WarehouseId = 512,
                            CreateBy = "WCS",
                            MaterialId = materialIds
                        }) ;
                        dbContext.SaveChanges();
                        HandyControl.Controls.Growl.Info("创建盘库任务成功!");
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show("是否创建一个盘库任务?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                    if (messageBoxResult == MessageBoxResult.OK)
                    {
                       
                        dbContext.Add(new WmsInventoryCheck()
                        {
                            CreateTime = DateTime.Now,
                            CheckStatus = "0",
                            LocationAmount = locationCount,
                            InventoriedAmount = 0,
                            InventoryingAmount = 0,
                            WarehouseId = 512,
                            CreateBy = "WCS",
                            MaterialId = materialIds
                        });
                        dbContext.SaveChanges();
                        HandyControl.Controls.Growl.Info("创建盘库任务成功!");
                    }
                }

                this.Close();
                //刷新列表
                RefreshInventoryListEvent?.Invoke();


            }
            catch
            {

            }

        }



        /// <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 = StockDataGrid.SelectedItem;
                if (checkbox.IsChecked != null && checkbox.IsChecked.Value)
                {
                    //if (itemsControlItems != null && itemsControlItems.Count >= 6)
                    //{
                    //    MessageBox.Show("最多只能选择6个");
                    //    checkbox.IsChecked = false;
                    //    return;
                    //}

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

                    bool isIn = itemsControlItems.Any(t => t.materialId == Currentselected.materialId);
                    if (!isIn)
                    {
                        itemsControlItems.Add(new StockItem
                        {
                            materialId = Currentselected.materialId,
                            materialCode = Currentselected.materialCode,
                            materialName = Currentselected.materialName,
                            materialSpec = Currentselected.materialSpec,
                        });

                    }
                }
                else
                {

                    // 删除选中项
                    StockItem model = itemsControlItems.FirstOrDefault(x => x.materialId == Currentselected.materialId);
                    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 属性中获取当前数据项
            StockItem itemToRemove = button.Tag as StockItem;

            if (itemToRemove != null)
            {
                // 从集合中移除数据项
                itemsControlItems.Remove(itemToRemove);
            }
        }


    }
}
