using AutoMapper.Internal;
using BBWY.Client.APIServices;
using BBWY.Client.Helpers;
using BBWY.Client.Models;
using BBWY.Client.Models.PackTask;
using BBWY.Client.Views.Order;
using BBWY.Client.Views.PackTask;
using BBWY.Common.Extensions;
using BBWY.Common.Models;
using BBWY.Controls;
using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WebSocketSharp;

namespace BBWY.Client.ViewModels.PackTask
{
    public class PackTaskTotalViewModel : BaseVM, IDenpendency
    {
        private readonly PackTaskService packTaskService;
        private bool isLoading;
        private DateTime startDate;
        private DateTime endDate;
        private int pageIndex = 1;
        private int pageSize = 15;
        private int orderCount;
        private string searchTaskId;
        private string searchDepartment;
        private string searchShopName;
        private string searchSkuId;
        private ObservableCollection<ShopTotal> packTaskTotalList;
        private bool isBatchChecked;

        public bool IsBatchChecked { get => isBatchChecked; set { Set(ref isBatchChecked, value); } }
        public ObservableCollection<ShopTotal> PackTaskTotalList { get => packTaskTotalList; set { Set(ref packTaskTotalList, value); } }
        public string SearchSkuId { get => searchSkuId; set { Set(ref searchSkuId, value); } }
        public string SearchShopName { get => searchShopName; set { Set(ref searchShopName, value); } }
        public string SearchDepartment { get => searchDepartment; set { Set(ref searchDepartment, value); } }
        public string SearchTaskId { get => searchTaskId; set { Set(ref searchTaskId, value); } }

        public bool IsLoading { get => isLoading; set { Set(ref isLoading, value); } }


        public DateTime StartDate { get => startDate; set { Set(ref startDate, value); } }

        public DateTime EndDate { get => endDate; set { Set(ref endDate, value); } }

        public int PageIndex { get => pageIndex; set { Set(ref pageIndex, value); } }

        public int PageSize { get => pageSize; set { Set(ref pageSize, value); } }

        public int OrderCount { get => orderCount; set { Set(ref orderCount, value); } }
        
        private decimal totalPackDiscountFees;
        /// <summary>
        /// 总打包费用
        /// </summary>
        public decimal TotalPackDiscountFees { get => totalPackDiscountFees; set { Set(ref totalPackDiscountFees, value); } }

        private decimal totalConsumableFees;
        /// <summary>
        /// 总耗材费
        /// </summary>
        public decimal TotalConsumableFees { get => totalConsumableFees; set { Set(ref totalConsumableFees, value); } }

        private decimal totalFees;
        /// <summary>
        /// 总耗材费
        /// </summary>
        public decimal TotalFees { get => totalFees; set { Set(ref totalFees, value); } }

        public ICommand SetSearchDateCommand { get; set; }

        public ICommand SearchTaskTotalCommand { get; set; }

        public ICommand ExportCommand { get; set; }

        public ICommand BatchSettleCommand { get; set; }

        public ICommand SettleCommand { get; set; }

        public ICommand OrderPageIndexChangedCommand { get; set; }

        public ICommand BatchCheckedCommand { get; set; }

        //public IList<Department> departmentList;
        //ShopService shopService;
        public PackTaskTotalViewModel(PackTaskService packTaskService)
        {
            this.packTaskService = packTaskService;
            //this.shopService = shopService;
            SearchTaskTotalCommand = new RelayCommand(() =>
            {
                SearchTask(1);
            });

            StartDate = DateTime.Now;
            EndDate = DateTime.Now;

            SetSearchDateCommand = new RelayCommand<int>(d =>
            {
                EndDate = d == 1 ? DateTime.Now.Date.AddDays(-1) : DateTime.Now;
                StartDate = DateTime.Now.Date.AddDays(d * -1);
                PageIndex = 1;
                Task.Factory.StartNew(() => LoadOrder(1));  //点击日期查询订单
            });

            OrderPageIndexChangedCommand = new RelayCommand<PageArgs>(p =>
            {
                LoadOrder(p.PageIndex);
            });

            BatchCheckedCommand = new RelayCommand(BatchCheck);
            BatchSettleCommand = new RelayCommand(BatchSettle);
            SettleCommand = new RelayCommand<long>(SettleTask);
            ExportCommand = new RelayCommand(Export);

            SearchTaskTotal();
        }



        private void Export()
        {

            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "csv files(*.csv)|*.csv";
            var result = save.ShowDialog();
            if (result == null || !result.Value)
            {
                return;
            }

            string fileName = save.FileName;

            Task.Factory.StartNew(() =>
            {
                IsLoading = true;
                var res = packTaskService.ShopTotalV2(SearchSkuId, SearchTaskId, null, StartDate, EndDate, SearchShopName,
                    SearchDepartment, 0, 0);//获取全部数据
                if (res.Success)
                {
                    //string title = "任务ID,日期,是否结清,部门,店铺,对接人,sku名称,sku数量,增值服务,打包服务,耗材服务,原价,促销折扣,结算价格,对接备注";
                    string title = "任务ID,日期,是否结清,所属部门,所属店铺,包装数量,收货数量,耗材总价,工序类型,工序套餐,工序单价,包装原价,包装折扣系数,包装折扣价,总收费";
                    var excelList = res.Data.ShopTotals.Select(x => x.ToString()).ToList();
                    excelList.Insert(0, title);
                    System.IO.File.WriteAllLines(fileName, excelList, Encoding.UTF8);
                }
                IsLoading = false;

            });

        }

        private void BatchCheck()
        {

            if (PackTaskTotalList.Count > 0)
                App.Current.Dispatcher.Invoke(() =>
                {
                    PackTaskTotalList.ForAll(s =>
                    {

                        s.TaskChecked = IsBatchChecked;
                    });

                });

        }

        private void SettleTask(long obj)
        {
            MessageBoxResult result = MessageBox.Show($"是否结清任务:{obj} ?", "提示",
                                           MessageBoxButton.YesNo,
                                           MessageBoxImage.Warning);
            if (result != MessageBoxResult.Yes) return;
            SettlePackTask(obj);
        }

        private void BatchSettle()
        {


            var ids = PackTaskTotalList.Where(p => p.TaskChecked).Select(p => p.TaskId).ToArray();
            if (ids.Length <= 0)
                return;
            MessageBoxResult result = MessageBox.Show("是否批量结清?", "提示",
                                          MessageBoxButton.YesNo,
                                          MessageBoxImage.Warning);
            if (result != MessageBoxResult.Yes) return;
            SettlePackTask(ids);
        }
        private void SettlePackTask(params long[] ids)
        {
            Task.Factory.StartNew(() =>
            {
                IsLoading = true;
                var res = packTaskService.BatchSettle(ids);
                if (res.Success)
                {
                    SearchTaskTotal();
                }
                IsLoading = false;
            });

        }

        private void SearchTaskTotal()
        {

            PackTaskTotalList = new ObservableCollection<ShopTotal>();
            Task.Factory.StartNew(() =>
            {
                IsLoading = true;
                var res = packTaskService.ShopTotalV2(SearchSkuId, SearchTaskId, null, StartDate, EndDate, SearchShopName,
                     SearchDepartment, PageIndex, PageSize);
                if (res != null && res.Success)
                {
                    OrderCount = res.Data.TotalCount;
                    TotalConsumableFees = res.Data.TotalConsumableFees;
                    TotalPackDiscountFees = res.Data.TotalPackDiscountFees;
                    TotalFees = TotalConsumableFees + TotalPackDiscountFees;
                    foreach (var shopTotal in res.Data.ShopTotals)
                    {
                        if (!shopTotal.ProcessComboName.IsNullOrEmpty())
                            shopTotal.FeesItemResponse = new Models.APIModel.Response.PackTask.FeesItemResponse
                            {
                                AllFees = shopTotal.AllFees.Value,
                                 PackFees=shopTotal.PackDisCountFees.Value,
                                  TaskId = shopTotal.TaskId,
                                   ProcessTypeName = shopTotal.ProcessTypeName,
                                    ProcessComboName = shopTotal.ProcessComboName,
                                     ConsumableFees =shopTotal.ConsumableFees,
                                      ConsumableList = shopTotal.ConsumableList,
                                        ProcessComboPrice = shopTotal.ProcessComboPrice,
                                         ProcessComboTaskCount = shopTotal.ProcessComboTaskCount,
                                          DiscountFoctor = shopTotal.DiscountFactor
                            };

                        App.Current.Dispatcher.Invoke(() =>
                        {
                            PackTaskTotalList.Add(shopTotal);
                        });
                    }
                    if (IsBatchChecked)
                    {
                        BatchCheck();
                    }
                }

                IsLoading = false;
            });


        }

        private void LoadOrder(int pageIndex)
        {
            SearchTask(pageIndex);
        }

        private void SearchTask(int pageIndex)
        {
            PageIndex = pageIndex;
            SearchTaskTotal();
        }
    }
}