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 智慧物流软件系统.Views.Controls;
using 智慧物流软件系统.Api;
using WCS.Model;
using WCS.Model.ApiModel.Home;
using WCS.Model.ApiModel.StoreInfo;
using WCS.BLL.DbModels;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.User;
using WCS.Model.ApiModel;
using Newtonsoft.Json.Bson;
using WCS.Model.ApiModel.LocationInfo;
using WCS.Model.ApiModel.MatDetailCurrentInfo;
using WCS.Model.ApiModel.BatchBindMatDetail;
using Microsoft.Win32;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using TouchSocket.Core;
using System.Text.RegularExpressions;

namespace 智慧物流软件系统.ViewModel
{
    public class BatchBindMatDetailViewModel : BindableBase
    {
        public BatchBindMatDetailViewModel()
        {
            //绑定工位编码
            StationCode = LocalStatic.CurrentUser;
        }

        #region Property
        /// <summary>
        /// 工位编号
        /// </summary>
        private string stationCode;
        public string StationCode
        {
            get { return stationCode; }
            set
            {
                SetProperty(ref stationCode, value);
            }
        }

        private List<MatDetailCurrentInfoModel> dataGridItemSource;
        public List<MatDetailCurrentInfoModel> DataGridItemSource
        {
            get { return dataGridItemSource; }
            set
            {
                SetProperty(ref dataGridItemSource, value);
            }
        }

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

        /// <summary>
        /// 单据编号
        /// </summary>
        private string orderNumber;
        public string OrderNumber
        {
            get { return orderNumber; }
            set
            {
                SetProperty(ref orderNumber, value);
            }
        }

        #region 货架
        /// <summary>
        /// 货架编号
        /// </summary>
        private string shelfCode;
        public string ShelfCode
        {
            get { return shelfCode; }
            set
            {
                SetProperty(ref shelfCode, value);
            }
        }

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

        private OrderTypeModel? selectedOrderTypeItem;
        public OrderTypeModel? SelectedOrderTypeItem
        {
            get { return selectedOrderTypeItem; }
            set
            {
                SetProperty(ref selectedOrderTypeItem, value);
            }
        }
        public void InitOrderTypeItems()
        {
            //调用接口更新！
            Task.Run(() =>
            {
                OrderTypeItems = new List<OrderTypeModel>();
                OrderTypeItems.Add(new OrderTypeModel { Id = null, OrderTypeName = "全部" });

                var body = new RequestBase()
                {
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                };

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

                SelectedOrderTypeItem = OrderTypeItems.FirstOrDefault();
            });
        }
        #endregion



        #endregion

        #region Command
        public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
        public void BtnReset()
        {
            if (OrderTypeItems != null)
            {
                SelectedOrderTypeItem = OrderTypeItems.FirstOrDefault();
            }
            OrderNumber = string.Empty;
            ShelfCode = 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 GetMatDetailCurrentInfosByStationCodeRequest()
                {
                    OrderTypeId = SelectedOrderTypeItem?.Id,
                    OrderNumber = OrderNumber,
                    ShelfCode = ShelfCode,
                    StationCode = StationCode,

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


        public ICommand BtnEditCommand { get => new DelegateCommand(BtnEdit); }
        public void BtnEdit()
        {
            //查询勾选的第一个数据
            var info = DataGridItemSource?.Where(t => t.IsSelected == true).FirstOrDefault();
            if (info == null)
            {
                Growl.Warning("请选择需要修改的数据！");
            }
            else
            {
                var updateView = new MatDetailCurrentInfoUpdateView("修改绑定数据", info);
                updateView.ShowDialog();
                if (updateView.DialogResult == true)
                {
                    CurrentPage = 1;
                }
            }
        }

        public ICommand BtnDeleteCommand { get => new DelegateCommand(BtnDelete); }
        public void BtnDelete()
        {
            Growl.Ask($"是否删除所有勾选的数据？", isConfirmed =>
            {
                if (isConfirmed)
                {
                    //查询勾选的第一个数据
                    var needDeleteIds = DataGridItemSource?.Where(t => t.IsSelected == true)
                                                    .Select(t => t.Id)
                                                    .ToList();

                    if (needDeleteIds == null)
                    {
                        Growl.Warning("请选择需要修改的数据！");
                    }
                    else
                    {
                        var body = new DeleteInfosRequest()
                        {
                            UserName = LocalStatic.CurrentUser,
                            DeviceType = LocalFile.Config.DeviceType,
                            needDeleteIds = needDeleteIds,
                        };
                        var Result = ApiHelp.GetDataFromHttp<ResponseBase<UserModel>>(LocalFile.Config.ApiIpHost + "batchBindMatDetail/deleteMatDetailCurrentInfoForBind", body, "POST");
                        if (Result != null && Result.Code == 200)
                        {
                            BtnSearch();
                            Growl.Success("删除成功！" + Result?.Message);
                        }
                        else
                        {
                            Growl.Error($"{Result?.Message?.ToString()}");
                        }
                    }
                }
                return true;
            });
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        public ICommand DownloadImportTemplateCommand { get => new DelegateCommand(DownloadImportTemplate); }
        public void DownloadImportTemplate()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "选择保存导入模板路径";//窗口标题

            saveFileDialog.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*"; // 设置文件过滤器
            saveFileDialog.ValidateNames = true;
            saveFileDialog.FileName = "物料绑定导入模板.xlsx";// 设置默认文件名

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    // 文件保存路径
                    var destinationPath = saveFileDialog.FileName;
                    // 文件源路径
                    var sourcePath = Path.Combine(LocalFile.ResourcesDir, "物料绑定导入模板.xlsx");

                    Folder.CopyFile(sourcePath, destinationPath);

                    // 更新文件的最后修改时间（通常设置为当前时间）
                    File.SetLastWriteTime(destinationPath, DateTime.Now);

                    if (File.Exists(destinationPath) && LocalFile.Config.IsLoadingDownloadPath)
                    {
                        LocalFile.Config.BatchBindImportTemplatePath = destinationPath;
                        LocalFile.SaveConfig();
                    }
                    Growl.Success("下载成功！");
                }
                catch (Exception ex)
                {
                    Growl.Warning($"操作失败：{ex.Message}");
                }
            }
        }

        public ICommand BtnImportCommand { get => new DelegateCommand(BtnImport); }
        public async void BtnImport()
        {
            try
            {
                #region 选择需要导入文件的路径
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "选择模板";
                ofd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
                ofd.Multiselect = false;
                if (!string.IsNullOrEmpty(LocalFile.Config.BatchBindImportTemplatePath))
                {
                    string pattern = @"^(.*?)\\[^\\]+$";

                    Match match = Regex.Match(LocalFile.Config.BatchBindImportTemplatePath, pattern);
                    if (match.Success)
                    {
                        ofd.InitialDirectory = match.Groups[1].Value;
                    }
                }


                if (ofd.ShowDialog() != true)
                {
                    return;
                }
                #endregion
                //已经选择文件 调用接口进行导入数据
                string path = ofd.FileName;

                var result = await ApiHelp.StationPostImportFileAsync<ResponseCommon<List<string>>>(path, System.Net.Http.HttpMethod.Post,
                    LocalFile.Config.ApiIpHost + "batchBindMatDetail/importMatDetailCurrentInfos", LocalStatic.CurrentUser, LocalFile.Config.DeviceType,StationCode);
                if (result.Code == 200)
                {
                    Growl.Success("成功导入！");
                    CurrentPage = 0;
                }
                else
                {
                    if (result.Data != null && result.Data.Count > 0)
                        HandyControl.Controls.MessageBox.Show(result.Message + "\t\n" + String.Join("\t\n", result.Data));
                    else
                        HandyControl.Controls.MessageBox.Show(result.Message);
                }
            }
            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
    }
}
