using HandyControl.Controls;
using Ping9719.WpfEx.Mvvm;
using QRCoder;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using WCS.Model;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.OutStore;
using 智慧物流软件系统.Api;
using 智慧物流软件系统.Views.Controls;

namespace 智慧物流软件系统.ViewModels
{
    public class OutInventoryDocumentViewModel : BindableBase
    {
        public OutInventoryDocumentViewModel()
        {
            BtnSearch();
        }

        #region Properties界面绑定的实体
        private ObservableCollection<OutOrderModel> dataGridItemSource;
        public ObservableCollection<OutOrderModel> DataGridItemSource
        {
            get { return dataGridItemSource; }
            set
            {
                SetProperty(ref dataGridItemSource, value);
            }
        }

        public OutOrderModel selectedataGridItem;
        public OutOrderModel SelectedataGridItem
        {
            get { return selectedataGridItem; }
            set
            {
                SetProperty(ref selectedataGridItem, value);
            }
        }

        private string orderNumber;
        public string OrderNumber
        {
            get { return orderNumber; }
            set
            {
                SetProperty(ref orderNumber, value);
            }
        }

        private string orderType;
        public string OrderType
        {
            get { return orderType; }
            set
            {
                SetProperty(ref orderType, value);
            }
        }

        private string orderSource;
        public string OrderSource
        {
            get { return orderSource; }
            set
            {
                SetProperty(ref orderSource, value);
            }
        }

        #endregion

        #region Command
        public ICommand BtnSearchCommand { get => new DelegateCommand(BtnSearchReset); }
        public void BtnSearchReset()
        {
            BtnSearch(true);
        }
        public void BtnSearch(bool IsPageReset = true)
        {
            if (CurrentPage == 0 || IsPageReset)
            {
                CurrentPage = 1;
                return;
            }

            #region 调用接口获取数据
            try
            {
                var body = new GetOutOrderListRequest()
                {
                    OrderNumber = OrderNumber,
                    OrderType = OrderType,
                    OrderSource = OrderSource,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                    PageNumber = CurrentPage,
                    PageSize = PageSize,
                };
                var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<OutOrderModel>>(LocalFile.Config.ApiIpHost + "outStore/GetOutOrderList", body, "POST");
                if (Result != null && Result.Data != null && Result.Data.Lists != null)
                {
                    DataGridItemSource = new ObservableCollection<OutOrderModel>(Result.Data.Lists);
                    MaxPage = Result.Data.MaxPage;
                    TotalCount = Result.Data.TotalCount;
                }
            }
            catch (Exception ex)
            {
                Growl.Error("加载数据失败：" + ex.Message);
            }
            finally
            {
            }
            #endregion
        }

        public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
        public void BtnReset()
        {
            OrderNumber = string.Empty;
            OrderType = string.Empty;
            OrderSource = string.Empty;
        }

        //public ICommand BtnDeleteCommand { get => new DelegateCommand(BtnDelete); }
        //public void BtnDelete()
        //{

        //}

        public ICommand BtnOutOrderCommand { get => new DelegateCommand(BtnOutOrder); }
        public void BtnOutOrder()
        {
            var window = new OutInventoryAddDucumentView();
            window.Owner = Application.Current.MainWindow;
            window.Topmost = true;
            var result = window.ShowDialog();
            if (result == true)
                BtnSearch(true);
        }

        //导入出库
        public ICommand BtnImportDocumentCommand { get => new DelegateCommand(BtnImportDocument); }
        public void BtnImportDocument()
        {
            var window = new OutInventoryImportDucumentView();
            window.Owner = Application.Current.MainWindow;
            var result = window.ShowDialog();
            if (result == true)
                BtnSearch(true);
        }

        public ICommand BtnOrderDetailCommand { get => new DelegateCommand(BtnOrderDetail); }
        public void BtnOrderDetail()
        {
            try
            {
                if (DataGridItemSource == null)
                {
                    Growl.Warning("未勾选数据！");
                    return;
                }

                //判断是否勾选数据
                var selectedOutOrder = DataGridItemSource.Where(t => t.IsSelected)
                                                         .FirstOrDefault();
                if (selectedOutOrder == null)
                {
                    Growl.Warning("未勾选数据！");
                    return;
                }

                #region 调用接口获取数据

                var body = new GetOutOrderDetailRequest()
                {
                    OrderId = selectedOutOrder.Id,
                    OrderNumber = selectedOutOrder.OrderNumber,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,

                };
                var Result = ApiHelp.GetDataFromHttp<ResponseCommon<List<OutOrderDetailModel>>>(LocalFile.Config.ApiIpHost + "outStore/getOutOrderDetail", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    if (Result.Data.Count > 0)
                    {
                        //打开窗体
                        var window = new OutInventoryDocumentDetailView(Result.Data);
                        window.Owner = Application.Current.MainWindow;
                        window.ShowDialog();
                    }
                    else
                    {
                        Growl.Warning("该单据没有单据明细！");
                    }
                }
                else if (Result != null)
                {
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Growl.Warning("调用接口失败！");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Growl.Error("出现异常：" + ex.Message);
            }
            finally
            {
            }

        }

        public ICommand BtnOrderMatDetailCommand { get => new DelegateCommand(BtnOrderMatDetail); }
        public void BtnOrderMatDetail()
        {
            try
            {
                if (DataGridItemSource == null)
                {
                    Growl.Warning("未勾选数据！");
                    return;
                }

                //判断是否勾选数据
                var selectedOutOrder = DataGridItemSource.Where(t => t.IsSelected)
                                                         .FirstOrDefault();
                if (selectedOutOrder == null)
                {
                    Growl.Warning("未勾选数据！");
                    return;
                }
                #region 调用接口获取数据
                var body = new GetOutOrderDetailRequest()
                {
                    OrderId = selectedOutOrder.Id,
                    OrderNumber = selectedOutOrder.OrderNumber,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,

                };
                var Result = ApiHelp.GetDataFromHttp<ResponseCommon<List<OutOrderMatDetailModel>>>(LocalFile.Config.ApiIpHost + "outStore/getOutOrderMatDetail", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    if (Result.Data.Count > 0)
                    {
                        //打开窗体
                        var window = new OutInventoryDocumentMatDetailView(Result.Data);
                        window.Owner = Application.Current.MainWindow;
                        window.ShowDialog();
                    }
                    else
                    {
                        Growl.Warning("该单据没有发料明细！");
                    }
                }
                else if (Result != null)
                {
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Growl.Warning("调用接口失败！");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Growl.Error("出现异常：" + ex.Message);
            }
            finally
            {
            }
        }

        //开始入库 如果成功就直接跳转出库界面
        public ICommand BtnStartCommand { get => new DelegateCommand(BtnStart); }
        public void BtnStart()
        {
            try
            {
                if (DataGridItemSource == null)
                {
                    Growl.Warning("未勾选数据！");
                    return;
                }
                //判断是否勾选数据
                var selectedOutOrder = DataGridItemSource.Where(t => t.IsSelected)
                                                         .FirstOrDefault();
                if (selectedOutOrder == null)
                {
                    Growl.Warning("未勾选数据！");
                    return;
                }

                //判断是否是信息化货架
                if (selectedOutOrder.ShelfTypeName == "信息化货架")
                {
                    Growl.Info("请使用PDA进行出库");
                    //生成二维码
                    var qrCodeImage = GenerateQRCode(selectedOutOrder.Id.ToString() + "," + selectedOutOrder.OrderNumber);
                    //展示二维码
                    Dialog.Show(new ImageDialog(qrCodeImage));
                    return;
                }

                #region 调用接口开始出库
                var body = new GetOutOrderDetailRequest()
                {
                    OrderId = selectedOutOrder.Id,
                    OrderNumber = selectedOutOrder.OrderNumber,
                    IsStart = true,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                };
                var Result = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "outStore/goInOutstore", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    //成功后直接跳转
                    MainWindow1.viewModel.GoToOutVentoryView = true;
                    //刷新出库单列表
                    OutVentoryView.viewModel.RefreshOutOrderList(selectedOutOrder.OrderNumber);

                    Growl.Success("已跳转到物料出库页面！");
                }
                else if (Result != null)
                {
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Growl.Warning("调用接口失败！");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Growl.Error("出现异常：" + ex.Message);
            }
            finally
            {
            }
        }

        public BitmapImage GenerateQRCode(string data)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(data, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(20, Color.Black, Color.White, true);
            // 将System.Drawing.Bitmap转换为System.Windows.Media.Imaging.BitmapImage  
            using (var memoryStream = new MemoryStream())
            {
                // 假设Bitmap的Save方法支持Png格式（通常是这样）  
                qrCodeImage.Save(memoryStream, ImageFormat.Png);
                memoryStream.Position = 0;
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memoryStream;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();

                // 返回BitmapImage  
                return bitmapImage;
            }
        }

        public ICommand BtnPauseCommand { get => new DelegateCommand(BtnPause); }
        public void BtnPause()
        {
            try
            {
                if (DataGridItemSource == null)
                {
                    Growl.Warning("未勾选数据！");
                    return;
                }
                //判断是否勾选数据
                var selectedOutOrder = DataGridItemSource.Where(t => t.IsSelected)
                                                         .FirstOrDefault();
                if (selectedOutOrder == null)
                {
                    Growl.Warning("未勾选数据！");
                    return;
                }

                #region 调用接口结束出库
                var body = new GetOutOrderDetailRequest()
                {
                    OrderId = selectedOutOrder.Id,
                    OrderNumber = selectedOutOrder.OrderNumber,
                    IsPause = true,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                };
                var Result = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "outStore/goOutOutstore", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    //刷新出库单列表
                    OutVentoryView.viewModel.RefreshOutOrderList(selectedOutOrder.OrderNumber);
                    Growl.Success("已暂停出库！");
                }
                else if (Result != null)
                {
                    OutVentoryView.viewModel.RefreshOutOrderList(OutVentoryView.viewModel.SelectedOutOrder?.OrderNumber);
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Growl.Warning("调用接口失败！");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Growl.Error("出现异常：" + ex.Message);
            }
            finally
            {
            }
        }
        #endregion

        #region PageOperation 分页操作
        private int currentPage;
        public int CurrentPage
        {
            get { return currentPage; }
            set
            {
                SetProperty(ref currentPage, value);
                BtnSearch(false);
            }
        }

        private int maxPage;
        public int MaxPage
        {
            get { return maxPage; }
            set { SetProperty(ref maxPage, value); }
        }

        //总数量
        private int totalCount;
        public int TotalCount
        {
            get { return totalCount; }
            set { SetProperty(ref totalCount, value); }
        }

        private int pageSize = 10;
        public int PageSize
        {
            get => pageSize;
            set
            {
                SetProperty(ref pageSize, value);
                BtnSearch(true);
            }
        }


        public ICommand BtnFirstPageCommand { get => new DelegateCommand(BtnFirstPage); }
        public void BtnFirstPage()
        {
            CurrentPage = 1;
        }

        public ICommand BtnPrePageCommand { get => new DelegateCommand(BtnPrePage); }
        public void BtnPrePage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
            }
        }

        public ICommand BtnNextPageCommand { get => new DelegateCommand(BtnNextPage); }
        public void BtnNextPage()
        {
            if (CurrentPage < MaxPage)
            {
                CurrentPage++;
            }
        }

        public ICommand BtnLastPageCommand { get => new DelegateCommand(BtnLastPage); }
        public void BtnLastPage()
        {
            if (CurrentPage != MaxPage)
            {
                CurrentPage = MaxPage;
            }
        }
        #endregion

    }
}
