<script setup lang="ts">
import { ref, onMounted } from 'vue'
import ContextMenu from '@imengyu/vue3-context-menu'
import { HtmlUtils } from '@imengyu/imengyu-utils'
import { AppItem } from '../model/App'
import AppList from '../components/AppList.vue'
import AppListItem from '../components/AppListItem.vue'
import UpdateStatus from '../components/UpdateStatus.vue'
import { APP_TITLE_KEY, DEFAULT_TITLE } from '../composeable/AppTitle.ts'

// 状态管理
const apps = ref<Record<string, AppItem[]>>({})
const selectedApp = ref<AppItem | null>(null)
const isFullScreen = ref(false)
const isLoading = ref(false)
const currentAspectRatio = ref('')
const isLeftPanelOpen = ref(true)
const menuBtn = ref<HTMLButtonElement>()

// 切换左侧面板
function toggleLeftPanel() {
  isLeftPanelOpen.value = !isLeftPanelOpen.value
  window.electronAPI.toggleChildSide(isLeftPanelOpen.value)
}

// 从本地加载应用数据
async function loadApps() {
  try {
    const data = await window.electronAPI.loadAppsJson()
    if (Array.isArray(data)) {
      apps.value = {
        "未分组": data as AppItem[]
      };
    } else {
      apps.value = data
    }
    let id = 0;
    for (const group in apps.value) {
      for (const app of apps.value[group])
        app.id = ++id;
    }
  } catch (error) {
    console.error('Failed to load apps:', error)
  }
}

// 选择应用
function selectApp(app: AppItem) {

  isLoading.value = true
  //if (app.openType === 'window') {
  //  window.electronAPI.openWindow(app.url)
  //} else {
    selectedApp.value = app

    function parseAspectRatio(aspectRatio: string) {
      if (aspectRatio && aspectRatio.includes('/')) {
        const [width, height] = aspectRatio.split('/').map(Number)
        if (width > 0 && height > 0) {
          currentAspectRatio.value = `${width} : ${height}`
          return width / height
        }
      }
      return 0
    }

    document.title = app.title;
    window.electronAPI.loadChildUrl(app.url, app.keepScreenSize ? (
      parseAspectRatio(app.aspectRatio || '16:9')
    ) : 0, app.inputPassword ? {
      username: app.inputPassword.username,
      password: app.inputPassword.password,
    } : undefined)
  //}
  setTimeout(() => {
    isLoading.value = false
  }, 2000);
}

// 打开应用
function openInSystem(app: AppItem) {
  window.electronAPI.openInSystem(app.url)
}

// 刷新应用
function refreshApp(app: AppItem) {
  if (app.id === selectedApp.value?.id) {
    selectApp(app)
  } else {
    window.electronAPI.refresh()
  }
}

// 退出应用
function exitApp() {
  window.electronAPI.exit()
}
// 切换全屏
function toggleFullScreen() {
  isFullScreen.value = !isFullScreen.value
  window.electronAPI.toggleFullScreen(isFullScreen.value)
}
// 切换开发者工具
function toggleDevTools() {
  window.electronAPI.toggleDevTools()
}
// 显示配置窗口
function showConfig() {
  window.electronAPI.showConfig()
}
// 显示关于窗口
function showAbout() {
  window.electronAPI.showAbout()
}
// 清除缓存
async function clearCache() {
  await window.electronAPI.clearCache()
}
// 显示菜单
function showMenu() {
  if (ContextMenu.isAnyContextMenuOpen())
    return
  ContextMenu.showContextMenu({
    x: HtmlUtils.getLeft(menuBtn.value!) + menuBtn.value!.offsetWidth,
    y: HtmlUtils.getTop(menuBtn.value!) + menuBtn.value!.offsetHeight + 8,
    direction: 'bl',
    items: [
      {
        label: '清除缓存',
        onClick: clearCache,
      },
      {
        label: '列表配置',
        onClick: showConfig,
      },
      {
        label: '全屏',
        shortcut: 'F11',
        onClick: toggleFullScreen,
      },
      {
        label: '开发者工具',
        shortcut: 'F12',
        onClick: toggleDevTools,
      },
      {
        label: '检查更新',
        divided: 'up',
        onClick: () => window.ipcRenderer.send('updater-check'),
      },
      {
        label: '关于',
        onClick: showAbout,
      },
      {
        label: '退出',
        shortcut: 'Alt+F4',
        onClick: exitApp,
      },
    ],
  })
}


// 初始化加载数据
onMounted(() => {
  document.title = localStorage.getItem(APP_TITLE_KEY) || DEFAULT_TITLE
  loadApps()
  window.ipcRenderer.on('main-side-state-changed', (_event, isOpen) => {
    isLeftPanelOpen.value = isOpen
  });
  window.ipcRenderer.on('main-config-changed', (_event) => {
    loadApps();
  });

})
</script>

<template>
  <div class="app-container">
    <!-- 左侧应用列表 -->
    <div v-if="isLeftPanelOpen" class="left-panel">
      <h2 class="panel-title">
        <div>
          <img src="/icon.svg" alt="应用" />
          应用列表
        </div>
        <button ref="menuBtn" class="control-btn" @click="showMenu">
          <img src="../assets/menu.svg" alt="菜单" />
        </button>
      </h2>
      <UpdateStatus />
      <AppList>
        <div v-for="(group, title) in apps" :key="title">
          <h5>{{ title }}</h5>
          <AppListItem 
            v-for="app in group" 
            :key="app.id"
            :app="app"
            :activeAppId="selectedApp?.id"
            @selectApp="selectApp(app)"
            @openInSystem="openInSystem(app)"
            @refreshApp="refreshApp(app)"
          />
        </div>
      </AppList>
      <!-- 底部控制按钮 -->
      <div class="bottom-panel">
        <button class="control-btn" @click="toggleLeftPanel">
          <img src="../assets/left.svg" alt="折叠" />
        </button>
      </div>
    </div>
    <!-- 右侧iframe区域 -->
    <div class="right-panel">
      <div v-if="currentAspectRatio" class="aspect-ratio-info">
        显示比例：{{ currentAspectRatio }}
      </div>
    </div>
  </div>
</template>

<style lang="scss">
@use '../assets/colors.scss' as *;

.app-container {
  display: flex;
  flex-direction: row;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  font-family: Arial, sans-serif;
  color: $text-color;
  background-color: #000;

  // 左侧面板
  .left-panel {
    position: relative;
    width: $panel-width;
    background: $bg-light;
    display: flex;
    flex-direction: column;
    border-right: 1px solid $bg-lighter;
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;

    .panel-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      padding: 20px;
      margin: 0;
      font-size: 18px;
      color: $primary-color;
      font-weight: bold;

      > div {
        display: flex;
        flex-direction: row;
        align-items: center;
        align-content: center;

        img {
          width: 28px;
          height: 28px;
          margin-right: 8px;
        }
      }
    }
  }

  // 右侧面板
  .right-panel {
    position: relative;
    flex: 1;
    padding: 0;

    .aspect-ratio-info {
      position: absolute;
      right: 10px;
      top: 10px;

      padding: 10px;
      font-size: 14px;
      border-radius: 5px;
      color: $text-color;
      background-color: $bg-light;
    }
  }

  // 底部面板
  .bottom-panel {
    flex-shrink: 0;
    padding: 15px;
    display: flex;
    justify-content: flex-start;
    gap: 10px;
  }
}

.control-btn {
  position: relative;
  padding: 10px;
  border: none;;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s ease;
  color: #000;
  border-radius: 6px;
  background-color: transparent;
  background-color: #efefef;

  img {
    width: 16px;
    height: 16px;
  }

  &:hover {
    background-color: #ddd;
  }
}
</style>
