using HandyControl.Controls;
using HandyControl.Data;
using MiniExcelLibs;
using Newtonsoft.Json;
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.MatInventoryDetail;
using WCS.Model.ApiModel.MXBackgroundThread;
using WCS.Model.ApiModel.OutStore;
using WCS.Model.ApiModel.Stocktaking;
using 智能仓储WCS管理系统.Api;
using 智能仓储WCS管理系统.ViewModel;

namespace 智能仓储WCS管理系统.ViewModel
{
    public class MXPDViewModel : BindableBase
    {
        public MXPDViewModel()
        {
            RefreshOutOrderList();
        }

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

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


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

        private ObservableCollection<OutOrderMatDetailModel> dataGridItemSource;
        public ObservableCollection<OutOrderMatDetailModel> 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 int totalCount;
        public int TotalCount
        {
            get => totalCount;
            set { SetProperty(ref totalCount, 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.IsSended).Count();
                TotalPan = dataGridItemSource.Count();
                TotalCount = dataGridItemSource.Sum(t => t.MatQty);
            });
        }


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

        private string wareHouseCode;
        public string WareHouseCode
        {
            get => wareHouseCode;
            set { SetProperty(ref wareHouseCode, value); }
        }
        #endregion

        #region Command
        public ICommand BtnOutOrderCommand { get => new DelegateCommand(BtnOutOrder); }
        public void BtnOutOrder()
        {
            var window = new MXOutOrderView();
            window.Owner = Application.Current.MainWindow;
            window.ShowDialog();
        }


        public ICommand BtnStartCommand { get => new DelegateCommand(BtnStart); }
        public void BtnStart()
        {
            try
            {
                //判断是否选择单据
                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>(LocalFile.Config.ApiIpHost + "outStore/goInOutstore", 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 GetOutOrderDetailRequest()
                {
                    OrderId = selectedOutOrder.Id,
                    OrderNumber = selectedOutOrder.OrderNumber,
                    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)
                {
                    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 BtnQueryCommand { get => new DelegateCommand(BtnQuery); }
        public void BtnQuery()
        {
            try
            {
                //请求WMS获取物料明细
                var request = new ElectronicSiloPushRequest()
                {
                    materialCode = MatCode,
                    warehouseCode = WareHouseCode
                };
                var requeststr = JsonConvert.SerializeObject(request);
                var result = ApiHelp.MXGetDataFromHttp<List<ElectronicSiloPushDto>>(requeststr, "http://192.168.2.23:9213/integrate/inOut/electronicSiloPush", "POST", true);
                if (result != null && (result.code == 200) && result.data != null && result.data.Count() > 0)
                {
                    //通过返回的物料明细查询当前库存中有的数据
                    var matSns = result.data.Select(t => t.materialBar).ToList();
                    //调用 比对库存数据 获取库存中有的数据
                    #region 调用接口 比对库存数据 获取库存中有的数据
                    try
                    {
                        var body = new CompareMatInventoryDetailRequest()
                        {
                            MatSns = matSns,
                        };
                        var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<MatInventoryDetailModel>>(LocalFile.Config.ApiIpHost + "matInventoryDetail/compareMatInventoryDetail", body, "POST", true);

                        //查询到物料信息
                        if (Result != null && Result.Data != null && Result.Data.Lists != null && Result.Data.Lists.Count != 0)
                        {
                            var count = Result.Data.Lists.Count;
                            //是否生成盘点单 实际上是出库单
                            var dialogResult = HandyControl.Controls.MessageBox.Show($"共查询到有{count}盘物料，是否生成盘点单？", "提示", MessageBoxButton.YesNo);
                            if (dialogResult == MessageBoxResult.Yes)
                            {
                                #region 调用接口保存出库单据
                                var body1 = new SysOutOrderByMatSnRequest()
                                {
                                    IsMXPD = true,
                                    OrderType = "出库",
                                    OrderSource = "WCS前端",
                                    SnList = Result.Data.Lists.Select(t => t.MatSN).ToList(),
                                    DeviceType = LocalFile.Config.DeviceType,
                                    UserName = LocalStatic.CurrentUser
                                };
                                var Result1 = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "outstore/sysOutOrderByMatSn", body1, "POST");
                                if (Result1 != null && Result1.Code == 200)
                                {
                                    //出库单据保存成功 刷新左侧出库单列表
                                    MXPDView.viewModel.RefreshOutOrderList(Result1.Message.ToString());
                                    Growl.Success("盘点单据保存成功，请点击【开始盘点】进行盘点下架！");
                                }
                                else if (Result1 != null)
                                {
                                    Growl.Warning(Result1.Message);
                                }
                                #endregion
                            }
                            else
                                return;
                        }
                        else if (Result != null && Result.Code == 200 && (Result.Data == null || Result.Data.Lists == null || Result.Data.Lists.Count == 0))
                        {
                            HandyControl.Controls.MessageBox.Show($"未查询到需要盘点的明细！所推荐物料在此货架上不存在，请确认是否在其他货架上！\r\n{string.Join(",\r\n", matSns)}");
                            DataGridItemSource = null;
                        }
                        else
                        {
                            HandyControl.Controls.MessageBox.Show($"未查询到需要盘点的明细！请重试！");
                            DataGridItemSource = null;
                        }
                    }
                    catch (Exception e)
                    {
                        HandyControl.Controls.MessageBox.Show($"未查询到需要盘点的明细！请重试！");
                        DataGridItemSource = null;
                    }
                    #endregion
                }
                else
                {
                    Growl.Warning("获取WMS系统库存数据失败！" + result?.message);
                }

            }
            catch (Exception ex)
            {

            }
            finally
            {
                //dia.Close();
                //dia.Collapse();
            }
        }

        public void RefreshOutOrderList(string OrderNumber = "")
        {
            #region 调用接口获取发料单
            try
            {
                var body = new GetOutOrderListByStatusRequest()
                {
                    OrderExeStatus = new List<OutOrderExeStatus>() { OutOrderExeStatus.开始发料, OutOrderExeStatus.发料完成 },
                    IsMXPD = true,
                };
                var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<OutOrderModel>>(LocalFile.Config.ApiIpHost + "outstore/getOutOrderListByStatus", body, "POST");
                if (Result != null && Result.Code == 200)
                {
                    OutOrderList = new ObservableCollection<OutOrderModel>(Result.Data.Lists);
                    if (!string.IsNullOrEmpty(OrderNumber))
                    {
                        SelectedOutOrder = OutOrderList.Where(t => t.OrderNumber == OrderNumber).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)
            {
                //选择的单据为空无法进行查询
                return;
            }
            #region 调用接口获取出库单物料明细
            Task.Run(() =>
            {
                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)
                    {
                        DataGridItemSource = new ObservableCollection<OutOrderMatDetailModel>(Result.Data);
                        OrderStatus = Result.Message;
                    }
                    else
                    {
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            DataGridItemSource?.Clear();
                        });
                        Growl.Warning("该单据未查询到发料明细！");
                    }
                }
                else if (Result != null)
                {
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Growl.Warning("调用接口失败！");
                }
            });
            #endregion
        }
        #endregion
    }
}
