using BBWY.Client.Models;
using BBWY.Client.ViewModels;
using BBWY.Common.Extensions;
using BBWY.Common.Http;
using BBWY.Common.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using QuanTan.SDK.Client;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Utils;

namespace BBWY.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; }

        public bool IsAdministrator()
        {
            WindowsIdentity current = WindowsIdentity.GetCurrent();
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
            return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            var isAdmin = IsAdministrator();
            Console.WriteLine($"run as admin : {isAdmin}");

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var gl = new GlobalContext();
            string userToken = string.Empty;
#if DEBUG
            //齐越山鸡
            userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNTM1MzMwMzI4ODkyMTQ5NzYwIiwidGVhbUlkIjoiMTUxNjk3NDI1MDU0MjUwMTg4OCIsInNvblRlYW1JZHMiOiIxNDM2Mjg4NTAwMjM1MjQzNTIwIiwiZXhwIjoxNjk0NjY5NjkxfQ.cSwro-7bGwOu92YejH9JhMenTai7Mvf99i2paQCmxIw";

            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNTIwOTc1NzQ0MTY2MDA2Nzg0IiwidGVhbUlkIjoiMTQzNjI4ODUwMDIzNTI0MzUyMCIsInNvblRlYW1JZHMiOiIiLCJleHAiOjE3MDkyNzQ3NzZ9.2aAkMNeDPHUZ3q0K83Usp7QNhPMkBNW8uWxknJZ49oE";

            //刷单组测试
            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNTcxODUyODE0OTAzMTUyNjQwIiwidGVhbUlkIjoiMTU3MTg1MjQ1MDI5NjUwMDIyNCIsInNvblRlYW1JZHMiOiIiLCJleHAiOjE2OTUxNDc2ODh9.hVupdHnhgHHGo3QrMSDqhINqtq6Q5_RovWyXjiMkkEs";
            //齐越愉辰
            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNDM5OTEyNDU1MzExNDYyNDAwIiwidGVhbUlkIjoiMTQzOTg5ODYxNzM1ODg0ODAwMCIsInNvblRlYW1JZHMiOiIiLCJleHAiOjE2OTUwNDA0ODZ9.0TvEhPzTeKvpQY31E5YhgfvRBJHYdvwWRrEHNnF9kkA";
            //齐越悠仁
            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNDM5OTEyMzAxODIwOTA3NTIwIiwidGVhbUlkIjoiMTQzOTg5ODU5MzE3MDI5NjgzMiIsInNvblRlYW1JZHMiOiIiLCJleHAiOjE2OTQ4NjU2NjR9.yQlRKUnnXl4cEzvqRwd-BSktGuW6-AAHLuCicp7f-EM";
            //齐越小戴
            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNDM5OTEyNjg0MDk4MTYyNjg4IiwidGVhbUlkIjoiMTQzOTg5ODY0MDU0OTE1NDgxNiIsInNvblRlYW1JZHMiOiIiLCJleHAiOjE2OTQ0OTQ1MDZ9.LxA_vc_YyXxgQjSQi4XVg2B-fdvAz3mIT0Bgg3Uuul8";
            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNDE1OTMxMjU4NjEzMDEwNDMyIiwidGVhbUlkIjoiMTQxNDkzNTcwNDQ2MjQzMDIwOCIsInNvblRlYW1JZHMiOiIiLCJleHAiOjE2OTQxMDY1MjV9.XeMruS0YkwI7B6nODGe-vbdUqA_PSAt4EacfRAHIjV0"; //齐越文魁
            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNDA1MTUxNjE5NTk0NTg4MTYwIiwidGVhbUlkIjoiMTQxMDk1NTYwNDYxMjA5MTkwNCIsImV4cCI6MTY4NjQ4MjU0M30.emnQNDcbqnuO2jH0Kgfk2Ui7crrwzRb986Sa511iS-U";  //齐越小一

            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNTczOTQ5NTkzMjcwMzU4MDE2IiwidGVhbUlkIjoiMTU3MTg1MjQ1MDI5NjUwMDIyNCIsInNvblRlYW1JZHMiOiIxNTcxODUyNDUwMjk2NTAwMjI0IiwiZXhwIjoxNjk2NzgwMjg5fQ.RgZ7byOeHpAHKIOM8q57gLIPNrtCDfLIV_dFD8ta-uk";  //齐越繁星兼

            //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNDM5OTE0NjczMzA5NzQ5MjQ4IiwidGVhbUlkIjoiMTQ0ODY4MTU0NDE4ODE3MDI0MCIsImV4cCI6MTY4NjQ1OTY0Mn0.4yCbZxOtogD0N868-YgySR5A-16VNnrp8fC13VCRs20"; //齐越耐克

#else
            //var uid = e.Args.Count() > 0 ? e.Args.LastOrDefault(args => args.StartsWith("uid:")) : string.Empty;
            //if (string.IsNullOrEmpty(uid))
            //{
            //    MessageBox.Show("缺少启动参数", "提示");
            //    Environment.Exit(0);
            //}
            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("BBWYAppSettings.json", false, true);
            Configuration = builder.Build();
            gl.BBYWApiHost = Configuration.GetSection("BBWYApiHost").Value;
            gl.MDSApiHost = Configuration.GetSection("MDSApiHost").Value;
            gl.JOSApiHost = Configuration.GetSection("JOSApiHost").Value;
            gl._1688ApiHost = Configuration.GetSection("1688ApiHost").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("BBWY.Client") }, typeof(IDenpendency));
            serviceCollection.AddMapper(new MappingProfile());

            serviceCollection.AddTransient<_1688PreviewPurchaseViewModel>();

            #region 注册拳探SDK相关类
            serviceCollection.AddSingleton<QuanTanProductClient>();
            #endregion

            ServiceProvider = serviceCollection.BuildServiceProvider();

            #region 启动本机WebSocket服务
            {
                var wssExeList = Process.GetProcessesByName("BBWY.WebSocket.Server");
                if (wssExeList == null || wssExeList.Count() == 0)
                {
                    try
                    {
                        ProcessStartInfo p = new ProcessStartInfo();
                        p.CreateNoWindow = true;
                        p.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "BBWY.WebSocket.Server.exe");
                        p.Verb = "runas";
                        Process.Start(p);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "启动bbwy websocket服务");
                    }
                }
            }
            #endregion

            base.OnStartup(e);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            using (var s = ServiceProvider.CreateScope())
            {
                var wb2m = s.ServiceProvider.GetRequiredService<WebView2Manager>();
                wb2m.Close();
            }
            base.OnExit(e);
        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            Console.WriteLine(e.Exception);
            e.SetObserved();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Console.WriteLine(e.Exception);
        }

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

            try
            {
                var token = MemoryHelper.GetMemoryToken();
                if (string.IsNullOrEmpty(token))
                    return (false, "token为空");
                else
                    return (true, token);
                //using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mapname))
                //{
                //    using (var mmfStream = mmf.CreateViewStream(0, 1000, MemoryMappedFileAccess.ReadWrite))
                //    {
                //        StreamReader reader = new StreamReader(mmfStream);
                //        string jwt = reader.ReadToEnd().Replace("\0", "").TrimEnd();
                //        return (true, jwt);
                //    }
                //}
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }
    }
}