using Khd.Core.EntityFramework;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections.Generic;
using System.Linq;
using System.Windows;

namespace Khd.Core.Wpf.TaskForm
{
    /// <summary>
    /// SelectOutRawForm.xaml 的交互逻辑
    /// </summary>
    public partial class SelectOutRawForm : Window
    {
        private readonly IHost _host;
        private readonly string _ud3;
        private readonly int _isOut;
        public SelectOutRawForm(IHost host, string ud3, int isOut)
        {
            InitializeComponent();
            _host = host;
            _ud3 = ud3;
            _isOut = isOut;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (this.endStationCode.SelectedItem == null)
            {
                MessageBox.Show("请选择出库站点！");
            }
            else
            {
                using var scope = _host.Services.CreateScope();
                var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var baseEquip = dbContext.BaseEquip.Where(t => t.objid == 10).First();
                baseEquip.endStationCode = this.endStationCode.SelectedItem.ToString();
                baseEquip.ud3 = _ud3;
                baseEquip.IsOut = _isOut;
                dbContext.BaseEquip.Update(baseEquip);
                dbContext.SaveChanges();
                this.Close();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            List<string> endStationCodes = SystemData.BaseEquip.Where(t => t.equipType == 10).Select(t => t.agvPositionCode).ToList();
            using var scope = _host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            var hasTask = dbContext.WcsTask.Where(t => (t.nextPointId == 11 && t.taskType == 30) || t.nextPointId == 10).Any();
            if (!hasTask)
            {
                var wmsRawOutstocks = dbContext.WmsRawOutstock
                    .Where(t => t.executeStatus == "0" || t.executeStatus == "1")
                    .Where(t => endStationCodes.Contains(t.endStationCode))
                    .Where(t => t.outstockAmount > t.realOutstockAmount)
                    .ToList();
                List<string> list = wmsRawOutstocks.Select(t => t.endStationCode).Distinct().ToList();
                this.endStationCode.ItemsSource = list;
            }
            else
            {
                MessageBox.Show("您有未完成的出库任务，请先完成后再进行此操作！");
                this.Close();
            }
        }
    }
}
