using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace CCDCount.DLL.Tools
{
    public static class OnScreenKeyboard
    {
        [DllImport("kernel32.dll")]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private const int SW_SHOW = 5;
        private const int SW_HIDE = 0;
        /// <summary>
        /// 启动软键盘（兼容Windows 10及以上版本）
        /// </summary>
        public static void KeyBoardShow()
        {
            try
            {
                // 检查是否为Windows 10或更高版本
                if (IsWindows10OrHigher())
                {
                    // 尝试启动TabTip
                    if (TryStartTabTip())
                        return;
                }

                // 回退到传统osk
                StartOnScreenKeyboard();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("无法启动软键盘", ex);
            }
        }

        /// <summary>
        /// 隐藏软键盘
        /// </summary>
        public static void KeyBoardHide()
        {
            try
            {
                // 隐藏TabTip窗口
                IntPtr tabTipHwnd = FindWindow("IPTip_Main_Window", null);
                if (tabTipHwnd != IntPtr.Zero)
                {
                    ShowWindow(tabTipHwnd, SW_HIDE);
                }

                // 隐藏OSK窗口
                IntPtr oskHwnd = FindWindow("OSKMainClass", "屏幕键盘");
                if (oskHwnd != IntPtr.Zero)
                {
                    ShowWindow(oskHwnd, SW_HIDE);
                }
            }
            catch
            {
                // 忽略异常
            }
        }

        private static void StartOnScreenKeyboard()
        {
            try
            {
                // 检查是否已经运行
                Process[] oskProcesses = Process.GetProcessesByName("osk");
                if (oskProcesses.Length > 0)
                {
                    // 如果已经运行，尝试显示窗口
                    IntPtr oskHwnd = FindWindow("OSKMainClass", "屏幕键盘");
                    if (oskHwnd != IntPtr.Zero)
                    {
                        ShowWindow(oskHwnd, SW_SHOW);
                        return;
                    }
                    else
                    {
                        // 如果找不到窗口，杀死进程重新启动
                        foreach (var process in oskProcesses)
                        {
                            try { process.Kill(); } catch { }
                        }
                    }
                }

                Process.Start("osk.exe");
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("无法启动屏幕键盘", ex);
            }
        }

        private static bool IsWindows10OrHigher()
        {
            var os = Environment.OSVersion;
            if (os.Version.Major >= 10)
                return true;

            try
            {
                using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
                {
                    var currentBuild = key?.GetValue("CurrentBuild")?.ToString();
                    if (int.TryParse(currentBuild, out int buildNumber))
                    {
                        // Windows 10 build 10240及以上
                        return buildNumber >= 10240;
                    }
                }
            }
            catch
            {
                // 忽略异常
            }

            // 兼容性检查：Windows 8.1及以后版本的Major是6，但Minor版本不同
            return os.Version.Major == 10 || (os.Version.Major == 6 && os.Version.Minor >= 2);
        }

        private static bool TryStartTabTip()
        {
            try
            {
                // 检查是否已经运行
                Process[] tabTipProcesses = Process.GetProcessesByName("TabTip");
                if (tabTipProcesses.Length > 0)
                {
                    // 如果找不到窗口，杀死进程重新启动
                    foreach (var process in tabTipProcesses)
                    {
                        try { process.Kill(); } catch { }
                    }
                }

                // 方法1：通过注册表查找路径
                string tabTipPath = GetTabTipPathFromRegistry();
                if (!string.IsNullOrEmpty(tabTipPath) && File.Exists(tabTipPath))
                {
                    Process.Start(tabTipPath);
                    return true;
                }

                // 方法2：通过系统路径查找
                string systemPath = Path.Combine(Environment.SystemDirectory, "TabTip.exe");
                if (File.Exists(systemPath))
                {
                    Process.Start(systemPath);
                    return true;
                }

                // 方法3：使用modern Windows 10路径
                string modernPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
                    @"TabletTip\1.7\TabTip.exe");
                if (File.Exists(modernPath))
                {
                    Process.Start(modernPath);
                    return true;
                }

                // 方法4：使用默认路径
                string defaultPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
                if (File.Exists(defaultPath))
                {
                    Process.Start(defaultPath);
                    return true;
                }
            }
            catch (Exception ex)
            {
                // 记录异常但不中断
                System.Diagnostics.Debug.WriteLine($"启动TabTip失败: {ex.Message}");
            }

            return false;
        }

        private static string GetTabTipPathFromRegistry()
        {
            try
            {
                using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\InboxApplications"))
                {
                    if (key != null)
                    {
                        foreach (var subKeyName in key.GetSubKeyNames())
                        {
                            if (subKeyName.Contains("Microsoft.Windows.Keyboard"))
                            {
                                using (var subKey = key.OpenSubKey(subKeyName))
                                {
                                    var installPath = subKey?.GetValue("Path")?.ToString();
                                    if (!string.IsNullOrEmpty(installPath))
                                    {
                                        string tabTipPath = Path.Combine(installPath, "TabTip.exe");
                                        if (File.Exists(tabTipPath))
                                            return tabTipPath;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                // 忽略注册表访问异常
            }

            return null;
        }
    }
}
