<template>
  <div class="header-bar">
    <div class="header-bar__menu">
      <div v-for="(item, index) in menu" :key="index" class="header-bar__menu-item">
        <div
          v-if="!item.children || item.children.length === 0"
          @click="getItemClick(item)"
          class="header-bar__menu-item-content flex"
        >
          <img v-if="getItemIcon(item)" :src="getItemIcon(item)" class="header-bar__menu-icon" />
          <span class="header-bar__menu-name">{{ getItemName(item) }}</span>
        </div>
        <div v-else class="header-bar__submenu">
          <div
            class="header-bar__submenu-header"
            @click.stop="toggleSubmenu(index)"
          >
            <img v-if="getItemIcon(item)" :src="getItemIcon(item)" class="header-bar__menu-icon" />
            <span class="header-bar__menu-name">{{ getItemName(item) }}</span>
          </div>
          <!-- 二级菜单 -->
          <div
            class="header-bar__submenu-body"
            :class="{ 'submenu-open': submenuOpen[index] }"
          >
            <div
              v-for="(child, childIndex) in item.children"
              :key="childIndex"
              class="header-bar__submenu-item"
              @click="getItemClick(child)"
            >
              <div
                v-if="!child.children || child.children.length === 0"
                class="header-bar__submenu-item-content flex left"
              >
                <img v-if="getItemIcon(child)" :src="getItemIcon(child)" class="header-bar__menu-icon" />
                <span class="header-bar__menu-name">{{ getItemName(child) }}</span>
              </div>
              <div v-else class="header-bar__submenu-third-level">
                <div
                  class="header-bar__submenu-third-header"
                  @click.stop="toggleThirdLevel(index, childIndex)"
                >
                  <img v-if="getItemIcon(child)" :src="getItemIcon(child)" class="header-bar__menu-icon" />
                  <span class="header-bar__menu-name">{{ getItemName(child) }}</span>
                </div>
                <!-- 三级菜单 -->
                <div
                  class="header-bar__submenu-third-body"
                  :class="{ 'submenu-open': thirdLevelOpen[`${index}-${childIndex}`] }"
                >
                  <div
                    v-for="(grandChild, grandChildIndex) in child.children"
                    :key="grandChildIndex"
                    class="header-bar__submenu-third-item"
                    @click="getItemClick(grandChild)"
                  >
                    <img v-if="getItemIcon(grandChild)" :src="getItemIcon(grandChild)" class="header-bar__menu-icon" />
                    <span class="header-bar__menu-name">{{ getItemName(grandChild) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="header-bar__title">
      <span class="header-bar__text">
        <slot name="title">{{ title }}</slot>
      </span>
    </div>
    <div class="header-bar__buttons">
      <!-- 版本信息 - 始终显示 -->
      <div class="header-bar__button header-bar__button__version">
        <span class="version-text" @click="openOTA" title="点击查看版本详情">
          当前版本：{{ currentVersion }}
        </span>
      </div>
      <!-- 用户信息 - 仅在需要时显示 -->
      <div class="header-bar__button header-bar__button__user" v-if="showUser">
        <el-dropdown>
          <span class="el-dropdown-link">
            {{ useUserInfoStore.userInfo.account_name || useUserInfoStore.userInfo.real_name || useUserInfoStore.userInfo.login_name }}
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="loginOut">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
  <div class="header-bar_blank"></div>
</template>

<script setup lang="ts">
import {defineProps, reactive, onMounted, onUnmounted, ref} from 'vue'
import useUserInfo from '@/stores/modules/user'
import { useRouter } from 'vue-router'
import iconsz from './assets/shezhi@2x.png'
import iconykq from './assets/yaokong@2x.png'
import gengxin from './assets/gengxin.svg'
import icpList from '@/utils/ipc'
import { getRouterUrl } from '@/utils/appfun'
import client from '@/stores/modules/client'
import packageJson from '@/../../package.json';

const clientStore = client()
const useUserInfoStore = useUserInfo()

const currentVersion = ref(packageJson.version);
// 定义 menu 项的类型
interface MenuItem {
  name?: string //名称
  icon?: string // 图标
  click?: () => void // 点击事件
  type?: keyof typeof menuType // 类型 menuType里面的值
  children?: MenuItem[] // 支持嵌套菜单
}

// 定义 props
const props = defineProps({
  title: {
    type: String,
    required: true
  },
  menu: {
    type: Array as () => MenuItem[],
    default: () => []
  },
  showUser: {
    type: Boolean,
    default: false
  }
})

const Router = useRouter()

const submenuOpen = reactive<{ [key: number]: boolean }>({})
const thirdLevelOpen = reactive<{ [key: string]: boolean }>({})

const toggleSubmenu = (index: number) => {
  submenuOpen[index] = !submenuOpen[index]
}

const toggleThirdLevel = (parentIndex: number, childIndex: number) => {
  const key = `${parentIndex}-${childIndex}`
  thirdLevelOpen[key] = !thirdLevelOpen[key]
}

const menuType = reactive({
  setting: {
    name: '设置',
    icon: iconsz,
    click: openSetting
  },
  remoteControl: {
    name: '模拟遥控器',
    icon: iconykq,
    click: openRemoteControl
  },
  developer: {
    name: '初始设备调频设置',
    icon: iconsz,
    click: openDeveloper
  },
  ota: {
    name: '当前版本：'+currentVersion.value,
    click: openOTA
  }
})

function getItemClick(item: MenuItem) {
  const menuItem = item.type ? { ...menuType[item.type], ...item } : item
  if (menuItem && menuItem.click) {
    menuItem.click()
  }

  // 关闭所有展开的一级和三级菜单
  for (const key in submenuOpen) {
    submenuOpen[key] = false
  }
  for (const key in thirdLevelOpen) {
    thirdLevelOpen[key] = false
  }
}
function getItemName(item: MenuItem) {
  const menuItem = item.type ? { ...menuType[item.type], ...item } : item
  return menuItem.name
}

function getItemIcon(item: MenuItem) {
  const menuItem = item.type ? { ...menuType[item.type], ...item } : item
  return menuItem.icon
}

function openSetting() {
  const { href } = Router.resolve({
    name: 'setting',
    query: {
      type: 0
    }
  })

  clientStore.ipc.removeAllListeners(icpList.utils.openMain)
  let params = {
    title: '设置',
    width: 3840,
    height: 2160,
    frame: true,
    id: 'seeting',
    url: getRouterUrl(href)
  }
  clientStore.ipc.send(icpList.utils.openMain, params)
}

function openRemoteControl() {
  const { href } = Router.resolve({
    name: 'RemoteControl'
  })

  clientStore.ipc.removeAllListeners(icpList.utils.openMain)
  let params = {
    title: '模拟遥控器',
    width: 350,
    height: 600,
    frame: true,
    id: 'RemoteControl',
    url: getRouterUrl(href)
  }
  clientStore.ipc.send(icpList.utils.openMain, params)
}

function openDeveloper() {
  const { href } = Router.resolve({
    name: 'developer'
  })

  clientStore.ipc.removeAllListeners(icpList.utils.openMain)
  let params = {
    title: '初始设备调频设置',
    width: 900,
    height: 700,
    frame: true,
    id: 'developer',
    url: getRouterUrl(href)
  }
  clientStore.ipc.send(icpList.utils.openMain, params)
}

function openOTA() {
  const { href } = Router.resolve({
    name: 'ota'
  })

  clientStore.ipc.removeAllListeners(icpList.utils.openMain)
  let params = {
    title: '版本更新',
    width: 900,
    height: 700,
    frame: true,
    id: 'ota',
    url: getRouterUrl(href)
  }
  clientStore.ipc.send(icpList.utils.openMain, params)
}

function loginOut() {
  useUserInfoStore.loginOut()
  useUserInfoStore.updateLoginShow(true)
}

onMounted(() => {
  document.addEventListener('click', handleOutsideClick)
})

onUnmounted(() => {
  document.removeEventListener('click', handleOutsideClick)
})

function handleOutsideClick(event: MouseEvent) {
  const menuElement = document.querySelector('.header-bar__menu')
  if (menuElement && !menuElement.contains(event.target as Node)) {
    // 关闭所有一级菜单
    for (const key in submenuOpen) {
      submenuOpen[key] = false
    }
    // 关闭所有三级菜单
    for (const key in thirdLevelOpen) {
      thirdLevelOpen[key] = false
    }
  }
}
</script>

<style lang="scss" scoped>
.header-bar_blank {
  width: 100%;
  height: 30px;
}

.header-bar {
  position: fixed;
  app-drag: drag;
  -webkit-app-region: drag;
  top: 0;
  width: 100%;
  height: 30px;
  z-index: 100000;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
}

.header-bar__menu {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
}

.header-bar__menu-item {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2px 10px;
  min-height: 30px;
  cursor: pointer;

  &:hover {
    background: #dcdcdc;
  }
}

.header-bar__menu-icon {
  width: 16px;
  height: 16px;
  margin-right: 5px;
}

.header-bar__menu-name {
  font-size: 14px;
}

.header-bar__title {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  height: 30px;
  line-height: 30px;
  align-items: center;
  justify-content: center;
}

.header-bar__logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.header-bar__text {
  font-weight: 600;
  font-size: 14px;
  color: #474747;
}

.header-bar__buttons {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  align-items: center;
}

.header-bar__button {
  min-width: 30px;
  height: 30px;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-bar__button__user {
  padding: 0 10px;
}

.header-bar__button__version {
  padding: 0 8px;
  margin-right: 5px;
}

.version-text {
  font-size: 12px;
  color: #666;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 3px;
  transition: all 0.2s ease;
}

.header-bar__button:hover {
  background-color: #e0e0e0;
}

.header-bar__button-icon {
  width: 16px;
  height: 16px;
}

.header-bar__submenu {
  position: relative;
  display: flex;
  flex-direction: column;
}

.header-bar__submenu-header {
  display: flex;
  align-items: center;
  padding: 2px 10px;
  cursor: pointer;
}

.header-bar__submenu-body {
  position: absolute;
  top: 100%;
  left: 0;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 160px;
  border-radius: 4px;
  overflow: hidden;
  display: none;
  margin-top: 5px;

  &.submenu-open {
    display: block;
  }
}

.header-bar__submenu-item {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  white-space: nowrap;

  &:hover {
    background-color: #f0f0f0;
  }
}

.header-bar__submenu-third-level {
  position: relative;
  display: flex;
  flex-direction: column;
}

.header-bar__submenu-third-header {
  display: flex;
  align-items: center;
  cursor: pointer;

  &:hover {
    background-color: #f0f0f0;
  }
}

.header-bar__submenu-third-body {
  position: fixed;
  margin-left: 150px;
  top: 0;
  left: 100%;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 160px;
  border-radius: 4px;
  overflow: hidden;
  display: none;

  &.submenu-open {
    display: block;
  }
}
</style>
