using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
using Newtonsoft.Json.Linq;
using 智慧物流软件系统.Views.Controls;
using WCS.Model.ApiModel.User;
using 智慧物流软件系统.Api;
using WCS.Model;
using WCS.Model.ApiModel;
using System.Windows.Controls;
using WCS.Model.ApiModel.InterfaceRecord;
using HandyControl.Collections;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.MatInventoryDetail;
using HandyControl.Tools.Extension;
using WCS.Model.ApiModel.Stocktaking;
using WCS.Model.ApiModel.Home;

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

        public void InitMatCode()
        {
            //调用接口更新！
            Task.Run(() =>
            {
                var body = new GetMatCodeListRequest()
                {
                    IsFromBaseData = false,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                };

                var Result = ApiHelp.GetDataFromHttp<ResponseCommon<List<string>>>(LocalFile.Config.ApiIpHost + "matBaseInfo/getMatCodeList", body, "POST");
                if (Result != null && Result.Data != null && Result.Data.Count() > 0)
                {
                    matCodes = Result.Data.Select(t => new DataModel()
                    {
                        MatCode = t
                    }).ToList();
                }
            });
        }

        #region Property
        private List<MatInventoryDetailModel> dataGridItemSource;
        public List<MatInventoryDetailModel> DataGridItemSource
        {
            get { return dataGridItemSource; }
            set
            {
                SetProperty(ref dataGridItemSource, value);
            }
        }

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

        private string totalQtyStr;

        public string TotalQtyStr { get => totalQtyStr; set { SetProperty(ref totalQtyStr, value); } }


        /// <summary>
        /// 物料编码
        /// </summary>
        private string matCode;
        public string MatCode
        {
            get { return matCode; }
            set
            {
                SetProperty(ref matCode, value);
                FilterItems(value);
            }
        }
        public ManualObservableCollection<DataModel> Items { get; set; } = new();
        private List<DataModel> matCodes = new List<DataModel>();
        private void FilterItems(string key)
        {
            //至少输入三个字符 避免删除或输入时界面变卡
            if (string.IsNullOrEmpty(key) || key.Length < 3)
            {
                Items.Clear();
                return;
            }
            key = key.ToUpper();
            Items.CanNotify = false;
            Items.Clear();
            foreach (var matCode in matCodes)
            {
                if (matCode.MatCode.ToUpper().Contains(key))
                {
                    Items.Add(matCode);
                }
            }
            Items.CanNotify = true;
        }
        public class DataModel
        {
            public string MatCode { get; set; }
        }

        /// <summary>
        /// 物料名称
        /// </summary>
        private string matName;
        public string MatName
        {
            get { return matName; }
            set
            {
                SetProperty(ref matName, value);
            }
        }

        /// <summary>
        /// 物料批次
        /// </summary>
        private string matBatch;
        public string MatBatch
        {
            get { return matBatch; }
            set
            {
                SetProperty(ref matBatch, value);
            }
        }



        /// <summary>
        /// 库位
        /// </summary>
        private string storeCode;
        public string StoreCode
        {
            get { return storeCode; }
            set
            {
                SetProperty(ref storeCode, value);
            }
        }

        /// <summary>
        /// 物料条码
        /// </summary>
        private string matSN;
        public string MatSN
        {
            get { return matSN; }
            set
            {
                SetProperty(ref matSN, value);
            }
        }

        private List<OrderTypeModel> shelfTypeItems;
        public List<OrderTypeModel> ShelfTypeItems
        {
            get { return shelfTypeItems; }
            set
            {
                SetProperty(ref shelfTypeItems, value);
            }
        }
        public void InitShelfTypeItems()
        {
            //调用接口更新！
            Task.Run(() =>
            {
                var body = new RequestBase()
                {
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                };

                var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<OrderTypeModel>>(LocalFile.Config.ApiIpHost + "home/getShelfTypes", body, "POST");
                if (Result != null && Result.Data != null && Result.Data.Lists.Count() > 0)
                {
                    ShelfTypeItems = Result.Data.Lists;
                }
            });
        }

        private OrderTypeModel selectedShelfTypeItem;
        public OrderTypeModel SelectedShelfTypeItem
        {
            get { return selectedShelfTypeItem; }
            set
            {
                SetProperty(ref selectedShelfTypeItem, value);
            }
        }
        #endregion

        #region Command
        public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
        public void BtnReset()
        {
            MatCode = string.Empty;
            MatName = string.Empty;
            MatSN = string.Empty;
            StoreCode = string.Empty;
            ShelfCode = string.Empty;
            MatBatch = string.Empty;
        }

        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 调用接口获取数据
            //var dia = Dialog.Show(new TextDialog());
            //try
            //{
            //    var body = new GetMatInventoryDetailRequest()
            //    {
            //        MatName = MatName,
            //        MatSN = MatSN,
            //        MatBatch = MatBatch,
            //        MatCode = MatCode,
            //        StoreCode = StoreCode,

            //        ShelfTypeId = SelectedRecordTypeItem == null ? 0 : SelectedRecordTypeItem.Id,
            //        ShelfCode = ShelfCode,

            //        UserName = LocalStatic.CurrentUser,
            //        DeviceType = LocalFile.Config.DeviceType,
            //        PageNumber = CurrentPage,
            //        PageSize = PageSize,
            //    };
            //    var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<MatInventoryDetailModel>>(LocalFile.Config.ApiIpHost + "matInventoryDetail/getMatInventoryDetail", body, "POST");
            //    if (Result != null && Result.Data != null && Result.Data.Lists != null)
            //    {
            //        DataGridItemSource = Result.Data.Lists;
            //        MaxPage = Result.Data.MaxPage;
            //        TotalCount = Result.Data.TotalCount;
            //        TotalQtyStr = "物料总数量" + Result.Message;
            //    }
            //    else
            //    {
            //        TotalQtyStr = string.Empty;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Growl.Error("加载数据失败：" + ex.Message);
            //}
            //finally
            //{
            //    dia.Close();
            //}
            //#endregion
        }

        public ICommand BtnExportCommand { get => new DelegateCommand(BtnExport); }
        public async void BtnExport()
        {
            try
            {
                #region 选择文件保存路径
                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                sfd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
                sfd.FileName = "库存数据" + DateTime.Now.ToString("yyyyMMddhhmmss");
                sfd.OverwritePrompt = true;
                if (sfd.ShowDialog() != true)
                {
                    return;
                }
                string path = sfd.FileName;
                #endregion

                #region 调用接口导出数据
                var body = new GetMatInventoryDetailRequest()
                {
                    MatName = MatName,
                    MatSN = MatSN,
                    MatBatch = MatBatch,
                    MatCode = MatCode,
                    StoreCode = StoreCode,

                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                    PageNumber = CurrentPage,
                    PageSize = 65535,
                };
                await ApiHelp.PostDownloadFileAsync(path, System.Net.Http.HttpMethod.Post, LocalFile.Config.ApiIpHost + "matInventoryDetail/exportMatInventoryDetail", body);
                Growl.Success("导出成功！");
                #endregion
            }
            catch (Exception ex)
            {
                Growl.Error("导出失败：" + ex.Message);
            }
        }

        public ICommand BtnGenerateOutstoreCommand { get => new DelegateCommand(BtnGenerateOutstore); }
        public async void BtnGenerateOutstore()
        {
            try
            {
                //#region 调用接口获取物料SN
                //try
                //{
                //    var body = new GetMatInventoryDetailRequest()
                //    {
                //        MatName = MatName,
                //        MatSN = MatSN,
                //        MatBatch = MatBatch,
                //        MatCode = MatCode,
                //        StoreCode = StoreCode,

                //        ShelfTypeId = SelectedRecordTypeItem == null ? 0 : SelectedRecordTypeItem.Id,
                //        ShelfCode = ShelfCode,

                //        UserName = LocalStatic.CurrentUser,
                //        DeviceType = LocalFile.Config.DeviceType,
                //        PageNumber = 1,
                //        PageSize = 65535,
                //    };
                //    var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<MatInventoryDetailModel>>(LocalFile.Config.ApiIpHost + "matInventoryDetail/getMatInventoryDetail", body, "POST");
                //    if (Result != null && Result.Data != null && Result.Data.Lists != null)
                //    {
                //        //获取搜索条件返回数据中未锁定的物料
                //        var unLockedMatSns = Result.Data.Lists.Where(t => t.IsLocked == false)
                //                                              .Select(t => t.MatSN)
                //                                              .ToList();

                //        if (unLockedMatSns.Count == 0)
                //        {
                //            HandyControl.Controls.MessageBox.Show("根据您的搜索条件不存在可以出库的物料（或物料已全部被锁定）！");
                //            return;
                //        }
                //        //提示 是否生成出库单
                //        var result = HandyControl.Controls.MessageBox.Show($"根据您的搜索条件，共有{unLockedMatSns.Count}盘未锁定的物料，是否生成出库单并锁定物料？", "提示", MessageBoxButton.OKCancel);

                //        if (result == MessageBoxResult.OK)
                //        {
                //            var dia = Dialog.Show(new TextDialog());
                //            try
                //            {
                //                #region 调用接口生成出库单据
                //                var body1 = new SysOutOrderByMatSnRequest()
                //                {
                //                    OrderType = "出库",
                //                    OrderSource = "WCS前端-库存数据出库",
                //                    SnList = unLockedMatSns,
                //                    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)
                //                {
                //                    App.Current.Dispatcher.Invoke(() =>
                //                    {
                //                        dia.Close();
                //                        dia.Collapse();
                //                        HandyControl.Controls.MessageBox.Show(Result1.Message);
                //                    });
                //                }
                //                else if (Result1 != null)
                //                {
                //                    Growl.Warning(Result1.Message);
                //                }

                //                #endregion
                //            }
                //            catch (Exception ex)
                //            {
                //                Growl.Error("生成出库单据失败：" + ex.Message);
                //            }
                //            finally
                //            {
                //                App.Current.Dispatcher.Invoke(() =>
                //                {
                //                    dia.Close();
                //                    dia.Collapse();
                //                });
                //            }
                //        }
                //    }
                //}
                //catch (Exception ex)
                //{
                //    Growl.Error("获取数据失败：" + ex.Message);
                //}
                //finally
                //{
                //}
                //#endregion
            }
            catch (Exception ex)
            {
                Growl.Error("导出失败：" + ex.Message);
            }
        }

        public ICommand BtnGenerateStocktakingCommand { get => new DelegateCommand(BtnGenerateStocktaking); }
        public void BtnGenerateStocktaking()
        {
            //try
            //{
            //    #region 调用接口获取物料SN
            //    try
            //    {
            //        var body = new GetMatInventoryDetailRequest()
            //        {
            //            MatName = MatName,
            //            MatSN = MatSN,
            //            MatBatch = MatBatch,
            //            MatCode = MatCode,
            //            StoreCode = StoreCode,

            //            ShelfTypeId = SelectedRecordTypeItem == null ? 0 : SelectedRecordTypeItem.Id,
            //            ShelfCode = ShelfCode,

            //            UserName = LocalStatic.CurrentUser,
            //            DeviceType = LocalFile.Config.DeviceType,
            //            PageNumber = CurrentPage,
            //            PageSize = 65535,
            //        };
            //        var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<MatInventoryDetailModel>>(LocalFile.Config.ApiIpHost + "matInventoryDetail/getMatInventoryDetail", body, "POST");
            //        if (Result != null && Result.Data != null && Result.Data.Lists != null)
            //        {
            //            //获取搜索条件返回数据中未锁定的物料
            //            var unLockedMatSns = Result.Data.Lists.Where(t => t.IsLocked == false)
            //                                                  .Select(t => t.MatSN)
            //                                                  .ToList();

            //            if (unLockedMatSns.Count == 0)
            //            {
            //                HandyControl.Controls.MessageBox.Show("根据您的搜索条件不存在可以盘点的物料！");
            //                return;
            //            }
            //            //提示 是否生成出库单
            //            var result = HandyControl.Controls.MessageBox.Show($"根据您的搜索条件，共有{unLockedMatSns.Count}盘未锁定的物料，是否生成盘点单？", "提示", MessageBoxButton.OKCancel);

            //            if (result == MessageBoxResult.OK)
            //            {
            //                var dia = Dialog.Show(new TextDialog());
            //                try
            //                {
            //                    #region 调用接口生成盘点单据
            //                    var body1 = new SysStockTakingOrderRequest()
            //                    {
            //                        StocktakingOrderType = "snList",
            //                        StocktakingOrderSource = "WCS前端-库存数据",
            //                        List = unLockedMatSns,
            //                        DeviceType = LocalFile.Config.DeviceType,
            //                        UserName = LocalStatic.CurrentUser
            //                    };
            //                    var Result1 = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "stockTaking/sysStockTakingOrder", body1, "POST");
            //                    if (Result1 != null && Result1.Code == 200)
            //                    {
            //                        App.Current.Dispatcher.Invoke(() =>
            //                        {
            //                            dia.Close();
            //                            dia.Collapse();
            //                            HandyControl.Controls.MessageBox.Show(Result1.Message);
            //                        });
            //                    }
            //                    else if (Result1 != null)
            //                    {
            //                        Growl.Warning(Result1.Message);
            //                    }

            //                    #endregion
            //                }
            //                catch (Exception ex)
            //                {
            //                    Growl.Error("生成盘点单据失败：" + ex.Message);
            //                }
            //                finally
            //                {
            //                    App.Current.Dispatcher.Invoke(() =>
            //                    {
            //                        dia.Close();
            //                        dia.Collapse();
            //                    });
            //                }
            //            }
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        Growl.Error("获取数据失败：" + ex.Message);
            //    }
            //    finally
            //    {
            //    }
            //    #endregion
            //}
            //catch (Exception ex)
            //{
            //    Growl.Error("导出失败：" + ex.Message);
            //}
        }
        #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
    }
}
