using BBWY.Client.APIServices.QiKu;
using BBWY.Client.APIServices;
using BBWY.Client.Helpers;
using BBWY.Client.Models.APIModel.Response.PackTask;
using BBWY.Client.Models.PackTask;
using BBWY.Client.Models;
using BBWY.Client.Views.PackTask;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using WebSocketSharp;
using System.IO;
using BBWY.Client.Models.APIModel;
using Org.BouncyCastle.Bcpg;
using System.Threading;
using Org.BouncyCastle.Ocsp;
using BBWY.Client.Views.PackagingTask;

namespace BBWY.Client.ViewModels.PackTask
{
    public class PackDetailViewModel : BaseVM
    {

        private PackProcessType packProcessType;
        /// <summary>
        /// 推荐工序=0,自定义工序=1
        /// </summary>
        public PackProcessType PackProcessType { get => packProcessType; set { Set(ref packProcessType, value); } }

        private decimal allFees;
        /// <summary>
        /// 任务总费用
        /// </summary>
        public decimal AllFees { get => allFees; set { Set(ref allFees, value); } }


        private decimal processPrice;
        /// <summary>
        /// 工序单价
        /// </summary>
        public decimal ProcessPrice { get => processPrice; set { Set(ref processPrice, value); } }

        private decimal consumableFees;
        /// <summary>
        /// 耗材费用
        /// </summary>
        public decimal ConsumableFees { get => consumableFees; set { Set(ref consumableFees, value); } }

        public ObservableCollection<PackUserModel> packUserModelList;
        public ObservableCollection<PackUserModel> PackUserModelList { get => packUserModelList; set { Set(ref packUserModelList, value); } }



        // private decimal? customProcessSinglePrice;
        /// <summary>
        /// 定制工序单价
        /// </summary>
        public decimal? CustomProcessSinglePrice
        {
            get; set;
        }

        private string directionalSingleFees;

        public string DirectionalSingleFees
        {
            get => directionalSingleFees; set
            {

                Set(ref directionalSingleFees, value);
                try
                {
                    CustomProcessSinglePrice = decimal.Parse(DirectionalSingleFees);
                }
                catch
                {
                    CustomProcessSinglePrice = null;
                }

            }
        }
        private decimal packFees;
        /// <summary>
        /// 打包原价
        /// </summary>
        public decimal PackFees { get => packFees; set { Set(ref packFees, value); } }

        private decimal discountFactory;
        /// <summary>
        /// 折扣系数
        /// </summary>
        public decimal DiscountFactory { get => discountFactory; set { Set(ref discountFactory, value); } }

        private decimal packDiscountFees;
        /// <summary>
        /// 打包折后价价
        /// </summary>
        public decimal PackDiscountFees { get => packDiscountFees; set { Set(ref packDiscountFees, value); } }



        private int processTaskCount;
        /// <summary>
        /// 工序任务量
        /// </summary>
        public int ProcessTaskCount
        {
            get => processTaskCount; set
            {
                Set(ref processTaskCount, value);
                if (PackProcessType == PackProcessType.推荐工序 && SelectProcessComboIdV2 > 0 && ProcessTaskCount > 0)

                    TotalPackFeesDetail(null, ProcessTaskCount, SelectProcessComboIdV2);
                if (PackProcessType == PackProcessType.自定义工序 && !SelectProcessType.IsNullOrEmpty() && ProcessTaskCount > 0)
                    TotalPackFeesDetail(SelectProcessType, ProcessTaskCount, null);
            }
        }

        //void OnProcessTaskCountChanged()
        //{
        //    PackFees = decimal.Parse((ProcessTaskCount * ProcessPrice).ToString("0.00")); ;
        //    PackDiscountFees = decimal.Parse((PackFees * DiscountFactory).ToString("0.00"));
        //}


        private ObservableCollection<ProcessComboResponse> processComboList;
        /// <summary>
        /// 套餐类型列表
        /// </summary>
        public ObservableCollection<ProcessComboResponse> ProcessComboList { get => processComboList; set { Set(ref processComboList, value); } }

        private ObservableCollection<ProcessComboResponse> processComboListV2;
        /// <summary>
        /// 套餐类型列表
        /// </summary>
        public ObservableCollection<ProcessComboResponse> ProcessComboListV2 { get => processComboListV2; set { Set(ref processComboListV2, value); } }



        private long selectProcessComboId;
        /// <summary>
        /// 选中套餐类型
        /// </summary>
        public long SelectProcessComboId
        {
            get => selectProcessComboId; set
            {
                Set(ref selectProcessComboId, value);

                OnProcessComboChanged(SelectProcessComboId);
            }
        }


        private long selectProcessComboIdV2;
        /// <summary>
        /// 选中套餐类型(推荐工序)
        /// </summary>
        public long SelectProcessComboIdV2
        {
            get => selectProcessComboIdV2; set
            {
                Set(ref selectProcessComboIdV2, value);

                OnProcessComboChanged(SelectProcessComboIdV2);
            }
        }





        public bool isConsumableTypeListEnable;
        public bool IsConsumableTypeListEnable { get => isConsumableTypeListEnable; set { Set(ref isConsumableTypeListEnable, value); } }
        private void OnProcessComboChanged(long SelectProcessComboId, int type = 1)
        {
            if (SelectProcessComboId <= 0)
            {
                return;
            }
            if (PackProcessType == PackProcessType.推荐工序)
            {
                if (ProcessComboListV2 == null || ProcessComboListV2.Count <= 0)
                {
                    return;
                }

                if (!DirectionalSingleFees.IsNullOrEmpty())
                    DirectionalSingleFees = string.Empty;//

                var selectProcessComboData = ProcessComboListV2.
                SingleOrDefault(p => p.ProcessComboId == SelectProcessComboId);
                App.Current.Dispatcher.Invoke(new Action(() =>
                {
                    ConsumableServiceList.Clear();
                }));
                IsConsumableTypeListEnable = false;
                ProcessPrice = selectProcessComboData.ProcessComboNamePrice;

                ConsumableFees = 0;
                AllFees = ConsumableFees + PackDiscountFees;
                if (selectProcessComboData != null && selectProcessComboData.ConsumableTypeList != null && selectProcessComboData.ConsumableTypeList.Count > 0)//自动添加列表
                {

                    foreach (var item in selectProcessComboData.ConsumableTypeList)
                    {
                        App.Current.Dispatcher.Invoke(new Action(() =>
                        {

                            ConsumableServiceList.Add(new PackItemModel
                            {
                                ConsumableTypeList = new ObservableCollection<string> { item.ConsumableTypeName },
                                ConsumableType = item.ConsumableTypeName,
                                ConsumableItemList = item.ConsumableList,
                                //ConsumableItem = item.ConsumableList.FirstOrDefault()?.ConsumableName,
                                //ConsumablePrice = item.ConsumableList.FirstOrDefault().ConsumablePrice,
                                TaskCount = ProcessTaskCount,
                                TotalConsumableFees = ToTalConsumableFees,
                            }); ;
                        }));
                    }

                }
                //关联工序类型名

                var discountRes = processService.GetDiscountFactory(SelectProcessType, ProcessTaskCount, SelectProcessComboIdV2);
                if (!discountRes.Success)
                {
                    System.Windows.MessageBox.Show(discountRes.Msg);
                    return;
                }

                if (discountRes.Success && discountRes.Data != null)
                {
                    DiscountFactory = discountRes.Data.DiscountFactory;
                    if (FeesMode == FeesMode.定向收费 && CustomProcessSinglePrice != null)
                    {
                        PackFees = decimal.Parse((ProcessTaskCount * CustomProcessSinglePrice.Value).ToString("0.00"));
                    }
                    else
                    {
                        FeesMode = discountRes.Data.FeesMode;
                        PackFees = decimal.Parse((ProcessTaskCount * ProcessPrice).ToString("0.00"));
                    }



                    PackDiscountFees = decimal.Parse((PackFees * DiscountFactory).ToString("0.00"));
                    AllFees = ConsumableFees + PackDiscountFees;
                }

            }
            if (PackProcessType == PackProcessType.自定义工序)
            {
                var selectProcessComboData = ProcessComboList.
                 SingleOrDefault(p => p.ProcessComboId == SelectProcessComboId);


                App.Current.Dispatcher.Invoke(new Action(() =>
                {
                    ConsumableServiceList.Clear();
                }));
                IsConsumableTypeListEnable = false;
                if (SelectProcessType == "定制")
                {
                    IsConsumableTypeListEnable = true;

                    ConsumableServiceList = new ObservableCollection<PackItemModel>();


                }
                else
                {
                    if (!DirectionalSingleFees.IsNullOrEmpty())
                        DirectionalSingleFees = string.Empty;
                }
                ConsumableFees = 0;
                AllFees = ConsumableFees + PackDiscountFees;
                if (selectProcessComboData != null && selectProcessComboData.ConsumableTypeList != null && selectProcessComboData.ConsumableTypeList.Count > 0)//自动添加列表
                {

                    foreach (var item in selectProcessComboData.ConsumableTypeList)
                    {
                        App.Current.Dispatcher.Invoke(new Action(() =>
                        {

                            ConsumableServiceList.Add(new PackItemModel
                            {
                                ConsumableTypeList = new ObservableCollection<string> { item.ConsumableTypeName },
                                ConsumableType = item.ConsumableTypeName,
                                ConsumableItemList = item.ConsumableList,
                                //ConsumableItem = item.ConsumableList.FirstOrDefault()?.ConsumableName,
                                //ConsumablePrice = item.ConsumableList.FirstOrDefault().ConsumablePrice,
                                TaskCount = ProcessTaskCount,
                                TotalConsumableFees = ToTalConsumableFees,
                            }); ;
                        }));
                    }

                }
            }

            if (PackProcessType == PackProcessType.推荐工序 && SelectProcessComboIdV2 > 0 && ProcessTaskCount > 0)
                TotalPackFeesDetail(null, ProcessTaskCount, SelectProcessComboIdV2);
            if (PackProcessType == PackProcessType.自定义工序 && !SelectProcessType.IsNullOrEmpty() && ProcessTaskCount > 0)
                TotalPackFeesDetail(SelectProcessType, ProcessTaskCount, null);


        }
        private void TotalPackFeesDetail(string processType, int taskCount, long? processComboId)
        {


            var discountRes = processService.GetDiscountFactory(processType, taskCount, processComboId);
            if (!discountRes.Success)
            {
                System.Windows.MessageBox.Show(discountRes.Msg);
                return;
            }

            if (discountRes.Success && discountRes.Data != null)
            {
                DiscountFactory = discountRes.Data.DiscountFactory;
                if (FeesMode == FeesMode.定向收费 && CustomProcessSinglePrice != null)
                {
                    PackFees = decimal.Parse((taskCount * CustomProcessSinglePrice.Value).ToString("0.00"));
                }
                else
                {
                    FeesMode = discountRes.Data.FeesMode;
                    PackFees = decimal.Parse((taskCount * ProcessPrice).ToString("0.00"));
                }



                PackDiscountFees = decimal.Parse((PackFees * DiscountFactory).ToString("0.00"));
                AllFees = ConsumableFees + PackDiscountFees;
            }
            //统计打包费用


        }



        private List<ProcessTypeResponse> processTypeList;
        /// <summary>
        /// 工序类型列表
        /// </summary>
        public List<ProcessTypeResponse> ProcessTypeList { get => processTypeList; set { Set(ref processTypeList, value); } }




        private string selectProcessType;
        /// <summary>
        /// 选中工序类型
        /// </summary>
        public string SelectProcessType
        {
            get => selectProcessType; set
            {
                Set(ref selectProcessType, value);
                OnProcessTypeChanged(SelectProcessType);
            }
        }
        private void OnProcessTypeChanged(string SelectProcessType)
        {

            if (SelectProcessType.IsNullOrEmpty()) return;

            var processTypeData = ProcessTypeList.SingleOrDefault(p => p.ProcessTypeName == SelectProcessType);
            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                ProcessPrice = processTypeData.ProcessTypePrice;
                ProcessComboList = processTypeData.ProcessComboList;

            }));
            if (ProcessComboList != null || ProcessComboList.Count() > 0)
            {
                SelectProcessComboId = ProcessComboList.FirstOrDefault().ProcessComboId;
            }


        }

        private string selectProductResistant;
        /// <summary>
        /// 选中易碎等级
        /// </summary>
        public string SelectProductResistant
        {
            get => selectProductResistant; set
            {
                Set(ref selectProductResistant, value);
                OnProductResistantChanged(SelectProductResistant);
            }
        }
        private void OnProductResistantChanged(string SelectProductResistant, int isTaskCount = 0)
        {
            if (SelectProductResistant.IsNullOrEmpty())
            {

                return;
            }

            if (isTaskCount == 0)//获取绑定的耗材列表
            {
                if (ProductResistantList == null || ProductResistantList.Count <= 0 || SelectProductResistant == null) return;
                var processTypeData = ProductResistantList.SingleOrDefault(p => p.ProductResistantName == SelectProductResistant);
                App.Current.Dispatcher.Invoke(new Action(() =>
                {
                    //ProcessPrice = processTypeData.ProcessTypePrice;
                    ProcessComboListV2 = processTypeData.ProcessComboList;
                }));
                if (ProcessComboListV2 != null || ProcessComboListV2.Count() > 0)
                {
                    SelectProcessComboIdV2 = ProcessComboListV2.FirstOrDefault().ProcessComboId;
                }

            }
        }

        private string suggestPackUserName;
        /// <summary>
        /// 打包人
        /// </summary>
        public string SuggestPackUserName { get => suggestPackUserName; set { Set(ref suggestPackUserName, value); } }

        private int? floorDragNumber;
        public int? FloorDragNumber { get => floorDragNumber; set { Set(ref floorDragNumber, value); } }

        private string packUserName;
        /// <summary>
        /// 打包人
        /// </summary>
        public string PackUserName { get => packUserName; set { Set(ref packUserName, value); } }


        private string processComboName;
        /// <summary>
        /// 工序套餐名称
        /// </summary>
        public string ProcessComboName { get => processComboName; set { Set(ref processComboName, value); } }




        private decimal? packerFee;
        /// <summary>
        /// 包装员费用
        /// </summary>
        public decimal? PackerFee { get => packerFee; set { Set(ref packerFee, value); } }


        private int incrementPartTaskCount;
        /// <summary>
        /// 配件任务数量
        /// </summary>
        public int IncrementPartTaskCount { get => incrementPartTaskCount; set { Set(ref incrementPartTaskCount, value); } }


        private int incrementPartCount;
        /// <summary>
        /// 配件数量
        /// </summary>
        public int IncrementPartCount { get => incrementPartCount; set { Set(ref incrementPartCount, value); } }

        private string directionalFees;
        /// <summary>
        /// 定向费用
        /// </summary>
        public string DirectionalFees { get => directionalFees; set { Set(ref directionalFees, value); } }


        private BitmapImage barcodeImage;
        /// <summary>
        /// 任务Id条形码
        /// </summary>
        public BitmapImage BarcodeImage { get => barcodeImage; set { Set(ref barcodeImage, value); } }

        private BitmapImage taskImage;
        /// <summary>
        /// 任务Id条形码
        /// </summary>
        public BitmapImage TaskImage { get => taskImage; set { Set(ref taskImage, value); } }

        private string printName;

        public string PrintName { get => printName; set { Set(ref printName, value); } }

        private ObservableCollection<string> printList;
        /// <summary>
        /// 打印机列表
        /// </summary>
        public ObservableCollection<string> PrintList { get => printList; set { Set(ref printList, value); } }

        private ObservableCollection<PackTaskModel> packTaskList;
        /// <summary>
        /// 动态数据表
        /// </summary>
        public ObservableCollection<PackTaskModel> PackTaskList { get => packTaskList; set { Set(ref packTaskList, value); } }


        private PackTaskModel packTaskModel;

        public PackTaskModel PackTaskModel { get => packTaskModel; set { Set(ref packTaskModel, value); } } //


        /// <summary>
        /// 添加打包人
        /// </summary>
        public ICommand AddPackUserCommand { get; set; }


        public ICommand AddConsumableCommand { get; set; }

        public ICommand UpLoadPackCommand { get; set; }

        public ICommand SetAllCountCommand { get; set; }


        public ICommand PrintCommand { get; set; }

        public ICommand SetCustomProcessPriceCommand { get; set; }
        readonly PackTaskService packTaskService;

        readonly PackUserService packUserService;

        readonly PackDetailService packDetailService;
        readonly ProcessService processService;
        private ObservableCollection<PackItemModel> increateList = new ObservableCollection<PackItemModel>();
        public ObservableCollection<PackItemModel> IncreateList { get => increateList; set { Set(ref increateList, value); } } //

        //private ObservableCollection<PackItemModel>
        // packList = new ObservableCollection<PackItemModel>();
        //public ObservableCollection<PackItemModel> PackList { get => packList; set { Set(ref packList, value); } } //

        private ObservableCollection<PackItemModel>
            consumableServiceList = new ObservableCollection<PackItemModel>();
        public ObservableCollection<PackItemModel> ConsumableServiceList { get => consumableServiceList; set { Set(ref consumableServiceList, value); } } //




        private ObservableCollection<PackItemModel> basicPackProcessList = new ObservableCollection<PackItemModel>();
        private ObservableCollection<PackItemModel> incrementProcessList = new ObservableCollection<PackItemModel>();
        /// <summary>
        ///增量工序
        /// </summary>
        public ObservableCollection<PackItemModel> IncrementProcessList { get => incrementProcessList; set { Set(ref incrementProcessList, value); } } //
        /// <summary>
        /// 基础包装工序
        /// </summary>
        public ObservableCollection<PackItemModel> BasicPackProcessList { get => basicPackProcessList; set { Set(ref basicPackProcessList, value); } }





        private string discount = "1";
        /// <summary>
        /// 折扣
        /// </summary>
        public string Discount { get => discount; set { Set(ref discount, value); } }
        public ObservableCollection<PackUser> MemberList { get; set; } = new ObservableCollection<PackUser>();
        public ObservableCollection<ConsumableModel> ConsumableList { get; set; } = new ObservableCollection<ConsumableModel>();



        /// <summary>
        /// 加载原数据
        /// </summary>
        public List<PackItemModel> LoadList = new List<PackItemModel>();



        public void InitPrintList()
        {
            TaskImage = MyPrintHelper.GetBarcodeImage(TaskId.ToString(), 300, 60);

            BarcodeImage = MyPrintHelper.GetBarcodeImage(SkuId, 300, 60);


            PrintList = new ObservableCollection<string>();
            var printingNames = PrinterSettings.InstalledPrinters;//获取本机的打印机数据
            int index = -1;
            int selectIndex = 0;
            foreach (string name in printingNames)
            {
                if (name == "Microsoft XPS Document Writer" || name == "Microsoft Print to PDF" || name == "Fax")
                {
                    continue;
                }
                index++;
                if (name.Contains("Deli"))
                {
                    selectIndex = index;
                }
                PrintList.Add(name);
            }
            try
            {
                var applicationPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string printNames = Path.Combine(applicationPath, "printName.init");
                if (File.Exists(printNames))
                {
                    PrintName = File.ReadAllText(printNames);
                }
                else
                {
                    if (PrintList.Count > 0)
                    {
                        PrintName = PrintList[0].ToString();
                    }
                }
            }
            catch (Exception)
            {


            }

        }

        public PackDetailViewModel(PackTaskService packTaskService, PackDetailService packDetailService, ProcessService processService, PackUserService packUserService)//, long taskId
        {
            this.processService = processService;
            this.packTaskService = packTaskService;
            this.packDetailService = packDetailService;


            PackUserModelList = new ObservableCollection<PackUserModel>();
            AddConsumableCommand = new RelayCommand(AddConsumable);
            UpLoadPackCommand = new RelayCommand<object>(UpLoadPack);
            SetAllCountCommand = new RelayCommand<object>(SetAllCount);
            SetCustomProcessPriceCommand = new RelayCommand(SetCustomProcessPrice);
            AddPackUserCommand = new RelayCommand(AddPackUser);
            this.packUserService = packUserService;
        }

        private void AddPackUser()
        {

            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                PackUserModelList.Add(new PackUserModel()
                {
                    TaskCount = ProcessTaskCount,
                    MemberList = MemberList,
                });
            }));
        }

        /// <summary>
        /// 所有的耗材类型
        /// </summary>
        public List<ConsumableTypeResponse> ConsumableTypeList { get; set; }
        /// <summary>
        /// 设置定制工序单价
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void SetCustomProcessPrice()
        {
            if (CustomProcessSinglePrice == null)
            {
                TotalPackFeesDetail(null, ProcessTaskCount, SelectProcessComboIdV2);
                return;
            }
            if (SelectProcessType != "定制")
            {
                SelectProcessType = "定制";
                SelectProcessComboId = ProcessComboList.FirstOrDefault().ProcessComboId;
            }
            FeesMode = FeesMode.定向收费;

            ProcessPrice = CustomProcessSinglePrice.Value;
            PackFees = decimal.Parse((ProcessTaskCount * CustomProcessSinglePrice.Value).ToString("0.00")); ;
            PackDiscountFees = decimal.Parse((PackFees * DiscountFactory).ToString("0.00"));
            AllFees = ConsumableFees + PackDiscountFees;


        }




        private List<ProductResistantResponse> productResistantList;
        public List<ProductResistantResponse> ProductResistantList { get => productResistantList; set { Set(ref productResistantList, value); } }
        /// <summary>
        /// 加载任务数据
        /// </summary>
        public void LoadPackDatas()
        {
            IncrementPartTaskCount = TaskCount;
            try
            {
                InitPrintList();
            }
            catch (Exception)
            {


            }

            LoadList = new List<PackItemModel>();
            Task task = Task.Factory.StartNew(() =>
            {
                var resMember = this.packUserService.GetPackMembers();//成员表
                if (resMember.Success)
                {
                    MemberList = new ObservableCollection<PackUser>();
                    foreach (var item in resMember.Data)
                    {
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            MemberList.Add(item);
                        });
                    }
                }
                var res = this.processService.GetProcessTypeList();
                if (!res.Success)
                {
                    App.Current.Dispatcher.Invoke(() =>
                    {

                        MessageBox.Show(res.Msg);
                    });
                }
                ProcessTaskCount = TaskCount;
                if (res.Success && res.Data != null)
                {

                    ConsumableTypeList = res.Data.ConsumableTypeList;
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        ProcessTypeList = res.Data.ProcessTypeList;
                        ProductResistantList = res.Data.ProductResistantList;
                    });

                }

                var packDetailRes = packDetailService.GetPackDetail(TaskId);

                if (!packDetailRes.Success)
                {

                    App.Current.Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show(packDetailRes.Msg);
                    });
                }
                if (packDetailRes.Success && packDetailRes.Data != null)
                {

                    var resData = packDetailRes.Data;


                    PackProcessType = resData.PackProcessType;

                    switch (PackProcessType)
                    {
                        case PackProcessType.推荐工序:
                            SelectProductResistant = resData.ProductResistantName;
                            SelectProcessComboIdV2 = resData.ProcessComboId;
                            break;
                        case PackProcessType.自定义工序:
                            SelectProcessType = resData.ProcessTypeName;
                            SelectProcessComboId = resData.ProcessComboId;
                            break;
                        default:
                            break;
                    }
                    SuggestPackUserName = resData.SuggestPackUserName;


                    ProcessTaskCount = resData.ProcessTaskCount;
                    DirectionalSingleFees = resData.DirectionalSingleFees?.ToString();
                    if (resData.DirectionalSingleFees > 0)
                    {
                        SetCustomProcessPrice();
                    }
                    if (resData.PackUserList != null && resData.PackUserList.Count > 0)
                    {
                        foreach (var packuser in resData.PackUserList)
                        {
                            App.Current.Dispatcher.Invoke(() =>
                            {
                                PackUserModelList.Add(new PackUserModel
                                {
                                    MemberList = MemberList,
                                    SelectUserId = packuser.UserId,
                                    TaskCount = packuser.TaskCount
                                });
                            });

                        }

                    }
                    if (resData.ConsumableList != null && resData.ConsumableList.Count > 0)
                    {

                        if (ConsumableServiceList != null && ConsumableServiceList.Count > 0)
                        {
                            foreach (var con in resData.ConsumableList)
                            {
                                var condate = ConsumableServiceList.FirstOrDefault(c => c.ConsumableItem.IsNullOrEmpty() && c.ConsumableType == con.ConsumableTypeName);
                                if (condate != null)

                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        condate.ConsumablePrice = con.ConsumablePrice;
                                        condate.SelectId = con.ConsumableId;
                                        condate.TaskCount = con.TaskCount;
                                        condate.IsHideDelete = true;

                                    });
                                else
                                {
                                    ObservableCollection<string> consumableTypeList = new ObservableCollection<string>();

                                    foreach (var item in ConsumableTypeList)
                                    {
                                        consumableTypeList.Add(item.ConsumableTypeName);
                                    }

                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        ConsumableServiceList.Add(new PackItemModel
                                        {

                                            ConsumableTypeList = consumableTypeList,
                                            AllConsumableTypeList = ConsumableTypeList,
                                            TotalConsumableFees = ToTalConsumableFees,
                                            ConsumableType = con.ConsumableTypeName,
                                            ConsumablePrice = con.ConsumablePrice,
                                            SelectId = con.ConsumableId,
                                            TaskCount = con.TaskCount
                                        });

                                    });

                                }

                            }
                        }
                        else
                        {
                            ObservableCollection<string> consumableTypeList = new ObservableCollection<string>();

                            foreach (var item in ConsumableTypeList)
                            {
                                consumableTypeList.Add(item.ConsumableTypeName);
                            }


                            foreach (var con in resData.ConsumableList)
                            {


                                App.Current.Dispatcher.Invoke(new Action(() =>
                                {
                                    ConsumableServiceList.Add(new PackItemModel()
                                    {
                                        ItemCount = TaskCount,
                                        ConsumableList = ConsumableList,
                                        ConsumableTypeList = consumableTypeList,
                                        AllConsumableTypeList = ConsumableTypeList,
                                        ConsumableType = con.ConsumableTypeName,
                                        ConsumablePrice = con.ConsumablePrice,
                                        SelectId = con.ConsumableId,
                                        TaskCount = con.TaskCount,
                                        TotalConsumableFees = ToTalConsumableFees


                                    });
                                }));

                            }


                        }



                    }
                }


            });
        }

        private void ToTalConsumableFees()
        {

            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                ConsumableFees = ConsumableServiceList.Select(c => c.ConsumablePrice * c.TaskCount).Sum();
                AllFees = ConsumableFees + PackDiscountFees;
            }));

        }

        /// <summary>
        /// 批量设置耗材数量
        /// </summary>
        /// <param name="obj"></param>
        private void SetAllCount(object obj)
        {
            if (ConsumableServiceList == null || ConsumableServiceList.Count <= 0)
            {
                return;
            }

            SetCountWindow set = new SetCountWindow();
            set.SetCount = new Action<int>((s) =>
            {
                var lbox = obj as ListBox;
                var serviceList = lbox.ItemsSource as ObservableCollection<PackItemModel>;
                foreach (var item in serviceList)
                {
                    if (item.ConsumableItem == null)
                    {
                        item.ConsumableItem = ConsumableServiceList.Select(c => c.ConsumableList).FirstOrDefault()?.Where(c => c.Id == item.SelectId).FirstOrDefault()?.Name;
                    }

                    item.TaskCount = s;
                }
                lbox.ItemsSource = serviceList;
            });
            set.Show();
        }

        private long taskId;
        public long TaskId { get => taskId; set { Set(ref taskId, value); } } //


        private int taskCount;
        public int TaskCount { get => taskCount; set { Set(ref taskCount, value); } } //
        public string OrderId { get; set; }
        public string SkuId { get; set; }


        /// <summary>
        /// 计费模式
        /// </summary>
        public FeesMode FeesMode { get; set; }

        public DateTime? packCompletionOverTime;
        /// <summary>
        /// 打包完成时间(超时时间)
        /// </summary>
        public DateTime? PackCompletionOverTime { get => packCompletionOverTime; set { Set(ref packCompletionOverTime, value); } } //


        public List<string> consumableNameList;
        /// <summary>
        /// 耗材名称列表
        /// </summary>
        public List<string> ConsumableNameList { get => consumableNameList; set { Set(ref consumableNameList, value); } } //



        /// <summary>
        /// 上传数据   (判断是否超量)  统一上传
        /// </summary>
        private void UpLoadPack(object obj)
        {
            if (PackUserModelList == null || PackUserModelList.Count <= 0)
            {
                System.Windows.MessageBox.Show("信息不完整,打包人设置有误");
                return;
            }
            if (PackUserModelList != null && PackUserModelList.Count > 0)
            {
                if (PackUserModelList.Any(p => p.SelectUserId.IsNullOrEmpty() || p.TaskCount <= 0))
                {
                    System.Windows.MessageBox.Show("信息不完整,打包人设置有误");
                    return;
                }

                var totalPackTaskCount = PackUserModelList.Select(p => p.TaskCount).Sum();
                if (totalPackTaskCount != ProcessTaskCount)
                {
                    System.Windows.MessageBox.Show($"工序任务总量:{ProcessTaskCount},与打包人任务总量:{totalPackTaskCount} 不相等.");
                    return;
                }

                if (PackUserModelList.Select(p => p.SelectUserId).Distinct().Count() != PackUserModelList.Count())
                {
                    System.Windows.MessageBox.Show($"请勿重复设置打包人任务.");
                    return;
                }

            }
            if (ConsumableServiceList != null && ConsumableServiceList.Count > 0)
            {
                if (ConsumableServiceList.Any(p => p.SelectId == null || p.TaskCount <= 0))
                {
                    System.Windows.MessageBox.Show("信息不完整,耗材设置有误");
                    return;
                }
                foreach (var item in ConsumableServiceList)
                {
                    if (item.TaskCount != ProcessTaskCount)
                    {
                        System.Windows.MessageBox.Show($"耗材分类:{item.ConsumableType}下,任务量:{item.TaskCount} 不等于工序任务总量:{ProcessTaskCount}.");
                        return;
                    }
                }



            }
            if (CustomProcessSinglePrice != null)
            {
                FeesMode = FeesMode.定向收费;
            }
            SetPackDetailRequest setPackDetailRequest = new SetPackDetailRequest()
            {
                DirectionalSingleFees = CustomProcessSinglePrice,
                FeesMode = FeesMode,
                AllFees = AllFees,
                ConsumableFees = ConsumableFees,
                TaskId = TaskId,
                PackUserList = PackUserModelList?.Select(p => new PackUserModelRequest { TaskCount = p.TaskCount, UserId = p.SelectUserId }).ToList(),
                ConsumableList = ConsumableServiceList?.Select(c => new ConsumableRequest { ConsumableId = c.SelectId.Value, TaskCount = c.TaskCount, ConsumableTypeName = c.ConsumableType, ConsumablePrice = c.ConsumablePrice, IsSaveConfig = c.IsHideDelete }).ToList(),
                DiscountFactory = DiscountFactory,
                PackDiscountPrice = PackDiscountFees,
                PackPrice = PackFees,
                ProcessComboCount = ProcessTaskCount,
                ProcessComboId = PackProcessType == PackProcessType.推荐工序 ? SelectProcessComboIdV2 : SelectProcessComboId,
                ProcessTypeName = SelectProcessType,
                PackProcessType = PackProcessType,
                ProductResistantName = SelectProductResistant,

            };


            var res = packDetailService.SetPackDetailV2(setPackDetailRequest);

            if (res == null)
            {
                System.Windows.MessageBox.Show("网络异常!");
                return;
            }
            if (!res.Success)
            {
                System.Windows.MessageBox.Show(res.Msg);
                return;
            }

            var names = PackUserModelList.Select(c => c.MemberList.SingleOrDefault(s => s.Id == c.SelectUserId)?.UserName);
            PackUserName = string.Join(",",names);

            ProcessTaskCount = res.Data.ProcessTaskCount;
            PackerFee = res.Data.PackerFees;
            ProcessComboName = res.Data.ProcessComboName;
            ConsumableNameList = res.Data.ConsumableNameList;
            PackCompletionOverTime = res.Data.PackCompletionOverTime;

            // new TipsWindow("上传成功!").Show();
            var win = obj as PackDetailWindow;


            PrintPackDetailWindow print = new PrintPackDetailWindow(win);
            print.ShowDialog();

            if (ReflashWindow != null)
                ReflashWindow();
            win.Close();

        }
        /// <summary>
        /// 刷新界面
        /// </summary>
        public Action ReflashWindow { get; set; }








        private void AddConsumable()
        {

            ObservableCollection<string> consumableTypeList = new ObservableCollection<string>();

            foreach (var item in ConsumableTypeList)
            {
                consumableTypeList.Add(item.ConsumableTypeName);
            }

            App.Current.Dispatcher.Invoke(new Action(() =>
            {




                ConsumableServiceList.Add(new PackItemModel()
                {
                    TaskCount = ProcessTaskCount,
                    ConsumableTypeList = consumableTypeList,
                    AllConsumableTypeList = ConsumableTypeList,
                    TotalConsumableFees = ToTalConsumableFees


                });
            }));

        }
    }
}