using HandyControl.Controls;
using HandyControl.Data;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TouchSocket.Core;
using WCS.Model;
using WCS.Model.ApiModel.OutStore;
using WCS.Model.ApiModel.Stocktaking;
using 智慧物流软件系统.Api;
using 智慧物流软件系统.ViewModel;

namespace 智慧物流软件系统.ViewModel
{
    public class StocktakingViewModel : BindableBase
    {
        public StocktakingViewModel()
        {
            RefreshStockTakingOrderList();
        }

        #region Property
        private StockTakingOrderModel selectedOutOrder;
        public StockTakingOrderModel SelectedOutOrder
        {
            get { return selectedOutOrder; }
            set
            {
                SetProperty(ref selectedOutOrder, value);
                if (selectedOutOrder != null)
                {
                    SelectedOutOrderNumber = selectedOutOrder.StocktakingOrderNumber;
                    RefreshDataGridItemSource();
                }
                else
                {
                    DataGridItemSource?.Clear();
                }
            }
        }

        private string selectedOutOrderNumber;
        public string SelectedOutOrderNumber
        {
            get => selectedOutOrderNumber;
            set
            {
                SetProperty(ref selectedOutOrderNumber, value);
            }
        }


        private ObservableCollection<StockTakingOrderModel> outOrderList;
        public ObservableCollection<StockTakingOrderModel> OutOrderList
        {
            get => outOrderList;
            set
            {
                SetProperty(ref outOrderList, value);
            }
        }

        private ObservableCollection<StockTakingOrderMatDetailModel> dataGridItemSource;
        public ObservableCollection<StockTakingOrderMatDetailModel> DataGridItemSource
        {
            get { return dataGridItemSource; }
            set
            {
                SetProperty(ref dataGridItemSource, value);
                RefreshCount();
            }
        }

        //单据总盘数
        private int totalPan;
        public int TotalPan
        {
            get => totalPan; set
            {
                SetProperty(ref totalPan, value);
            }
        }

        private int sendedPan;
        public int SendedPan
        {
            get => sendedPan; set
            {
                SetProperty(ref sendedPan, value);
            }
        }

        private string orderStatus;
        public string OrderStatus
        {
            get { return orderStatus; }
            set
            {
                SetProperty(ref orderStatus, value);
            }
        }

        public void RefreshCount()
        {
            Task.Run(() =>
            {
                SendedPan = dataGridItemSource.Where(t => t.IsStocktaking).Count();
                TotalPan = dataGridItemSource.Count();
            });
        }
        #endregion

        #region Command
        public ICommand BtnStartCommand { get => new DelegateCommand(BtnStart); }
        public void BtnStart()
        {
            try
            {
                //判断是否选择单据
                if (SelectedOutOrder == null)
                {
                    Growl.Warning("未选择单据！");
                    return;
                }

                #region 调用接口开始盘点
                var body = new GetStockTakingOrderMatDetailRequest()
                {
                    StockTakingOrderId = selectedOutOrder.Id,
                    StockTakingOrderNumber = selectedOutOrder.StocktakingOrderNumber,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                };
                var Result = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "stockTaking/startStockTakingOrder", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    Growl.Warning("已成功开始盘点！");
                    RefreshDataGridItemSource();
                }
                else if (Result != null)
                {
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Growl.Warning("调用接口失败！");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Growl.Error("出现异常：" + ex.Message);
            }
            finally
            {
            }
        }

        public ICommand BtnPauseCommand { get => new DelegateCommand(BtnPause); }
        public void BtnPause()
        {
            try
            {
                //判断是否选择单据
                if (SelectedOutOrder == null)
                {
                    Growl.Warning("未选择单据！");
                    return;
                }
                #region 调用接口结束盘点
                var body = new GetStockTakingOrderMatDetailRequest()
                {
                    StockTakingOrderId = selectedOutOrder.Id,
                    StockTakingOrderNumber = selectedOutOrder.StocktakingOrderNumber,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                };
                var Result = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "stockTaking/endStockTakingOrder", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    Growl.Warning("已成功结束盘点！");
                    RefreshDataGridItemSource();
                }
                else if (Result != null)
                {
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Growl.Warning("调用接口失败！");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Growl.Error("出现异常：" + ex.Message);
            }
            finally
            {
            }
        }

        public void RefreshStockTakingOrderList(string OrderNumber = "")
        {
            #region 调用接口获取发料单
            try
            {
                var body = new GetStockTakingOrdersRequest()
                {

                };
                var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<StockTakingOrderModel>>(LocalFile.Config.ApiIpHost + "stockTaking/getStockTakingOrdersByStatus", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    OutOrderList = new ObservableCollection<StockTakingOrderModel>(Result.Data.Lists);
                    if (!string.IsNullOrEmpty(OrderNumber))
                    {
                        SelectedOutOrder = OutOrderList.Where(t => t.StocktakingOrderNumber == OrderNumber).FirstOrDefault();
                    }
                    else
                    {
                        SelectedOutOrder = OutOrderList.FirstOrDefault(); ;
                    }
                }
                else if (Result != null && !string.IsNullOrEmpty(Result.Message))
                {
                    Growl.Warning(Result.Message);
                }
            }
            catch (Exception ex)
            {
                Growl.Warning(ex.Message);
            }
            #endregion
        }

        public void RefreshDataGridItemSource()
        {
            if (SelectedOutOrder == null)
            {
                //选择的单据为空无法进行查询
                Logs.Write("选择的单据为空无法进行查询!");
                return;
            }
            #region 调用接口获取盘点单物料明细
            Task.Run(() =>
            {
                var body = new GetStockTakingOrderMatDetailRequest()
                {
                    StockTakingOrderId = SelectedOutOrder.Id,
                    StockTakingOrderNumber = SelectedOutOrder.StocktakingOrderNumber,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,

                };
                Logs.Write("[刷新盘点明细1]!");
                var Result = ApiHelp.GetDataFromHttp<ResponseCommon<List<StockTakingOrderMatDetailModel>>>(LocalFile.Config.ApiIpHost + "stockTaking/getStockTakingOrderMatDetail", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    Logs.Write("[刷新盘点明细]Result != null && Result.Code == 200!");
                    if (Result.Data.Count > 0)
                    {
                        Logs.Write("[刷新盘点明细2]Result.Data.Count>0");
                        var list = Result.Data.OrderBy(t => t.IsStocktaking).ToList();
                        DataGridItemSource = new ObservableCollection<StockTakingOrderMatDetailModel>(list);
                    }
                    else
                    {
                        Logs.Write("[刷新盘点明细2]Result.Data.Count<=0,该单据未查询到盘点明细");
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            DataGridItemSource?.Clear();
                        });

                        Growl.Warning("该单据未查询到盘点明细！");
                    }
                }
                else if (Result != null)
                {
                    Logs.Write("[刷新盘点明细2]Result != null");
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Logs.Write("[刷新盘点明细2]调用接口失败");
                    Growl.Warning("调用接口失败！");
                }
            });
            #endregion
        }
        #endregion
    }
}
