using HandyControl.Controls;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using SqlSugar;
using 智慧物流软件系统.Views.Controls;
using 智慧物流软件系统.Api;
using WCS.Model;
using WCS.Model.ApiModel;
using WCS.Model.ApiModel.MatBaseInfo;
using System.Collections.ObjectModel;
using WCS.Model.ApiModel.Stocktaking;
using WCS.Model.ApiModel.StoreInfo;

namespace 智慧物流软件系统.ViewModel
{
    public class MatDetailStocktakingInfoViewModel : BindableBase
    {

        public MatDetailStocktakingInfoViewModel()
        {
            //初始化下拉列表框
            StocktakingStatuses.Add("全部");
            var statuses = Enum.GetValues(typeof(StocktakingStatusEnum))
                              .Cast<StocktakingStatusEnum>()
                              .ToList();
            foreach (var status in statuses)
            {
                StocktakingStatuses.Add(status.ToString());
            }
        }

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

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

        /// <summary>
        /// 物料编码
        /// </summary>
        private string matCode;
        public string MatCode
        {
            get { return matCode; }
            set
            {
                SetProperty(ref matCode, value);
            }
        }

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

        /// <summary>
        /// 盘点人
        /// </summary>
        private string stocktakingUser;
        public string StocktakingUser
        {
            get { return stocktakingUser; }
            set
            {
                SetProperty(ref stocktakingUser, value);
            }
        }

        /// <summary>
        /// 盘点状态列表
        /// </summary>
        private List<string> stocktakingStatuses = new List<string>();
        public List<string> StocktakingStatuses
        {
            get { return stocktakingStatuses; }
            set
            {
                SetProperty(ref stocktakingStatuses, value);
            }
        }

        private string selectedStocktakingStatus;
        public string SelectedStocktakingStatus
        {
            get { return selectedStocktakingStatus; }
            set
            {
                SetProperty(ref selectedStocktakingStatus, value);
            }
        }

        #endregion

        #region Command
        public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
        public void BtnReset()
        {
            MatCode = string.Empty;
            MatName = string.Empty;
            StocktakingUser = string.Empty;
            SelectedStocktakingStatus = StocktakingStatuses.Where(t => t.Contains("未提交")).First();
        }

        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;
            }
            var isSelected = Enum.TryParse<StocktakingStatusEnum>(SelectedStocktakingStatus, out StocktakingStatusEnum status);
            #region 调用接口获取数据
            var dia = Dialog.Show(new TextDialog());
            try
            {
                var body = new GetStocktakingInfosRequest()
                {
                    MatCode = MatCode,
                    MatName = MatName,
                    StocktakingUser = StocktakingUser,
                    StocktakingStatus = isSelected ? status : null,

                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                    PageNumber = CurrentPage,
                    PageSize = PageSize,

                };
                var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<MatDetailStocktakingInfoModel>>(LocalFile.Config.ApiIpHost + "PDAStocktaking/getStocktakingInfos", body, "POST");
                if (Result != null && Result.Data != null && Result.Data.Lists != null)
                {
                    DataGridItemSource = new ObservableCollection<MatDetailStocktakingInfoModel>(Result.Data.Lists);
                    MaxPage = Result.Data.MaxPage;
                    TotalCount = Result.Data.TotalCount;
                }
            }
            catch (Exception ex)
            {
                Growl.Error("加载数据失败：" + ex.Message);
            }
            finally
            {
                dia.Close();
            }
            #endregion
        }

        /// <summary>
        /// 盘点提交操作
        /// </summary>
        public ICommand BtnCommitCommand { get => new DelegateCommand(BtnCommit); }
        public async void BtnCommit()
        {
            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 + "PDAStocktaking/commitStocktakingInfos", body, "POST");
                        if (Result != null && Result.Code == 200)
                        {
                            CurrentPage = 1;
                            Growl.Success("提交成功！" + Result?.Message);
                        }
                        else
                        {
                            Growl.Error($"{Result?.Message?.ToString()}");
                        }
                    }
                }
                return true;
            });
        }


        /// <summary>
        /// 物料修改操作
        /// </summary>
        public ICommand BtnEditCommand { get => new DelegateCommand(BtnEdit); }
        public async void BtnEdit()
        {
            //查询勾选的第一个数据
            var matDetailStocktakingInfo = DataGridItemSource?.Where(t => t.IsSelected == true).FirstOrDefault();
            if (matDetailStocktakingInfo == null)
            {
                Growl.Warning("请选择需要修改的数据！");
                return;
            }
            else
            {
                var updateView = new MatDetailStocktakingInfoUpdateView("修改盘点数据", matDetailStocktakingInfo);
                updateView.ShowDialog();
                if (updateView.DialogResult == true)
                {
                    matDetailStocktakingInfo = updateView.matDetailStocktakingInfo;
                    var body = new UpdateStocktakingInfoRequest()
                    {
                        MatDetailStocktakingInfoId = matDetailStocktakingInfo.Id,
                        StocktakingQty = matDetailStocktakingInfo.StocktakingQty,
                        UserName = LocalStatic.CurrentUser,
                        DeviceType = LocalFile.Config.DeviceType,
                    };
                    var Result = ApiHelp.GetDataFromHttp<ResponseBase<object>>(LocalFile.Config.ApiIpHost + "PDAStocktaking/updateStocktakingInfos", body, "POST");
                    if (Result != null && Result.Code == 200)
                    {
                        CurrentPage = 1;
                        Growl.Success("修改成功！");
                    }
                    else
                    {
                        Growl.Error($"{Result?.Message?.ToString()}");
                    }
                }
            }
        }

        /// <summary>
        /// 物料删除操作
        /// </summary>
        public ICommand BtnDeleteCommand { get => new DelegateCommand(BtnDelete); }
        public async 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 + "PDAStocktaking/deleteStocktakingInfos", body, "POST");
                        if (Result != null && Result.Code == 200)
                        {
                            CurrentPage = 1;
                            Growl.Success("删除成功！" + Result?.Message);
                        }
                        else
                        {
                            Growl.Error($"{Result?.Message?.ToString()}");
                        }
                    }
                }
                return true;
            });
        }

        /// <summary>
        /// 导出功能
        /// </summary>
        public ICommand BtnExportCommand { get => new DelegateCommand(BtnExport); }
        public async void BtnExport()
        {
            try
            {
                #region 选择文件保存路径
                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                sfd.Title = "选择文件保存路径";
                sfd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
                sfd.FileName = "库存盘点" + DateTime.Now.ToString("yyyyMMddhhmmss");
                sfd.OverwritePrompt = true;
                if (sfd.ShowDialog() != true)
                {
                    return;
                }
                string path = sfd.FileName;
                #endregion
                var isSelected = Enum.TryParse<StocktakingStatusEnum>(SelectedStocktakingStatus, out StocktakingStatusEnum status);
                var body = new GetStocktakingInfosRequest()
                {
                    MatCode = MatCode,
                    MatName = MatName,
                    StocktakingUser = StocktakingUser,
                    StocktakingStatus = isSelected ? status : null,

                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                    PageNumber = CurrentPage,
                    PageSize = PageSize,

                };
                await ApiHelp.PostDownloadFileAsync(path, System.Net.Http.HttpMethod.Post, LocalFile.Config.ApiIpHost + "PDAStocktaking/exportStocktakingInfos", body);
                Growl.Success("导出成功！");
            }
            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
    }
}
