using BBWY.Common.Models;
using QYDongDongTool;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace BBWY.Client.Helpers
{
    public class DongDongHelper : IDenpendency
    {
        private CSharpAPIs csapi;
        private System.Timers.Timer inJectionTimer;
        public DongDongHelper()
        {
            csapi = new CSharpAPIs();
            inJectionTimer = new System.Timers.Timer(20000);
            inJectionTimer.Elapsed += InJectionTimer_Elapsed;
        }

        private void InJectionTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
           InJection();
        }

        private void InJection()
        {
            try
            {
                ProcessStartInfo p = new ProcessStartInfo();
                //p.UseShellExecute = true;
                p.CreateNoWindow = true;
                p.FileName= Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "InJectionDongDong", "dllin.exe");
                p.Verb = "runas";
                Process.Start(p);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"InJection Error, {ex.Message}");
            }
        }

        public void StartInJection()
        {
            if (!inJectionTimer.Enabled)
            {
                InJection();
                inJectionTimer.Start();
            }

        }

        /// <summary>
        /// 获取全部登录咚咚账号
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllDongdongUser()
        {
            List<string> dongdongList = new List<string>();
            var list = csapi.GetAllDesktopWindows();

            var windows = list.Where(c => c.szClassName == "DD_JM_Workbench_DLG").ToList();

            windows.ForEach(info =>
            {
                dongdongList.Add(info.szWindowName.Replace("的工作台", ""));
            });

            return dongdongList;
        }

        /// <summary>
        /// 唤醒咚咚
        /// </summary>
        /// <param name="waiterName"></param>
        /// <param name="buyerAccount"></param>
        public void WakeUpDongDong(string waiterName, string buyerAccount)
        {
            var url = $"jdworkstation://jm/?command=openDD&pin={waiterName}&client={buyerAccount}";
            try
            {
                try
                {
                    //Process.Start("explorer.exe", url);

                    ShellExecuteHelper.ShellExecute(IntPtr.Zero, "open", url, string.Empty, string.Empty, ShellExecuteHelper.ShowCommands.SW_SHOWNORMAL);
                }
                catch (Exception ex)
                {
                    Clipboard.SetText(url);
                    MessageBox.Show($"{ex.Message}\r\n唤醒咚咚失败,唤醒链接已复制到剪切板,请手动打开浏览器唤醒", "提示");
                }
            }
            catch { throw; }
        }
    }
}