import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
import { type WindowLabel, windowLabel } from './windows-util';
import { invoke } from '@tauri-apps/api/core';
import { LogicalPosition, LogicalSize, currentMonitor } from '@tauri-apps/api/window';
import { ElMessage as Toast } from 'element-plus';
/**
 * 创建悬浮球窗口
 */
export async function createFloatListWindow(pageType: 'interaction' | 'tutorship') {
  try {
    await invoke('create_float_list_window', { page_type: pageType });
  } catch (error: any) {
    console.error('创建悬浮球窗口时出错:', error);
    Toast.error('悬浮球创建失败');
  }
}

/**
 * 创建主窗口
 */
export async function createMainWindow() {
  try {
    await invoke('create_main_window');
  } catch (error: any) {
    console.error('创建主窗口时出错:', error);
    Toast.error('创建主窗口失败');
  }
}

/**
 * 创建会议窗口
 * @param windowType - 窗口类型
 * @param courseId - 课程ID
 */
export async function createMeetingWindow(windowType: number, courseId?: number) {
  try {
    await invoke('create_meeting_window', { window_type: windowType, course_id: typeof courseId === 'number' ? courseId : null });
  } catch (error: any) {
    console.error('创建会议窗口时出错:', error);
    Toast.error('创建会议窗口失败');
  }
}

/**
 * 创建画板窗口
 */
export function createDrawingBoardWindow(): Promise<boolean> {
  Toast.warning('当前版本暂不支持画板窗口');
  return Promise.resolve(false);
}

/**
 * 创建实时字幕窗口
 */
export function createSubtitleWindow(): Promise<boolean> {
  Toast.warning('当前版本暂不支持实时字幕窗口');
  return Promise.resolve(false);
}

/**
 * 调整窗口位置和大小
 */
export async function moveAndResizeWindow(x: number, y: number, width: number, height: number) {
  const win = WebviewWindow.getCurrent();
  await win.setSize(new LogicalSize(width, height));

  // 获取当前显示器信息
  const _currentMonitor = await currentMonitor();
  const scaleFactor = await win.scaleFactor();

  // 如果有当前显示器信息，则将相对坐标转换为绝对坐标
  if (_currentMonitor) {
    const monitorPos = _currentMonitor.position.toLogical(scaleFactor);
    await win.setPosition(new LogicalPosition(x + monitorPos.x, y + monitorPos.y));
  } else {
    await win.setPosition(new LogicalPosition(x, y));
  }

  return Promise.resolve(true);
}

/**
 * 关闭当前窗口
 */
export async function closeCurrentWindow() {
  const win = WebviewWindow.getCurrent();
  if (win.label === windowLabel.main) {
    await win.hide();
  } else {
    await win.close();
  }
}

/**
 * 根据 label 关闭指定窗口
 */
export async function closeWindowByLabel(label: WindowLabel) {
  try {
    if (!label) {
      return;
    }
    const win = await WebviewWindow.getByLabel(label);
    if (!win) {
      return;
    }
    if (win.label === windowLabel.main) {
      await win.hide();
    } else {
      await win.close();
    }
  } catch (error) {
    console.log('关闭错误或已被关闭====', error);
  }
}

/**
 * 最小化当前窗口
 */
export async function minimizeCurrentWindow() {
  const win = WebviewWindow.getCurrent();
  await win.minimize();
}
