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 System.Security.AccessControl;
using WCS.Model.ApiModel.AGV;

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

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

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

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

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

        /// <summary>
        /// 任务创建人
        /// </summary>
        private string createUser;
        public string CreateUser
        {
            get { return createUser; }
            set
            {
                SetProperty(ref createUser, value);
            }
        }

        /// <summary>
        /// 起点
        /// </summary>
        private string startLocationCode;
        public string StartLocationCode
        {
            get { return startLocationCode; }
            set
            {
                SetProperty(ref startLocationCode, value);
            }
        }

        /// <summary>
        /// 终点
        /// </summary>
        private string endLocationCode;
        public string EndLocationCode
        {
            get { return endLocationCode; }
            set
            {
                SetProperty(ref endLocationCode, value);
            }
        }

        /// <summary>
        /// 结束位置
        /// </summary>
        private List<string> stocktakingStatuses = new List<string>();
        public List<string> TaskStatus
        {
            get { return stocktakingStatuses; }
            set
            {
                SetProperty(ref stocktakingStatuses, value);
            }
        }

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

        #region Command
        public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
        public void BtnReset()
        {
            ShelfCode = string.Empty;
            CreateUser = string.Empty;

            StartLocationCode = string.Empty;
            EndLocationCode = string.Empty;

            SelectedTaskStatus = TaskStatus.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<TaskStatusEnum>(SelectedTaskStatus, out TaskStatusEnum status);
            #region 调用接口获取数据
            var dia = Dialog.Show(new TextDialog());
            try
            {
                var body = new GetAGVTasksRequest()
                {
                    ShelfCode = ShelfCode,
                    StartLocationCode = StartLocationCode,
                    EndLocationCode = EndLocationCode,
                    CreateUser = CreateUser,

                    TaskStatus = isSelected ? status : null,

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

                };
                var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<AGVTaskModel>>(LocalFile.Config.ApiIpHost + "AgvTask/getAGVTasks", body, "POST");
                if (Result != null && Result.Data != null && Result.Data.Lists != null)
                {
                    DataGridItemSource = new ObservableCollection<AGVTaskModel>(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 BtnCancelCommand { get => new DelegateCommand(BtnCancel); }
        public async void BtnCancel()
        {
            Growl.Ask($"是否取消所有勾选的任务?", isConfirmed =>
            {
                if (isConfirmed)
                {
                    //查询勾选的第一个数据
                    var needDeleteIds = DataGridItemSource?.Where(t => t.IsSelected == true)
                                                    .Select(t => t.Id)
                                                    .ToList();
                    

                    if (needDeleteIds == null || needDeleteIds.Count == 0)
                    {
                        Growl.Warning("请选择需要取消的任务！");
                        return true;
                    }
                    else
                    {
                        var task = DataGridItemSource?.Where(t => t.IsSelected == true).First();
                        var body = new CancelAGVTasksRequest()
                        {
                            TaskId = task == null ? 0 : task.Id,
                            TaskCode = task?.TaskCode,
                            UserName = LocalStatic.CurrentUser,
                            DeviceType = LocalFile.Config.DeviceType,
                        };
                        var Result = ApiHelp.GetDataFromHttp<ResponseBase<UserModel>>(LocalFile.Config.ApiIpHost + "agvTask/cancelAGVTask", 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 BtnResendCommand { get => new DelegateCommand(BtnResend); }
        public async void BtnResend()
        {
            Growl.Ask($"是否重新发送所勾选的任务?", isConfirmed =>
            {
                if (isConfirmed)
                {
                    //查询勾选的第一个数据
                    var needDeleteIds = DataGridItemSource?.Where(t => t.IsSelected == true)
                                                    .Select(t => t.Id)
                                                    .ToList();
                    

                    if (needDeleteIds == null || needDeleteIds.Count == 0)
                    {
                        Growl.Warning("请选择需要取消的任务！");
                        return true;
                    }
                    else
                    {
                        var task = DataGridItemSource?.Where(t => t.IsSelected == true).First();
                        var body = new ResendAGVTasksRequest()
                        {
                            TaskId = task == null ? 0 : task.Id,
                            TaskCode = task?.TaskCode,
                            UserName = LocalStatic.CurrentUser,
                            DeviceType = LocalFile.Config.DeviceType,
                        };
                        var Result = ApiHelp.GetDataFromHttp<ResponseBase<UserModel>>(LocalFile.Config.ApiIpHost + "agvTask/resendAGVTask", body, "POST");
                        if (Result != null && Result.Code == 200)
                        {
                            CurrentPage = 1;
                            Growl.Success("任务重新发送成功！" + Result?.Message);
                        }
                        else
                        {
                            Growl.Error($"{Result?.Message?.ToString()}");
                        }
                    }
                }
                return true;
            });
        }
        #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
    }
}
