<template>
  <div class="app-page">
    <div class="app-page__sidebar">
      <app-sidebar v-model:collapse="isCollapse" />
    </div>
    <div class="app-page__wrapper">
      <div class="app-page__header">
        <app-header>
          <template #left>
            <i class="icon-fold-expand" title="折叠/展开" @click="isCollapse = !isCollapse">
              <span :class="isCollapse ? 'g-icon--expand' : 'g-icon--fold'"></span>
            </i>
          </template>
        </app-header>
      </div>
      <app-tabs class="app-page__tabs" prop-label="title" :data-list="secondMenus" v-model:data-index="dataIndex"
        @change="onTabChange">
        <div id="appPageTeleport" class="app-page__main app-page__teleport"></div>
        <router-view v-slot="{ Component, route }">
          <component class="app-page__main" :is="Component" :key="route.fullPath" />
        </router-view>
      </app-tabs>
      <div class="app-page__footer">
        <app-footer />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { shallowRef, watch } from 'vue'
import { useMenu } from '@/hooks/menu'
import { globalStore } from '@/stores'
import AppTabs from '@/components/base/tabs/index.vue'
import AppHeader from '../header/index.vue'
import AppFooter from '../footer/index.vue'
import AppSidebar from '../sidebar/index.vue'

const { route, router, getChildrenMenus } = useMenu()
const isCollapse = shallowRef(globalStore.state.isMobile)
const secondMenus = shallowRef<Ermcp.UserRoutes[]>([]) // 二级菜单
const dataIndex = shallowRef(-1) // 选中的标签

// 切换标签
const onTabChange = (index: number, { code }: Ermcp.UserRoutes) => {
  router.push({ name: code })
}

watch(() => route.matched, (newMatched, oldMatched) => {
  const parentRoute = newMatched[newMatched.length - 2] // 父级路由信息
  if (parentRoute) {
    const old = oldMatched && oldMatched[oldMatched.length - 2]
    // 判断当前路由和上个路由是否属于同个父级路由
    if (parentRoute.name !== old?.name) {
      secondMenus.value = getChildrenMenus(parentRoute.name?.toString())
    }
    dataIndex.value = secondMenus.value.findIndex((e) => e.code === route.name)
  } else {
    secondMenus.value = []
    dataIndex.value = -1
  }
}, {
  immediate: true,
})
</script>

<style lang="less">
@import './index.less';
</style>