using AutoMapper.Internal;
using BBWY.Client.APIServices;
using BBWY.Client.Models;
using BBWY.Client.Models.APIModel;
using BBWY.Client.Models.QiKu;
using BBWY.Client.Models.SealBox;
using BBWY.Client.Views.BatchPurchase;
using BBWY.Controls;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace BBWY.Client.ViewModels.SealBox
{
    public class SealBoxConfigureViewModel : BaseVM
    {
        private IList<StoreResponse> storeList;//仓库列表
        private LogisticsService logisticsService;
        private SealBoxService sealBoxService;
        private GlobalContext globalContext;
        private ObservableCollection<SealBoxConfigureModel> sealBoxConfigureModelList;


        /// <summary>
        /// 分箱配置列表
        /// </summary>
        public ObservableCollection<SealBoxConfigureModel> SealBoxConfigureModelList { get => sealBoxConfigureModelList; set { Set(ref sealBoxConfigureModelList, value); } }
        public SealBoxConfigureViewModel(LogisticsService logisticsService, SealBoxService sealBoxService, GlobalContext globalContext)
        {
            this.logisticsService = logisticsService;
            this.sealBoxService = sealBoxService;
            SetSplitCountCommand = new RelayCommand<SealBoxConfigureModel>(SetSplitCount);
            SetPackCountAndStoreCommand = new RelayCommand<object>(SetPackCountAndStore);
            SaveCommand = new RelayCommand<object>(Save);
            SealBoxConfigureModelList = new ObservableCollection<SealBoxConfigureModel>();
            this.globalContext = globalContext;
        }

        private long sealBoxId;
        public long SealBoxId { get => sealBoxId; set { Set(ref sealBoxId, value); } }

        public ICommand SetSplitCountCommand { get; set; }

        public ICommand SetPackCountAndStoreCommand { get; set; }

        public ICommand SaveCommand { get; set; }

        private void SetSplitCount(SealBoxConfigureModel sealBoxConfigureModel)
        {
            sealBoxConfigureModel.WareHourseDatas.Where(w => w.WareState == null || w.WareState == PositionState.待封箱).ToList().ForEach(
             s => sealBoxConfigureModel.WareHourseDatas.Remove(s)

             );
            var otherCount = sealBoxConfigureModel.WareHourseDatas.Count();
            if (sealBoxConfigureModel.SplitCount <= 0 || sealBoxConfigureModel.SplitCount < otherCount)
            {
                MessageBox.Show("份数不正确");
                return;
            }

            int resetIndex = 1;
            foreach (var item in sealBoxConfigureModel.WareHourseDatas)
            {
                item.Index = resetIndex;
                resetIndex++;
            }




            for (var i = 1 + otherCount; i <= sealBoxConfigureModel.SplitCount; i++)
            {
                sealBoxConfigureModel.WareHourseDatas.Add(new SealBoxConfigureWareHourseModel()
                {
                    Index = i,
                    Count = 0
                });
            }



        }



        private StoreResponse store;
        private void SetPackCountAndStore(object obj)
        {

            var sealBoxConfigureWareHourseModel = obj as SealBoxConfigureWareHourseModel;
            if (storeList == null)
            {
                var response = logisticsService.GetStoreList();
                if (!response.Success)
                {
                    MessageBox.Show(response.Msg, "获取仓库");
                    return;
                }
                storeList = response.Data.Where(s => s.Status == StockStatus.使用).ToArray();
            }
            if (store == null)
            {
                if (sealBoxConfigureWareHourseModel != null)
                    store = new StoreResponse
                    {
                        Id = sealBoxConfigureWareHourseModel.WareId,
                        Name = sealBoxConfigureWareHourseModel.WareName,
                        Type = ToStockType(sealBoxConfigureWareHourseModel.WareType),
                        Status = StockStatus.使用
                    };
            }



            var w = new PackSkuSplitCountAndStoreWindow(sealBoxConfigureWareHourseModel.Count, store, storeList, sealBoxConfigureWareHourseModel.WareType == WareType.聚水潭齐越仓);
            if (w.ShowDialog() == true)
            {
                store = w.Store;
                sealBoxConfigureWareHourseModel.Count = w.Quantity;
                IsJST = w.IsJST;
                sealBoxConfigureWareHourseModel.WareType = w.IsJST ? WareType.聚水潭齐越仓 : ToWareType(w.Store.Type);
                sealBoxConfigureWareHourseModel.WareId = w.IsJST ? "qiyuejushuitan" : w.Store.Id;
                sealBoxConfigureWareHourseModel.WareName = w.IsJST ? "齐越聚水潭" : w.Store.Name;




            }
        }

        /// <summary>
        /// 是否聚水潭
        /// </summary>
        public bool IsJST { get; set; }

        private WareType ToWareType(StockType stockType)
        {
            switch (stockType)
            {
                case StockType.商家仓:
                    return WareType.商家仓;
                    break;
                case StockType.京仓:
                    return WareType.京仓;
                    break;
                case StockType.云仓:
                    return WareType.云仓;
                    break;
                default:
                    break;
            }
            return WareType.聚水潭齐越仓;
        }

        private StockType ToStockType(WareType? wareType)
        {
            switch (wareType)
            {
                case WareType.京仓:
                    return StockType.京仓;
                    break;
                case WareType.云仓:
                    return StockType.云仓;
                    break;
                case WareType.商家仓:
                    return StockType.商家仓;
                    break;
                case WareType.聚水潭齐越仓:
                    break;
                default:
                    break;
            }

            return StockType.京仓;
        }

        private void Save(object obj)
        {

            if (SealBoxId <= 0)//设置分箱
            {
                SetSealBoxConfiguredRequest setSealBoxConfiguredRequest = new SetSealBoxConfiguredRequest();
                setSealBoxConfiguredRequest.ShopId = globalContext.User.Shop.ShopId.ToString();
                IList<SetSealBoxConfiguredData> SetSealBoxConfiguredDatas = new List<SetSealBoxConfiguredData>();
                foreach (var sealBoxConfigureModel in SealBoxConfigureModelList)
                {

                    if (sealBoxConfigureModel.WareHourseDatas==null|| !sealBoxConfigureModel.WareHourseDatas.Any(w=>w.Count>0))
                    {
                        continue;
                    }



                    //判断存在0的报错

                    if (sealBoxConfigureModel.WareHourseDatas.Any(w=>w.Count==0))
                    {
                        System.Windows.MessageBox.Show($"任务id:{sealBoxConfigureModel.TaskId}中,存在未配置的数据");
                        return;
                    }



                    ////todo: 到分箱界面判断
                    //if (sealBoxConfigureModel.WareHourseDatas.Select(s => s.WareId).Distinct().Count() != sealBoxConfigureModel.WareHourseDatas.Count())
                    //{
                    //    MessageBox.Show($"任务id:{sealBoxConfigureModel.TaskId} ,分箱出现重复仓库,请重新设置!");
                    //    return;
                    //}
                    //判断任务数量与分箱数量总和是否相等
                    if (sealBoxConfigureModel.SkuCount != sealBoxConfigureModel.WareHourseDatas.Select(s => s.Count).Sum())
                    {
                        MessageBox.Show($"任务id:{sealBoxConfigureModel.TaskId}中,采购数量:{sealBoxConfigureModel.SkuCount} 不等于 分箱总数量:{sealBoxConfigureModel.WareHourseDatas.Select(s => s.Count).Sum()}");
                        return;
                    }
                    SetSealBoxConfiguredDatas.Add(new SetSealBoxConfiguredData
                    {
                        SkuId = sealBoxConfigureModel.SkuId,
                        TaskId = sealBoxConfigureModel.TaskId,
                        TotalCount = sealBoxConfigureModel.SkuCount,
                        WareHourseDatas = sealBoxConfigureModel.WareHourseDatas.Select(x => new WareHourseData
                        {
                            Count = x.Count,
                            WareId = x.WareId,
                            WareName = x.WareName,
                            WareType = x.WareType.Value,
                        }).ToList(),
                    });
                }
                setSealBoxConfiguredRequest.SetSealBoxConfiguredDatas = SetSealBoxConfiguredDatas;
                var setSealBoxRes = sealBoxService.SetSealBoxConfigured(setSealBoxConfiguredRequest);
                if (setSealBoxRes == null)
                {
                    MessageBox.Show("网络异常");
                    return;
                }
                if (!setSealBoxRes.Success || setSealBoxRes.Data == null || !setSealBoxRes.Data)
                {
                    MessageBox.Show(setSealBoxRes.Msg);
                    return;
                }
                if (ReflashWindow != null) ReflashWindow();
            
                var window = obj as BWindow;
                window.Close();
            }


            if (SealBoxId > 0)//修改分箱
            {
                BatchUpdateSealBoxConfiguredRequest res = new BatchUpdateSealBoxConfiguredRequest()
                {

                    SealBoxId = SealBoxId,
                    ShopId = globalContext.User.Shop.ShopId.ToString()
                };

                IList<UpdateSealBoxConfiguredDataRequest> UpdateSealBoxConfiguredDatas = new List<UpdateSealBoxConfiguredDataRequest>();
                foreach (var sealBoxConfigureModel in SealBoxConfigureModelList)
                {

                    ////todo: 到分箱界面判断
                    //if (sealBoxConfigureModel.WareHourseDatas.Select(s => s.WareId).Distinct().Count() != sealBoxConfigureModel.WareHourseDatas.Count())
                    //{
                    //    MessageBox.Show($"任务id:{sealBoxConfigureModel.TaskId} ,分箱出现重复仓库,请重新设置!");
                    //    return;
                    //}
                    //判断任务数量与分箱数量总和是否相等
                    if (sealBoxConfigureModel.SkuCount != sealBoxConfigureModel.WareHourseDatas.Select(s => s.Count).Sum())
                    {
                        MessageBox.Show($"任务id:{sealBoxConfigureModel.TaskId} 中,采购数量:{sealBoxConfigureModel.SkuCount} 不等于 分箱总数量:{sealBoxConfigureModel.WareHourseDatas.Select(s => s.Count).Sum()}");
                        return;
                    }
                    UpdateSealBoxConfiguredDatas.Add(new UpdateSealBoxConfiguredDataRequest
                    {

                        TaskId = sealBoxConfigureModel.TaskId,
                        SkuCount = sealBoxConfigureModel.SkuCount,
                        SealBoxConfiguredWareHourseRequests = sealBoxConfigureModel.WareHourseDatas.Select(x => new SealBoxConfiguredWareHourseRequest
                        {
                            Count = x.Count,
                            WareId = x.WareId,
                            WareName = x.WareName,
                            WareType = x.WareType.Value,
                            WareState = x.WareState,
                             SealBoxId=x.SealBoxId

                        }).ToList(),
                    });
                }
                res.UpdateSealBoxConfiguredDatas = UpdateSealBoxConfiguredDatas;


                var setSealBoxRes = sealBoxService.BatchUpdateSealBoxConfigured(res);
                if (setSealBoxRes == null)
                {
                    MessageBox.Show("网络异常");
                    return;
                }
                if (!setSealBoxRes.Success || setSealBoxRes.Data == null || !setSealBoxRes.Data)
                {
                    MessageBox.Show(setSealBoxRes.Msg);
                    return;
                }
                if (ReflashWindow != null) ReflashWindow();
                var window = obj as BWindow;
                window.Close();
            }

        }



      public    Action ReflashWindow { get; set; }

    }
}