using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using Microsoft.Extensions.DependencyInjection;
using SlnMesnac.Business;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto;
using SlnMesnac.WPF.MessageTips;
using SlnMesnac.WPF.Model;
using SqlSugar;
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.Media;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：LAPTOP-E0N2L34V
* 命名空间：SlnMesnac.WPF.ViewModel
* 唯一标识：14008fcc-0a31-4f1e-bc80-9f9ea84d3de5
*
* 创建者：WenJY
* 电子邮箱：wenjy@mesnac.com
* 创建时间：2024-04-10 16:18:57
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.WPF.ViewModel
{
    /// <summary>
    /// 生产统计ViewModel
    /// </summary>
    internal class ProdStatisticsViewModel : ViewModelBase
    {
        private readonly PalletStowBusiness _palletStowBusiness;
        private readonly ProdCompletionBusiness _prodCompletionBusiness;
        private readonly ISqlSugarClient sqlClient;

        public ProdStatisticsViewModel()
        {
            _palletStowBusiness = App.ServiceProvider.GetService<PalletStowBusiness>();
            _prodCompletionBusiness = App.ServiceProvider.GetService<ProdCompletionBusiness>();
            sqlClient = App.ServiceProvider.GetService<ISqlSugarClient>();
            QueryCommand = new RelayCommand<object>(obj => Query());


            BeginDate = DateTime.Now.AddDays(-3);
            EndDate = DateTime.Now;
            Query();

        }

        #region 参数定义

        #region 投料X轴日期
        /// <summary>
        /// 日产量柱状图X轴日期
        /// </summary>
        private List<string> outDayList = new List<string>();

        public List<string> OutDayList
        {
            get { return outDayList; }
            set { outDayList = value; }
        }
        #endregion

        #region 投料柱状图
        /// <summary>
        /// 投料统计柱状图
        /// </summary>
        private SeriesCollection outAchievement = new SeriesCollection();

        public SeriesCollection OutAchievement
        {
            get { return outAchievement; }
            set { outAchievement = value; }
        }
        #endregion


        #region 日产量柱状图X轴日期
        /// <summary>
        /// 日产量柱状图X轴日期
        /// </summary>
        private List<string> productDayList = new List<string>();

        public List<string> ProductDayList
        {
            get { return productDayList; }
            set { productDayList = value; }
        }
        #endregion

        #region 型号统计柱状图
        /// <summary>
        /// 日产量统计柱状图
        /// </summary>
        private SeriesCollection productAchievement = new SeriesCollection();

        public SeriesCollection ProductAchievement
        {
            get { return productAchievement; }
            set { productAchievement = value; }
        }
        #endregion




        private DateTime _BeginDate;
        public DateTime BeginDate
        {
            get { return _BeginDate; }
            set
            {
                if (_BeginDate != value)
                {
                    _BeginDate = value;
                    RaisePropertyChanged();//属性通知
                }
            }
        }
        private DateTime _EndDate;
        public DateTime EndDate
        {
            get { return _EndDate; }
            set
            {

                _EndDate = value;
                RaisePropertyChanged();//属性通知

            }
        }



        /// <summary>
        /// 原材料投料明细DataGrid
        /// </summary>
        private ObservableCollection<WmsRawOutstockDetail> wmsRawOutstockDetailDataGrid = new ObservableCollection<WmsRawOutstockDetail>();

        public ObservableCollection<WmsRawOutstockDetail> WmsRawOutstockDetailDataGrid
        {
            get { return wmsRawOutstockDetailDataGrid; }
            set { wmsRawOutstockDetailDataGrid = value; RaisePropertyChanged(() => WmsRawOutstockDetailDataGrid); }
        }

        /// <summary>
        /// 成品入库记录DataGrid
        /// </summary>
        private ObservableCollection<WmsProductInstock> productDataGrid = new ObservableCollection<WmsProductInstock>();

        public ObservableCollection<WmsProductInstock> ProductDataGrid
        {
            get { return productDataGrid; }
            set { productDataGrid = value; RaisePropertyChanged(() => ProductDataGrid); }

        }
        #endregion

        #region 事件定义

        /// <summary>
        /// 时间查询事件
        /// </summary>
        public RelayCommand<object> QueryCommand { get; set; }


        public RelayCommand<string> DeleteBarCodeCommand { get; set; }

        #endregion


        #region 时间查询

        private async Task Query()
        {
            try
            {
              
         
                if (EndDate < BeginDate)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("结束时间要大于开始时间", 2, 3);
                    });
                    return;
                }
                else
                {
                    await RefreshWmsRawOutstockDetailDataGrid(BeginDate.Date, EndDate.AddDays(1).Date);
                    await RefreshProductDataGrid(BeginDate.Date, EndDate.AddDays(1).Date);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        #endregion



        #region 3F原材料出库记录及图表
        /// <summary>
        /// 刷新原材料出库记录
        /// </summary>
        private async Task RefreshWmsRawOutstockDetailDataGrid(DateTime beginDate, DateTime endDate)
        {
            List<WmsRawOutstockDetail> list;

            list = await sqlClient.AsTenant().GetConnection("mes").Queryable<WmsRawOutstockDetail>().Where(x => x.WarehouseId == 311 && x.OutstockTime >= beginDate && x.OutstockTime <= endDate).OrderByDescending(t => t.OutstockTime).ToListAsync();

            if (list != null && list.Count > 0)
            {
                await App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    WmsRawOutstockDetailDataGrid.Clear();
                    int i = 1;
                    foreach (WmsRawOutstockDetail verify in list)
                    {
                        verify.RawOutstockDetailId = i++;
                        WmsRawOutstockDetailDataGrid.Add(verify);
                    }
                }));


                
                // 刷新图表
                RefreshWmsRawOutstockDetailChart(list);

            }
        }

        /// <summary>
        /// 刷新原材料出库图表
        /// </summary>
        /// <param name="list"></param>
        private void RefreshWmsRawOutstockDetailChart(List<WmsRawOutstockDetail> list)
        {
             list = list.OrderBy(x => x.CreateDate).ToList();
             App.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                OutAchievement.Clear();
                OutDayList.Clear();
                ChartValues<ObservablePoint> achievement = new ChartValues<ObservablePoint>();
                var listByDate = list
            .GroupBy(detail => detail.OutstockTime.Value.Date) // 按日期分组
            .Select(group => new
            {
                Date = group.Key,
                TotalAmount = group.Count() // 统计出库数量
            })
            .ToList();
                int i = 0;
                foreach (var item in listByDate)
                {
                    outDayList.Add(item.Date.ToString("MM-dd"));
                    achievement.Add(new ObservablePoint(i++, double.Parse(item.TotalAmount.ToString())));
                  
                }
                //加一个汇总柱状图
                outDayList.Add("合计");
                achievement.Add(new ObservablePoint(i, list.Count));
                var column = new ColumnSeries();
                column.DataLabels = true;
                column.Title = "日投料量";
                column.Values = achievement;
                column.Foreground = Brushes.White;
                column.Fill = new SolidColorBrush(Brushes.YellowGreen.Color);
                OutAchievement.Add(column);
            }));
        }
        #endregion


        #region 2F成品生产记录及统计图表
        private async Task RefreshProductDataGrid(DateTime beginDate, DateTime endDate)
        {
            List<WmsProductInstock> list;
            
            list = await sqlClient.AsTenant().GetConnection("mes").Queryable<WmsProductInstock>().Where(x => x.warehouseId == 231 && x.beginTime >= beginDate && x.beginTime <= endDate).OrderByDescending(t => t.beginTime).ToListAsync();

            if (list != null && list.Count > 0)
            {
                await App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    productDataGrid.Clear();
                    int i = 1;
                    foreach (WmsProductInstock verify in list)
                    {
                        verify.productInstockId = i++;
                        productDataGrid.Add(verify);
                    }
                }));

                // 刷新图表
                RefreshProductChart(list);
            }
        }

        private void RefreshProductChart(List<WmsProductInstock> list)
        {
            list = list.OrderBy(x => x.updateDate).ToList();
            App.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                ProductAchievement.Clear();
                ProductDayList.Clear();
                ChartValues<ObservablePoint> achievement = new ChartValues<ObservablePoint>();
                var listByDate = list
            .GroupBy(detail => detail.updateDate.Value.Date) // 按日期分组
            .Select(group => new
            {
                Date = group.Key,
                TotalAmount = group.Count() // 统计出库数量
            })
            .ToList();
                int i = 0;
                foreach (var item in listByDate)
                {
                    ProductDayList.Add(item.Date.ToString("MM-dd"));
                    achievement.Add(new ObservablePoint(i++, double.Parse(item.TotalAmount.ToString())));

                }
                //加一个汇总柱状图
                ProductDayList.Add("合计");
                achievement.Add(new ObservablePoint(i, list.Count));
                var column = new ColumnSeries();
                column.DataLabels = true;
                column.Title = "日生产量";
                column.Values = achievement;
                column.Foreground = Brushes.White;
            column.Fill = new SolidColorBrush(Brushes.LimeGreen.Color);
                ProductAchievement.Add(column);
            }));
        }

        #endregion
    }
}
