using BBWYB.Client.Helpers;
using BBWYB.Client.Models;
using BBWYB.Client.ViewModels;
using BBWYB.Common.Extensions;
using BBWYB.Common.Http;
using BBWYB.Common.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace BBWYB.Client
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public IServiceProvider ServiceProvider { get; private set; }
        public IConfiguration Configuration { get; private set; }


        protected override void OnStartup(StartupEventArgs e)
        {
            var gl = new GlobalContext();
            string userToken = string.Empty;

#if DEBUG
            //齐越山鸡
            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNTM1MzMwMzI4ODkyMTQ5NzYwIiwidGVhbUlkIjoiMTUxNjk3NDI1MDU0MjUwMTg4OCIsInNvblRlYW1JZHMiOiIxNDM2Mjg4NTAwMjM1MjQzNTIwIiwiZXhwIjoxNzI2MzAwNjY0fQ.hPSbgJEuTt0MLy_7YkSJX4rRG3drJAfso-5IS8ZlOkY";

            //议价2组
            userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMzk1NzA4MjA4NjU1MzcyMjg4IiwidGVhbUlkIjoiMTYyMDM0MjAxNDcwNjk3ODgxNiIsInNvblRlYW1JZHMiOiIxNzYwOTcxNjg4OTY0NTI2MDgwIiwiZXhwIjoxNzQyNjMwODk0fQ.Vtq2MU1Qd9Oo192udkA01ZAwiQgQxj2m-pkayGZ1d3I";

            //拳探店铺 陈默
            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNjI0OTUxNjgzNTc2NTAwMjI0IiwidGVhbUlkIjoiMTYyMDM0MjAxNDcwNjk3ODgxNiIsInNvblRlYW1JZHMiOiIxNjIwMzQyMDE0NzA2OTc4ODE2LDE2MjAzNDM4Mjc0NzI1ODQ3MDQsMTYyMDM0NDAzMzczNTg3MjUxMiwxNjIwMzQ0MDkyODI5NDIxNTY4LDE2MjAzNDQxNDA4NTAwMDgwNjQiLCJleHAiOjE3MjA3NjQzMjV9.Q8fiKXCHgvzbm7NDEre-MeoSju_AmC6Ae6eDY22rUAw";
#else

            var tokenResult = ReadMMF();
            if (tokenResult.isOk)
                userToken = tokenResult.content;
            else
            {
                MessageBox.Show($"读取内存数据失败\r\n{tokenResult.content}", "提示");
                Environment.Exit(0);
            }
#endif
            gl.UserToken = userToken;

            #region 注册全局异常
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            #endregion


            var applicationPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var builder = new ConfigurationBuilder().SetBasePath(applicationPath).AddJsonFile("appsettings.json", false, true);
            Configuration = builder.Build();
            gl.BBWYApiHost = Configuration.GetSection("BBWYApiHost").Value;
            gl.BBWYCApiHost = Configuration.GetSection("BBWYCApiHost").Value;
            gl.MDSApiHost = Configuration.GetSection("MDSApiHost").Value;
            gl.QKApiHost = Configuration.GetSection("QKApiHost").Value; 

            IServiceCollection serviceCollection = new ServiceCollection();
            serviceCollection.AddHttpClient();
            serviceCollection.AddHttpClient("gzip").ConfigurePrimaryHttpMessageHandler(handler => new HttpClientHandler()
            {
                AutomaticDecompression = System.Net.DecompressionMethods.GZip
            });

            serviceCollection.AddMemoryCache();
            serviceCollection.AddSingleton<RestApiService>();
            serviceCollection.AddSingleton(gl);
            serviceCollection.BatchRegisterServices(new Assembly[] { Assembly.Load("BBWYB.Client") }, typeof(IDenpendency));
            serviceCollection.AddTransient<ChoosePurchaseSchemeViewModel>();
            serviceCollection.AddTransient<OnlinePurchaseViewModel>();
            serviceCollection.AddTransient<EditPriceViewModel>();
            serviceCollection.AddTransient<UpdatePurchaseTaskViewModel>();
            serviceCollection.AddTransient<BindingPurchaseProductViewModel>();
            serviceCollection.AddMapper(new MappingProfile());
            ServiceProvider = serviceCollection.BuildServiceProvider();
            base.OnStartup(e);
        }

        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
        
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
          
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
          
        }

        public (bool isOk, string content) ReadMMF()
        {

            try
            {
                var token = MemoryHelper.GetMemoryToken();
                if (string.IsNullOrEmpty(token))
                    return (false, "token为空");
                else
                    return (true, token);
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }
    }
}