using BBWYB.Client.APIServices;
using BBWYB.Client.Helpers;
using BBWYB.Client.Models;
using BBWYB.Client.Models._1688;
using BBWYB.Client.Views;
using BBWYB.Client.Views._1688;
using BBWYB.Client.Views.PackPurchaseTaska;
using BBWYB.Common.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace BBWYB.Client
{

    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    public class GlobalContext : ObservableObject
    {
        public GlobalContext()
        {
            BBWYBApiVersion = "10043";
        }

        public List<_1688CookieModel> _1688CookieList { get; set; } = new List<_1688CookieModel>();

        private User user;

        public User User { get => user; set { SetProperty(ref user, value); } }

        public string UserToken { get; set; }

        public IList<LogisticsResponse> LogisticsResponseList { get; set; }

        /// <summary>
        /// JD客户端
        /// </summary>
        //public IJdClient JdClient { get; set; }

        #region APIHost
        public string BBWYApiHost { get; set; }

        public string MDSApiHost { get; set; }
        public string BBWYCApiHost { get; set; }
        public string QKApiHost { get; set; }

        public string BBWYBApiVersion { get; set; }
        public Window CurryWindow { get; set; }
        #endregion

        #region Web
        public string GetUserString()
        {
            return JsonConvert.SerializeObject(User);
        }

        public string GetClientApiVersion()
        {
            return BBWYBApiVersion;
        }

        public void CallALiWangWang(string sellerLoginId)
        {
            var url = $"aliim:sendmsg?siteid=cnalichn&portalId=&gid=&itemsId=&touid=cnalichn{sellerLoginId}&status=1";
            try
            {
                //Process.Start("explorer.exe", url);
                ShellExecuteHelper.ShellExecute(IntPtr.Zero, "open", url, string.Empty, string.Empty, ShellExecuteHelper.ShowCommands.SW_SHOWNORMAL);
            }
            catch (Exception ex)
            {
                try
                {
                    Clipboard.SetText(url);
                }
                catch { }
                MessageBox.Show($"{ex.Message}\r\n唤醒旺旺失败,唤醒链接已复制到剪切板,请手动打开浏览器唤醒", "提示");
            }
        }

        /// <summary>
        /// 对web版提供的修改打包任务方法
        /// </summary>
        /// <param name="belongSkuId">订单sku归属的来源sku(JD)</param>
        /// <param name="orderId">订单Id</param>
        /// <param name="skuLogo">sku图片</param>
        /// <param name="skuTitle">sku标题</param>
        /// <param name="originShopName">订单来源店铺名称</param>
        public void OpenUpdatePurchaseTask(string belongSkuId, string orderId, string skuLogo, string skuTitle, string originShopName)
        {
            var app = App.Current as App;
            var sp = app.ServiceProvider;

            PackPurchaseTaskService packPurchaseTaskService = null;
            using (var s = sp.CreateScope())
            {
                packPurchaseTaskService = s.ServiceProvider.GetRequiredService<PackPurchaseTaskService>();
            }

            var orderSku = new OrderSku()
            {
                OrderId = orderId,
                BelongSkuId = belongSkuId,
                Title = skuTitle,
                Logo = skuLogo,

            };

            var res = packPurchaseTaskService.GetOrderTask(orderSku.BelongSkuId, orderSku.OrderId);
            if (res == null || !res.Success)
            {
                MessageBox.Show("网络异常!查不到任务");
                return;
            }
            if (res.Data == null)
            {
                MessageBox.Show("打包任务,不存在或已被删除,请重新发起任务!");
                return;
            }
            UpdatePurchaseTaskWindow packTask = new(res.Data, originShopName, orderSku);
            if (!packTask.IsClosed)
                packTask.Show();
            //
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="IsNeedLogin">是否必须登陆</param>
        /// <returns></returns>
        public async Task<string> Login1688_(string userName, string password, bool IsNeedLogin)
        {
            return await Task.Factory.StartNew<string>(() =>
                {
                    if (!IsNeedLogin)
                    {
                        if (_1688CookieList.Any(c => c.UserName == userName))
                        {
                            return _1688CookieList.FirstOrDefault(c => c.UserName == userName).Cookie;
                        }
                    }
                    string cookie = string.Empty;
                    try
                    {
                        //检查是否跨线程

                        if (!App.Current.Dispatcher.CheckAccess())
                        {
                            App.Current.Dispatcher.Invoke(new Action(() =>
                            {
                                var loginWindow = new Login1688Window(userName, password);
                                loginWindow.ShowDialog();
                                var newCookie = loginWindow.downCookies;


                                if (!string.IsNullOrEmpty(newCookie))
                                    //更新或者添加
                                    if (_1688CookieList.Any(c => c.UserName == userName))
                                    {
                                        var oldCookie = _1688CookieList.FirstOrDefault(c => c.UserName == userName);
                                        oldCookie.Cookie = newCookie;
                                    }
                                    else
                                    {
                                        _1688CookieList.Add(new _1688CookieModel() { UserName = userName, Cookie = newCookie });
                                    }

                                cookie = loginWindow.downCookies;

                            }));
                        }
                    }
                    catch (Exception ex)
                    {


                    }
                    return cookie;

                });






        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="IsNeedLogin">是否必须登陆</param>
        /// <returns></returns>
        public async Task<string> Login1688123(string userName, string password, bool IsNeedLogin)
        {
            return await Task.Factory.StartNew<string>(() =>
            {
                if (!IsNeedLogin)
                {
                    if (_1688CookieList.Any(c => c.UserName == userName))
                    {
                        return _1688CookieList.FirstOrDefault(c => c.UserName == userName).Cookie;
                    }
                }
                string cookie = string.Empty;

                try
                {
                    //检查是否跨线程

                    if (!App.Current.Dispatcher.CheckAccess())
                    {
                        App.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            var loginWindow = new NewLogin1688Window(userName, password);
                            loginWindow.ShowDialog();
                            var newCookie = loginWindow.downCookies;
                            //更新或者添加
                            if (_1688CookieList.Any(c => c.UserName == userName))
                            {
                                var oldCookie = _1688CookieList.FirstOrDefault(c => c.UserName == userName);
                                oldCookie.Cookie = newCookie;
                            }
                            else
                            {
                                _1688CookieList.Add(new _1688CookieModel() { UserName = userName, Cookie = newCookie });
                            }
                            cookie = loginWindow.downCookies;

                        }));
                    }
                    //else
                    //{
                    //    var loginWindow = new NewLogin1688Window(userName, password);
                    //    loginWindow.ShowDialog();
                    //    var newCookie = loginWindow.downCookies;
                    //    //更新或者添加
                    //    if (_1688CookieList.Any(c => c.UserName == userName))
                    //    {
                    //        var oldCookie = _1688CookieList.FirstOrDefault(c => c.UserName == userName);
                    //        oldCookie.Cookie = newCookie;
                    //    }
                    //    else
                    //    {
                    //        _1688CookieList.Add(new _1688CookieModel() { UserName = userName, Cookie = newCookie });
                    //    }
                    //    cookie = loginWindow.downCookies;

                    //}
                }
                catch (Exception ex)
                {


                }
                return cookie;

            });






        }




        /// <summary>
        /// 客户端登陆 不获取cookie
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="IsNeedLogin">是否必须登陆</param>
        /// <returns></returns>
        public string  Login1688(string userName, string password, bool IsNeedLogin)
        {

            if (!IsNeedLogin)
            {
                if (_1688CookieList.Any(c => c.UserName == userName&&!c.IsExpire))
                {
                    return JsonConvert.SerializeObject(_1688CookieList.FirstOrDefault(c => c.UserName == userName));
                }
            }

            Task.Factory.StartNew(() =>
            {

                try
                {
                    //检查是否跨线程

                    if (!App.Current.Dispatcher.CheckAccess())
                    {
                        App.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            var loginWindow = new NewLogin1688Window(userName, password);
                            loginWindow.ShowDialog();
                            var newCookie = loginWindow.downCookies;


                            if (!string.IsNullOrEmpty(newCookie))
                                //更新或者添加
                                if (_1688CookieList.Any(c => c.UserName == userName))
                                {
                                    var oldCookie = _1688CookieList.FirstOrDefault(c => c.UserName == userName);
                                    oldCookie.Cookie = newCookie;
                                }
                                else
                                {
                                    _1688CookieList.Add(new _1688CookieModel() { UserName = userName, Cookie = newCookie, Password = password, LoginTime = DateTime.Now });
                                }
                            //SaveLocalFile?.Invoke(_1688LogunPath, JsonConvert.SerializeObject(_1688CookieList));

                        }));
                    }
                    //else
                    //{
                    //    var loginWindow = new NewLogin1688Window(userName, password);
                    //    loginWindow.ShowDialog();
                    //    var newCookie = loginWindow.downCookies;
                    //    //更新或者添加
                    //    if (_1688CookieList.Any(c => c.UserName == userName))
                    //    {
                    //        var oldCookie = _1688CookieList.FirstOrDefault(c => c.UserName == userName);
                    //        oldCookie.Cookie = newCookie;
                    //    }
                    //    else
                    //    {
                    //        _1688CookieList.Add(new _1688CookieModel() { UserName = userName, Cookie = newCookie });
                    //    }
                    //    cookie = loginWindow.downCookies;

                    //}
                }
                catch (Exception ex)
                {
                }
            });

            return null;
        }
        //public Action<string ,string> SaveLocalFile { get; set; }
        //public const string _1688LogunPath = "1688LoginCookies";

        public void  SetCookieExpire(string userName)
        {
            if (_1688CookieList.Any(c => c.UserName == userName))
            {
                var oldCookie = _1688CookieList.FirstOrDefault(c => c.UserName == userName);
                oldCookie.IsExpire = true;
                //SaveLocalFile?.Invoke(_1688LogunPath, JsonConvert.SerializeObject(_1688CookieList));
            }
        }
        /*
        public string CreatePurchaseOrderByWeb(string orderProductListJson, string adress, int _orderModel, string remark, string userName, string password)
        {

            OrderModel orderModel = (OrderModel)_orderModel;
            List<OrderProduct> models = JsonConvert.DeserializeObject<List<OrderProduct>>(orderProductListJson);


            List<OrderProduct> distinModels = new List<OrderProduct>();
            //合并相同的sku商品 叠加数量
            foreach (var item in models)
            {

                //判断是否存在
                if (distinModels.Any(m => m.SkuId == item.SkuId && m.SpectId == item.SpectId && m.ProductId == item.ProductId))
                {
                    var oldModel = distinModels.FirstOrDefault(m => m.SkuId == item.SkuId);
                    oldModel.Quantity += item.Quantity;
                }
                else
                {
                    distinModels.Add(item);
                }


            }


            models = distinModels;




            string cookie = "";

            if (_1688CookieList.Any(c => c.UserName == userName))
            {
                var oldCookie = _1688CookieList.FirstOrDefault(c => c.UserName == userName);
                cookie = oldCookie.Cookie;
            }
            else
            {
                Login1688(userName, password, true);

                return JsonConvert.SerializeObject(new ApiResponse<string>
                {
                    Code = 1000,
                    Msg = "登录失效,请重新登陆后下单",

                });
            }
            Collect1688Helper collect1688Helper = new Collect1688Helper(cookie);

            var prewOrder = collect1688Helper.PrewOrder(models, adress, orderModel);
            if (prewOrder == null)
            {
                Login1688(userName, password, true);
                return JsonConvert.SerializeObject(new ApiResponse<string>
                {
                    Code = 1000,
                    Msg = "登录失效,正在重新登陆,登录后点击下单!",
                });
            }
            return JsonConvert.SerializeObject(collect1688Helper.CommitOrder(prewOrder, remark));

        }
        public async Task<string> CreatePurchaseOrderByWeb_olf(string orderProductListJson, string adress, int _orderModel, string remark, string userName, string password)
        {

            OrderModel orderModel = (OrderModel)_orderModel;
            List<OrderProduct> models = JsonConvert.DeserializeObject<List<OrderProduct>>(orderProductListJson);

            string cookie = "";

            if (_1688CookieList.Any(c => c.UserName == userName))
            {
                var oldCookie = _1688CookieList.FirstOrDefault(c => c.UserName == userName);
                cookie = oldCookie.Cookie;
            }
            else
            {
                Login1688(userName, password, true);

                return JsonConvert.SerializeObject(new ApiResponse<string>
                {
                    Code = 1000,
                    Msg = "登录失效,请重新登陆后下单",

                });
            }


            return await Task.Factory.StartNew<string>(() =>
            {
                Collect1688Helper collect1688Helper = new Collect1688Helper(cookie);

                var prewOrder = collect1688Helper.PrewOrder(models, adress, orderModel);
                if (prewOrder == null)
                {
                    return JsonConvert.SerializeObject(new ApiResponse<string>
                    {
                        Code = 1000,
                        Msg = "预览订单失败,登录失效",
                    });
                }
                return JsonConvert.SerializeObject(collect1688Helper.CommitOrder(prewOrder, remark));
            });
        }
        */
        #endregion
    }
}