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 WCS.BLL.DbModels;
using WCS.Model.ApiModel.MatBaseInfo;
using System.Collections.ObjectModel;
using HandyControl.Tools.Extension;
using 智慧物流软件系统.Tool;
using System.Printing;
using System.Printing.IndexedProperties;

namespace 智慧物流软件系统.ViewModel
{
    public class MatInfoViewModel : BindableBase
    {
        public MatInfoViewModel()
        {
            IsPrintedItemSource = new List<ComboBoxItem>()
            {
                new ComboBoxItem(){Text = "全部",Value = null},
                new ComboBoxItem(){Text = "否",Value = false },
                new ComboBoxItem(){Text = "是",Value = true},
            };
        }
        #region Property
        private ObservableCollection<MatInfoModel> dataGridItemSource;
        public ObservableCollection<MatInfoModel> DataGridItemSource
        {
            get { return dataGridItemSource; }
            set
            {
                SetProperty(ref dataGridItemSource, value);
            }
        }

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

        private List<ComboBoxItem> isPrintedItemSource;
        public List<ComboBoxItem> IsPrintedItemSource
        {
            get => isPrintedItemSource;
            set { SetProperty(ref isPrintedItemSource, value); }
        }

        public class ComboBoxItem
        {
            public string Text { get; set; }
            public bool? Value { get; set; }
        }

        private bool? isPrinted;
        public bool? IsPrinted
        {
            get => isPrinted;
            set { SetProperty(ref isPrinted, value); }
        }

        private string matBatch;
        public string MatBatch
        {
            get => matBatch;
            set { SetProperty(ref matBatch, 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 matSpec;
        public string MatSpec
        {
            get { return matSpec; }
            set
            {
                SetProperty(ref matSpec, value);
            }
        }

        private string matSN;
        public string MatSN
        {
            get { return matSN; }
            set
            {
                SetProperty(ref matSN, value);
            }
        }
        #endregion

        #region Command
        public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
        public void BtnReset()
        {
            MatCode = string.Empty;
            MatName = string.Empty;
            MatSpec = string.Empty;
            MatSN = 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 调用接口获取数据
            try
            {
                var body = new GetMatInfoRequest()
                {
                    MatCode = MatCode,
                    MatName = MatName,
                    MatSpec = MatSpec,
                    MatSN = MatSN,
                    MatBatch = MatBatch,
                    IsPrinted = IsPrinted,

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

                };
                var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<MatInfoModel>>(LocalFile.Config.ApiIpHost + "matBaseInfo/getMatInfo", body, "POST");
                if (Result != null && Result.Data != null && Result.Data.Lists != null)
                {
                    DataGridItemSource = new ObservableCollection<MatInfoModel>(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 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 + "matBaseInfos/deleteMatBaseInfo", body, "POST");
                        if (Result != null && Result.Code == 200)
                        {
                            CurrentPage = 1;
                            Growl.Success("删除成功！" + Result?.Message);
                        }
                        else
                        {
                            Growl.Error($"{Result?.Message?.ToString()}");
                        }
                    }
                }
                return true;
            });
        }

        public ICommand BtnPrintCommand { get => new DelegateCommand(BtnPrint); }
        public void BtnPrint()
        {
            var matBaseInfos = DataGridItemSource?.Where(t => t.IsSelected == true).ToList();

            if (matBaseInfos == null || matBaseInfos.Count == 0)
            {
                Growl.Warning("请选择需要打印的物料！");
                return;
            }

            //重复打印提示
            #region
            var printedMatBaseInfo = matBaseInfos.Where(t => t.IsPrinted).ToList();
            if (printedMatBaseInfo != null && printedMatBaseInfo.Count > 0)
            {
                //拼接提示字符串
                var messageStr = "以下条码已打印：\r\n" +
                    string.Join("\r\n", printedMatBaseInfo.Select(t => $"[{t.MatSN}]已打印{t.PrintedTimes}次！").ToList())
                    + "\r\n\r\n是否继续打印？(重复打印可能造成条码重复)";
                var result = HandyControl.Controls.MessageBox.Show(messageStr, "重复打印提示", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    return;
                }
            }
            #endregion

            //批量打印
            Task.Run(() =>
            {
                try
                {
                    ProcessDialog process = null;
                    Dialog dia = null;
                    var totalCount = matBaseInfos.Count();
                    int currentCount = 0;

                    App.Current.Dispatcher.Invoke(() =>
                    {
                        process = new ProcessDialog();
                        dia = Dialog.Show(process);
                    });
                    matBaseInfos.ForEach(t =>
                    {
                        PrintTender.PrintTag(new PrintClass()
                        {
                            MatSn = t.MatSN,
                            MatName = t.MatName,
                            MatCode = t.MatCode,
                            MatBatch = t.MatBatch,
                            MatQty = t.MatQty.ToString(),
                            MatSpec = t.MatSpec,
                        });
                        currentCount++;
                        if (process != null)
                            process.viewModel.ProcessValue = Convert.ToInt32(((decimal)currentCount / totalCount) * 100);
                    });
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        dia.Close();
                        dia.Collapse();
                    });

                    #region 回传后端打印成功
                    try
                    {
                        var body = new PrintedMatInfoRequest()
                        {
                            PrintedMatInfoIds = matBaseInfos.Select(t => t.Id).ToList(),
                            UserName = LocalStatic.CurrentUser,
                            DeviceType = LocalFile.Config.DeviceType,
                        };
                        var Result = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "matBaseInfo/printedMatInfo", body, "POST");
                        if (Result != null && Result.Code == 200)
                        {
                            //回传成功
                        }
                        else
                        {
                            //回传失败
                        }
                    }
                    catch (Exception ex)
                    {
                        Logs.Write("回传“打印成功”失败：" + ex.Message);
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    Logs.Write("打印条码失败：" + 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
    }
}
