using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using PTMedicalInsurance.Forms;

namespace PTMedicalInsurance.Business
{
    //使用 EnumWindows API 枚举所有顶层窗口，并检测目标窗体
    public class WindowMonitor
    {
        [DllImport("user32.dll")]
        private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
        private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

        private const string TargetWindowTitle = "新疆维吾尔自治区社会保障卡（电子社保卡）统一鉴权";//"安全控件 V1.0.6"; // 替换为目标窗体的标题
        private const int CheckInterval = 1000; // 检查间隔（毫秒）

        public static void Start()
        {
            Thread monitorThread = new Thread(MonitorWindows);
            monitorThread.IsBackground = true;
            monitorThread.Start();
        }

        private static void MonitorWindows()
        {
            while (true)
            {
                EnumWindows(EnumWindowsCallback, IntPtr.Zero);
                Thread.Sleep(CheckInterval);
            }
        }

        private static bool EnumWindowsCallback(IntPtr hWnd, IntPtr lParam)
        {
            StringBuilder windowTitle = new StringBuilder(256);
            GetWindowText(hWnd, windowTitle, windowTitle.Capacity);
            
                       
            if (windowTitle.ToString().Contains(TargetWindowTitle))
            {
                if (windowTitle.ToString().Contains("安全控件 V1.0.6"))
                {
                    //Thread.Sleep(3000);
                    ShowPasswordKeyboard();
                    return false; // 停止枚举
                }
            }
            return true; // 继续枚举
        }

        private static void ShowPasswordKeyboard()
        {
            //Application.Run(new PasswordKeyboardForm(IntPtr));
            PasswordKeyboardForm passwordKeyboard = new PasswordKeyboardForm();
            passwordKeyboard.ShowDialog();
        }
    }

    public class WindowCloseListener
    {
        private const int WM_CLOSE = 0x0010;
        private const int GWL_WNDPROC = -4;

        private IntPtr _targetWindowHandle;
        private IntPtr _originalWndProc;
        private WndProcDelegate _wndProcDelegate;

        public event EventHandler WindowClosed;

        public WindowCloseListener(IntPtr targetWindowHandle)
        {
            _targetWindowHandle = targetWindowHandle;
            _wndProcDelegate = new WndProcDelegate(WndProc);
        }

        public void Start()
        {
            // 替换目标窗口的窗口过程
            _originalWndProc = SetWindowLong(_targetWindowHandle, GWL_WNDPROC, Marshal.GetFunctionPointerForDelegate(_wndProcDelegate));
        }

        public void Stop()
        {
            // 恢复原始窗口过程
            SetWindowLong(_targetWindowHandle, GWL_WNDPROC, _originalWndProc);
        }

        private IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
        {
            if (msg == WM_CLOSE)
            {
                // 触发窗体关闭事件
                WindowClosed?.Invoke(this, EventArgs.Empty);
            }

            // 调用原始窗口过程
            return CallWindowProc(_originalWndProc, hWnd, msg, wParam, lParam);
        }

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        private delegate IntPtr WndProcDelegate(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
    }

}
