import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
import { currentMonitor } from '@tauri-apps/api/window';
type ValueOf<T> = T[keyof T];
export type $Placement = 'bottom' | 'center' | 'left' | 'right' | 'top';
export type WindowLabel = ValueOf<typeof windowLabel>;
/** 所有窗口的标签名 */
export const windowLabel = {
  main: 'main',
  meeting: 'meeting',
  meeting2: 'meeting2',
  floatList: 'float-list',
  popup: 'popup',
} as const;

export type TargetLocation = {
  /** 触发元素右上角的X轴坐标 */
  x: number;
  /** 触发元素右上角的Y轴坐标 */
  y: number;
  /** 触发元素宽高 */
  width: number;
  /** 触发元素宽高 */
  height: number;
};

export type PupupSize = {
  /** 弹出框的宽高 */
  width: number;
  /** 弹出框的宽高 */
  height: number;
};
export type Placement = 'auto' | 'bottom' | 'center' | 'left' | 'right' | 'top';
export type PupupLocation = {
  /** 弹出bubble的位置 */
  placement: Placement;
  /** 是浏览器窗口否足够bubble显示, true:足够显示; false:不足够(改用ElDialog方式显示) */
  enoughShow: boolean;
  /** bubble弹出框右上角的Y轴坐标 */
  y: number;
  /** bubble弹出框右上角的X轴坐标 */
  x: number;
  /** 弹出框的宽高 */
  width: number;
  /** 弹出框的宽高 */
  height: number;
};

/**
 * 获取当前窗口大小和位置
 */
export async function getWinSizeAndPosition() {
  try {
    const win = WebviewWindow.getCurrent();
    // 获取缩放因子
    const scaleFactor = await win.scaleFactor();

    // 获取当前窗口所在显示器的信息
    const monitor = await currentMonitor();

    // 获取悬浮球窗口的位置和尺寸
    const { x, y } = (await win.outerPosition()).toLogical(scaleFactor);
    const { width, height } = (await win.outerSize()).toLogical(scaleFactor);

    // 如果有当前显示器信息，则调整坐标为相对于该显示器的坐标
    if (monitor) {
      const monitorPos = monitor.position.toLogical(scaleFactor);
      return {
        x: x - monitorPos.x,
        y: y - monitorPos.y,
        width,
        height,
        monitor: {
          x: monitorPos.x,
          y: monitorPos.y,
          width: monitor.size.width,
          height: monitor.size.height,
        },
      };
    }

    return { x, y, width, height };
  } catch (error) {
    console.error('获取窗口位置和尺寸时出错:', error);
    return { x: 0, y: 0, width: 600, height: 800 };
  }
}

/**
 * 得到状态
 */
export async function getWindowIsShow(label: string) {
  try {
    const win = await WebviewWindow.getByLabel(label);
    const isVisible = await win?.isVisible();
    const isMinimized = await win?.isMinimized();
    return !(!win || !isVisible || isMinimized);
  } catch (error: any) {
    return false;
  }
}
