//go:build windows

package main

import (
	"errors"
	"fmt"
	"syscall"
	"unsafe"

	"go.uber.org/zap"
)

const (
	mbIconError       = 0x10
	mbIconInformation = 0x40
)

var (
	user32          = syscall.NewLazyDLL("user32.dll")
	procMessageBoxW = user32.NewProc("MessageBoxW")
	callMessageBoxW = func(hwnd, text, caption, flags uintptr) (uintptr, error) {
		ret, _, err := procMessageBoxW.Call(hwnd, text, caption, flags)
		return ret, err
	}
)

func showError(title, message string) {
	if err := messageBox(title, message, mbIconError); err != nil {
		if zapLogger != nil {
			zapLogger.Warn("显示错误对话框失败", zap.Error(err))
		}
	}
}

func messageBox(title, message string, flags uint) error {
	titlePtr, err := syscall.UTF16PtrFromString(title)
	if err != nil {
		return err
	}

	messagePtr, err := syscall.UTF16PtrFromString(message)
	if err != nil {
		return err
	}

	ret, callErr := callMessageBoxW(
		0,
		uintptr(unsafe.Pointer(messagePtr)),
		uintptr(unsafe.Pointer(titlePtr)),
		uintptr(flags),
	)
	if ret != 0 {
		return nil
	}

	if callErr != nil && !errors.Is(callErr, syscall.Errno(0)) {
		return callErr
	}

	return fmt.Errorf("MessageBoxW 调用失败")
}
