import { defineStore } from 'pinia';
import { ref } from 'vue';
import { ElMessage as Toast } from 'element-plus';
import { LogicalPosition, LogicalSize, Window, currentMonitor, getCurrentWindow } from '@tauri-apps/api/window';
import { MAIN_WINDOW_HEIGHT, MAIN_WINDOW_WIDTH } from '@/utils/constant';
import { isTauri } from '@tauri-apps/api/core';
/** 是否为 Tauri 环境 */
const IS_TAURI = isTauri();

export interface Rectangle {
  x: number;
  y: number;
  width: number;
  height: number;
}

export type ViewStore = ReturnType<typeof useViewStore>;
export type WindowStyle = 'mini' | 'normal';

/** 窗口大小和位置，以及屏幕可用区域的大小和位置 */
const displayWindowBounds = shallowRef<{ windowBounds: Rectangle; displayWorkArea: Rectangle } | undefined>(undefined);

/**
 * 注册全局状态相关的 store
 */
export const useViewStore = defineStore('view', () => {
  /** Tauri 窗口实例（仅在 Tauri 环境中存在） */
  let tauriWindow: Window | null = null;

  /** 需要缓存的路由名称列表 */
  const includeList = ref<string[]>([]);
  /** 是否最大化 */
  const isMaximize = ref(false);
  /** 是否锁定端口（置于最顶层） */
  const isPin = ref(false);
  /** 窗口样式 */
  const windowStyle = ref<WindowStyle>('normal');

  // 仅在 Tauri 环境下初始化
  if (IS_TAURI) {
    tauriWindow = getCurrentWindow();

    // 初始化窗口状态
    tauriWindow.isMaximized().then((isMaximized) => {
      isMaximize.value = isMaximized;
    });
    tauriWindow.isAlwaysOnTop().then((isAlwaysOnTop) => {
      isPin.value = isAlwaysOnTop;
    });
  }

  return {
    /** 是否最大化 */
    isMaximize,
    /** 需要缓存的路由名称列表 */
    includeList,
    /** 是否锁定 */
    isPin,
    /** 窗口样式 */
    windowStyle,

    /** 窗口最大化或退出最大化  */
    async toggleMximize() {
      if (!IS_TAURI || !tauriWindow) {
        Toast.warning('当前环境不支持此操作');
        return;
      }

      try {
        await tauriWindow.toggleMaximize();
        isMaximize.value = await tauriWindow.isMaximized();
      } catch (error: any) {
        Toast.error('操作失败');
        console.log('error====', error);
      }
    },

    /** 切换窗口是否锁定 */
    async togglePin() {
      if (!IS_TAURI || !tauriWindow) {
        Toast.warning('当前环境不支持此操作');
        return;
      }

      try {
        const isAlwaysOnTop = await tauriWindow.isAlwaysOnTop();
        await tauriWindow.setAlwaysOnTop(!isAlwaysOnTop);
        isPin.value = !isAlwaysOnTop;
      } catch (error: any) {
        Toast.error('操作失败');
        console.log('error====', error);
      }
    },

    /** 设置窗口是否锁定 */
    async setPin(bool: boolean) {
      if (!IS_TAURI || !tauriWindow) {
        Toast.warning('当前环境不支持此操作');
        return;
      }

      try {
        await tauriWindow.setAlwaysOnTop(bool);
        isPin.value = bool;
      } catch (error: any) {
        Toast.error('操作失败');
        console.log('error====', error);
      }
    },

    /** 改变窗口样式 */
    async setWindowStyle(_windowStyle: WindowStyle) {
      if (!IS_TAURI) {
        Toast.warning('当前环境不支持此操作');
        return;
      }
      windowStyle.value = _windowStyle;
      await setDisplayWindowBounds();
      if (windowStyle.value === 'mini') {
        const displayWorkArea = displayWindowBounds.value!.displayWorkArea;
        const width = Math.floor(displayWorkArea.width * 0.9);
        const height = Math.floor(displayWorkArea.height * 0.25);
        const currWindow = Window.getCurrent();
        currWindow.setSize(new LogicalSize(width, height));
        currWindow.setPosition(new LogicalPosition(Math.floor((displayWorkArea.width - width) / 2), displayWorkArea.height - height));
        this.setPin(true);
      } else {
        restoreWindow();
        this.setPin(false);
      }
    },
  };
});

/**
 * 设置屏幕大小和位置
 */
async function setDisplayWindowBounds() {
  if (!IS_TAURI) {
    Toast.warning('当前环境不支持此操作');
    return;
  }
  if (!displayWindowBounds.value) {
    const monitor = (await currentMonitor())!;
    /** 用于将物理像素映射到逻辑像素的缩放系数 */
    const scaleFactor = monitor.scaleFactor;
    /** 屏幕的大小 */
    const monitorSize = monitor.size.toLogical(scaleFactor);
    /** 屏幕的位置 */
    const monitorPosition = monitor.position.toLogical(scaleFactor);
    /** 屏幕的可用区域的大小 */
    const workAreaSize = monitor.workArea.size.toLogical(scaleFactor);
    /** 屏幕的可用区域的位置 */
    const workAreaPosition = monitor.workArea.position.toLogical(scaleFactor);
    const windowBounds = { x: monitorPosition.x, y: monitorPosition.y, width: monitorSize.width, height: monitorSize.height };
    const displayWorkArea = { x: workAreaPosition.x, y: workAreaPosition.y, width: workAreaSize.width, height: workAreaSize.height };
    displayWindowBounds.value = { windowBounds, displayWorkArea };
  }
}

/**
 * 恢复窗口
 */
function restoreWindow() {
  if (!IS_TAURI) {
    Toast.warning('当前环境不支持此操作');
    return;
  }
  if (!displayWindowBounds.value) {
    return;
  }
  const displayWorkArea = displayWindowBounds.value.displayWorkArea;
  const currWindow = Window.getCurrent();
  currWindow.setSize(new LogicalSize(MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT));
  currWindow.setPosition(
    new LogicalPosition(Math.floor((displayWorkArea.width - MAIN_WINDOW_WIDTH) / 2), Math.floor((displayWorkArea.height - MAIN_WINDOW_HEIGHT) / 2))
  );
}
