using GalaSoft.MvvmLight.Command;
using MahApps.Metro.Controls.Dialogs;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
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.Navigation;
using System.Windows.Shapes;
using WSDDBBrowser.Core;
using WSDDBBrowser.Core.Model;

namespace WSDDBBrowser
{
    /// <summary>
    /// PageSelect.xaml 的交互逻辑
    /// </summary>
    public partial class PgSelect : Page
    {
        PgSelectViewModel viewModel;
        public PgSelect()
        {
            InitializeComponent();
        }

        public void Init()
        {

        }

        private void ButtonBack_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack();
            this.NavigationService.RemoveBackEntry();
        }

        private void dgridProcesses_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            viewModel = new PgSelectViewModel();
            viewModel.Init(DBViewerModel.Instance, DBHelper.Instance,
                dgridProcesses, NavigationService);

            this.DataContext = viewModel;
        }
    }

    public class PgSelectViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 数据库加载结果
        /// </summary>
        public string DBInitResult { get; set; }

        /// <summary>
        /// 机台号
        /// </summary>
        public int? MachineNo { get; set; }

        /// <summary>
        /// 工序号
        /// </summary>
        public int? StepNo { get; set; }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime BeginDate { get; set; }
        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime EndDate { get; set; }
        /// <summary>
        /// 订单号过滤
        /// </summary>
        public string OrderNoFilter { get; set; }

        /// <summary>
        /// 只查找超出标准工艺
        /// </summary>
        public bool IsJustSelectError { get; set; }
        /// <summary>
        /// 生产列表
        /// </summary>
        public ObservableCollection<Process> Processes { get; } = new ObservableCollection<Process>();

        #region Command
        public RelayCommand SearchCmd { get; }
        public RelayCommand OkCmd { get; }
        public RelayCommand<List<TechInfo>> ShowTechInfosCmd { get; }
        #endregion


        DBViewerModel dbViewerModel;
        DBHelper dbHelper;
        DataGrid dataGrid;
        NavigationService navigationService;
        public PgSelectViewModel()
        {
            SearchCmd = new RelayCommand(Search);
            OkCmd = new RelayCommand(Ok);
            ShowTechInfosCmd = new RelayCommand<List<TechInfo>>(ShowTechInfos);

        }



        public void Init(DBViewerModel dbVm, DBHelper dbHelper, 
            DataGrid dataGrid, NavigationService navigationService)
        {
            this.dbViewerModel = dbVm;
            this.dbHelper = dbHelper;
            this.dataGrid = dataGrid;
            this.navigationService = navigationService;

            BeginDate = DateTime.Now.AddDays(-1);
            EndDate = DateTime.Now;

            MachineNo = this.dbViewerModel.MachineNo;
            StepNo = this.dbViewerModel.StepNo;
            
            DBInit(); 
        }

        void DBInit()
        {

            if (!dbHelper.Init(
                dbViewerModel.ServerIP,
                dbViewerModel.ServerUser,
                dbViewerModel.ServerPw))
            {
                DBInitResult = dbHelper.ErrorMsg;
            }
            else
            {
                DBInitResult = "数据库加载成功";
            }

        }

        private async void Search()
        {
            if(StepNo == null) 
            {
                await App.MetroWindow.ShowMessageAsync("参数异常", $"工序号为空");
                return;
            }


            //开始加载
            var controller = await App.MetroWindow.ShowProgressAsync("请等待...", "开始查找数据",
                settings: new MetroDialogSettings()
                {
                    NegativeButtonText = "停止",
                    AnimateShow = false,
                    AnimateHide = false,
                          
                });
            //controller.SetCancelable(true);
            controller.SetIndeterminate();



            var list = dbHelper.GetProcessList(StepNo, MachineNo, BeginDate, EndDate, OrderNoFilter, IsJustSelectError);

            //var list = dbHelper.GetProcessList_Debug(StepNo, MachineNo, BeginDate, EndDate, OrderNoFilter, IsJustSelectError);
            Processes.Clear();
            foreach (var p in list)
            {
                
                Processes.Add(p);
            }

            if (list.Count() > 0)
            {
                if (StepNo != dbViewerModel.StepNo ||
                    MachineNo != dbViewerModel.MachineNo )
                {
                    bool isChanged = false;
                    if (StepNo!=null)
                    {
                        dbViewerModel.StepNo = (int)StepNo;
                        isChanged = true;
                    }

                    if (MachineNo!=null)
                    {
                        dbViewerModel.MachineNo = (int)MachineNo;
                        isChanged = true;
                    }
                    if(isChanged)
                        dbViewerModel.Save();
                }
            }


            await controller.CloseAsync();



            if (Processes.Count > 0)
            {
                //加载成功
                await App.MetroWindow.ShowMessageAsync("加载成功", $"{Processes.Count()} 条记录被加载");
            }
            else
            {
                await App.MetroWindow.ShowMessageAsync("加载失败", $"不能找到任何记录");
            }
        }

        private async void Ok()
        {
            if (dataGrid.SelectedItems.Count == 0)
            {
                await App.MetroWindow.ShowMessageAsync("加载异常",
                    $"没有选择任何一个记录,也许忘记按 【搜索】 了！！");
                return;
            }


            //开始加载
            var controller = await App.MetroWindow.ShowProgressAsync("请等待...", "开始加载数据",
                settings: new MetroDialogSettings()
                {
                    NegativeButtonText = "停止",
                    AnimateShow = false,
                    AnimateHide = false,
                });
            //controller.SetCancelable(true);
            controller.SetIndeterminate();


            dbViewerModel.CurrProcess = null;

            dbViewerModel.CurrProcess = dataGrid.SelectedItem as Process;
            bool ret = dbViewerModel.GetProcessPacks();
            if (!ret)
            {
                //获取出错
                await controller.CloseAsync();
                await App.MetroWindow.ShowMessageAsync("加载出错", "数据异常，请检测数据库");
                return;
            }

            await controller.CloseAsync();
            string msg = "";
            if (dbViewerModel.CurrProcess.HasTGData)
            {
                int cnt = dbViewerModel.ScanDataItems.Sum(item => item.MixValues.Count());

                msg += $"厚度数据 {cnt}幅";
            }

            if (dbViewerModel.CurrProcess.HasSBData)
            {
                int cnt = DBViewerModel.Instance.SBProcessPack.Records.Count();
                msg += $"温控数据 {cnt}个点";
            }

            //加载成功
            await App.MetroWindow.ShowMessageAsync("加载成功", msg);


            navigationService.GoBack();
            navigationService.RemoveBackEntry();
        }

        private async void ShowTechInfos(List<TechInfo> techInfos)
        {
            TechInfoDialog techInfoDialog = new TechInfoDialog();
            await techInfoDialog.Show(techInfos);
        }

    }
    public class PgSelectViewModel_UnitTest : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 机台号
        /// </summary>
        public int MachineNo { get; set; }

        /// <summary>
        /// 工序号
        /// </summary>
        public int StepNo { get; set; }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime BeginDate { get; set; }

        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime EndDate { get; set; }

        /// <summary>
        /// 订单号过滤
        /// </summary>
        public string OrderNoFilter { get; set; }

        public ObservableCollection<g_tgProcess> Processes { get; } = new ObservableCollection<g_tgProcess>();

        public PgSelectViewModel_UnitTest()
        {
            BeginDate = DateTime.Now.AddDays(-1);
            EndDate = DateTime.Now;

        }
    }

    public class IntNullValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return "";
            else if (value is int)
            {
                return value.ToString();
            }
            else
                return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string) 
            {
                if (string.IsNullOrEmpty((string)value))
                {
                    return null;
                }
                else if (int.TryParse((string)value, out int v))
                {
                    return v;
                }
                else {
                    return null;
                }
            }
            return null;
        }
    }
}
