<script setup lang="ts">

import {ElRow} from "element-plus";
import {computed, onMounted, ref, watch} from "vue";
import {tabsStore} from '@/stores/tabs.ts'
import {menuStore} from "@/stores/menu.ts";
import router from "@/router";
import MessageUtils from "@/utils/MessageUtils.ts";
import StringUtils from "@/utils/StringUtils.ts";
import {useI18n} from "vue-i18n";

const appTabsInstance = tabsStore();
const menuStoreInstance = menuStore();
const { t } = useI18n();
let appTabs = computed(() => appTabsInstance.appTabs);
let selectedTab = computed({
  get() {
    return appTabsInstance.selectTab;
  },
  set(tab) {
    appTabsInstance.selectTab = tab;
  }
});

let selectMenu = computed({
  get() {
    return menuStoreInstance.selectMenu;
  },
  set(newVal) {
    menuStoreInstance.selectMenu = newVal;
  }
})


onMounted(() => {
})
watch(selectedTab, (newVal, oldValue) => {
  if(newVal == 'appHome'){
    router.push({name: 'home'});
    return;
  }
  const menuInfo = menuStoreInstance.getUserMenuWithId(newVal);
  if (menuInfo) {
    if(StringUtils.isNullOrEmpty(menuInfo.routerName)) {
      router.push({name: 'error'});
      return;
    }
    try {
      router.push({name: menuInfo.routerName});
    } catch (e) {
      router.push({name: 'error'});
    }
  } else {
    router.push({name: 'error'});
  }
})

const changeTab = (tab: string) => {
  selectMenu.value = tab;
}

const closeTab = (tab: string) => {
  appTabsInstance.removeAppTabWithTableName(tab);
  if(appTabs.value.length > 0){
    selectedTab.value = appTabs.value[appTabs.value.length - 1].tabName;
    selectMenu.value = selectedTab.value;
  } else {
    selectedTab.value = 'appHome';
    selectMenu.value = '';
  }
}

</script>

<template>
  <el-row style=" background-color: white; width: calc(100vw - 262px);height: 40px">
    <el-tabs class="tab" v-model="selectedTab" type="card" style="width: calc(100vw - 270px)" @tabChange="changeTab" @tabRemove="closeTab">
      <el-tab-pane :label="t('mainPage.homeTabName')" name="appHome">系统主页</el-tab-pane>
      <el-tab-pane v-for="item in appTabs" :label="item.tabLabel" :name="item.tabName" closable></el-tab-pane>
    </el-tabs>
  </el-row>
  <el-row style="background-color: #f8f8f8;height: calc(100vh - 85px)">
    <el-scrollbar style="height: calc(100vh - 85px)">
      <router-view v-slot="{ Component }">
        <keep-alive :max="10"><component :is="Component"/></keep-alive>
      </router-view>
    </el-scrollbar>
  </el-row>
</template>

<style scoped>
.tab :deep(.el-tabs__item).is-active {
  color: #6666cc; /* 选中时的颜色 */
  opacity: 1;
}
.tab :deep(.el-tabs__item):hover {
  color: #6666cc; /* 悬浮时的颜色 */
  cursor: pointer;
  opacity: 1;
}
</style>