using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Library.Mapper;
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;
using Khd.Core.Wpf.dto;
namespace Khd.Core.Wpf.WindowPage
{
    /// <summary>
    /// TaskHistoryWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TaskHistoryWindow : Window
    {
        private IHost _host;
        public  TaskHistoryWindow(IHost host)
        {
            _host = host;
            InitializeComponent();
            Task.Run(async() =>
            {
                await GetTask(DateTime.Now.AddDays(-3), DateTime.Now.AddDays(3));
            });
        }



        /// <summary>
        /// 显示序号事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgData_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }



        private async Task GetTask(DateTime startTime,DateTime endTime)
        {
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var data = await dbContext.WcsTaskLog.Where(x => x.createTime >= startTime && x.createTime <= endTime).OrderByDescending(x => x.createTime).ToListAsync();
                Dispatcher.Invoke(() =>
                {

                    long? nextPointId = 0;

                    List<taskModel> taskModel = CoreMapper.Map<List<taskModel>>(data);

                    this.LoadMaterial0.ItemsSource = null;
                    this.LoadMaterial0.ItemsSource = taskModel;
                    this.LoadMaterial0.Items.Refresh();
                });
            }catch(Exception ex)
            {
                MessageBox.Show($"查询任务出现异常,请重新尝试:{ex.Message}");
            }
        }

        private async void SelectByTime_Click(object sender, RoutedEventArgs e)
        {
            DateTime? begin = this.BeginTime.SelectedDate;
            DateTime? end = this.EndTime.SelectedDate;
            if (begin == null || end == null)
            {
                MessageBox.Show($"请选择开始或者结束时间");
                return;
            }
            await GetTask(begin.Value, end.Value);

        }
    }
}
