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.InOutRecord;
using System.Collections.ObjectModel;
using static 智慧物流软件系统.ViewModel.InOutRecordViewModel;
using WCS.Model.ApiModel.Home;

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

        private List<OrderTypeModel> shelfTypeItems;
        public List<OrderTypeModel> ShelfTypeItems
        {
            get { return shelfTypeItems; }
            set
            {
                SetProperty(ref shelfTypeItems, value);
            }
        }

        private OrderTypeModel selectedShelfTypeItem;
        public OrderTypeModel SelectedShelfTypeItem
        {
            get { return selectedShelfTypeItem; }
            set
            {
                SetProperty(ref selectedShelfTypeItem, 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;
                }
            });
        }

        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<InOutRecordModel> dataGridItemSource;
        public List<InOutRecordModel> DataGridItemSource
        {
            get { return dataGridItemSource; }
            set
            {
                SetProperty(ref dataGridItemSource, 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>
        /// 物料条码 物料SN
        /// </summary>
        private string matSN;
        public string MatSN
        {
            get { return matSN; }
            set
            {
                SetProperty(ref matSN, value);
            }
        }


        private DirectionEnum? selectedDirection;
        public DirectionEnum? SelectedDirection
        {
            get { return selectedDirection; }
            set
            {
                SetProperty(ref selectedDirection, value);
            }
        }

        public ObservableCollection<DirectionItem> Directions => GetEnumValues();
        private ObservableCollection<DirectionItem> GetEnumValues()
        {
            // 初始化ObservableCollection  
            var directions = new ObservableCollection<DirectionItem>();
            // 添加“全部”选项  
            directions.Add(new DirectionItem { Text = "全部", Value = null }); // Value设置为null或某个表示“全部”的值  

            // 遍历DirectionEnum枚举并添加项  
            foreach (DirectionEnum direction in Enum.GetValues(typeof(DirectionEnum)))
            {
                directions.Add(new DirectionItem { Text = direction.ToString(), Value = direction });
            }
            return directions;
        }

        public class DirectionItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public override string ToString()
            {
                return Text;
            }
        }
        #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;
        }

        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 GetInOutRecordRequest()
            //    {

            //        MatSN = MatSN,
            //        MatName = MatName,
            //        MatBatch = MatBatch,
            //        MatCode = MatCode,
            //        StoreCode = StoreCode,
            //        Direction = SelectedDirection,

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

            //        UserName = LocalStatic.CurrentUser,
            //        DeviceType = LocalFile.Config.DeviceType,
            //        PageNumber = CurrentPage,
            //        PageSize = PageSize,
            //    };
            //    var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<InOutRecordModel>>(LocalFile.Config.ApiIpHost + "inOutRecord/getInOutRecord", body, "POST");
            //    if (Result != null && Result.Data != null && Result.Data.Lists != null)
            //    {
            //        DataGridItemSource = Result.Data.Lists;
            //        MaxPage = Result.Data.MaxPage;
            //        TotalCount = Result.Data.TotalCount;
            //    }
            //}
            //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 GetInOutRecordRequest()
                {
                    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 + "inOutRecord/exportInOutRecord", body);
                Growl.Success("导出成功！");
                #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
    }
}
