<template>
  <el-container class="layout">
    <!-- 固定导航栏 -->
    <el-header class="navbar">
      <div class="logo">
        <img src="~/assets/img/KEP001.svg" class="logo-img" />
        <span class="log-text">KE Platform</span>
      </div>
      <ul class="nav-links" ref="el">
        <li v-for="item in navItems" :key="item.path">
          <NuxtLink :to="item.path" :class="{ active: activeTab === item.path }">
            {{ item.name }}
          </NuxtLink>
        </li>
      </ul>
      <!-- <div class="user-info">{{ user }}</div> -->
      <div class="div-area">
        当前工区：<el-select v-model="selectedAreaData" placeholder="请选择" class="workArea">
          <el-option v-for="item in areaData" :key="item.AreaID" :label="item.AreaName" :value="item.AreaID" />
        </el-select>
        &nbsp;
        当前用户：
        <el-dropdown @command="handleUser">
          <el-button link style="font-size: 20px;" :type="userBtnType">{{ userName }}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <template v-slot:dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 内容区域 - 会根据当前路由自动变化 -->
    <el-main class="content">
      <slot />
    </el-main>
  </el-container>
</template>

<script setup>
import { useAuthStore } from "~/stores/auth";
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRoute } from "vue-router";

import { getWorkArea, setWorkArea } from "~/services/workAreaService";
import { useCurrentTabStore } from "~/stores/currentTabStore";
import { emitter } from "~/utils/eventBus";
import { STORAGE_KEYS } from "~/utils/storageKeys"
import { EMIT_COMMAND } from '~/utils/commandTypes'

const authStore = useAuthStore();
// authStore.initializeAuth();

const useTabStore = useCurrentTabStore();

const route = useRoute();
const activeTab = ref("/");

const areaData = ref(null);

const selectedAreaData = ref('');

const userName = ref('未登录');
const userBtnType = computed(() => { userName.value === '未登录' ? 'success' : 'danger' });


const navItems = ref([
  { name: "工区管理", path: "/" },
  { name: "数据管理", path: "/dataManage" },
  { name: "井位智能推荐", path: "/smartWellRecommend" },
  { name: "参数图形绘制", path: "/drawParamGdi" },
  { name: "井段数据分析", path: "/wellDataAnalysis" },
  { name: "水平井", path: "/horizontalWell" },
  { name: "微地震云图", path: "/microEarthQuake" },
  { name: "有利区推荐", path: "/favorableArea" }
]);

// 监听路由变化更新激活状态
watchEffect(() => {
  activeTab.value = route.path;
  useTabStore.changeTab(route.path);
});

const handleUser = ((val) => {
  switch (val) {
    case 'logout':
      localStorage.setItem(STORAGE_KEYS.GLOBAL_USER, '');
      authStore.logout();
      navigateTo('/login');
      break;
  }

});

watch(selectedAreaData, async (newVal) => {
  if (newVal) {
    await setData();
  }
}, { immediate: true });

onMounted(() => {
  const userStr = localStorage.getItem(STORAGE_KEYS.GLOBAL_USER);
  if (checkEmpty(userStr) || !authStore.checkAuth()) {
    handleUser('logout');
  }
  const user = JSON.parse(userStr);
  if (user) {
    userName.value = user.UserName;
  }

  emitter.on(EMIT_COMMAND.ADD_WORK_AREA, () => {
    getData();
  });
  getData();
});

onBeforeUnmount(() => {
  emitter.off(EMIT_COMMAND.ADD_WORK_AREA);
})

const getData = async () => {
  const response = await getWorkArea();
  if (response.Count > 0) {
    areaData.value = response.Data;
    const savedAreaData = localStorage.getItem(STORAGE_KEYS.GLOBAL_WORK_AREA);
    if (savedAreaData) {
      selectedAreaData.value = savedAreaData;
    } else {
      selectedAreaData.value = areaData.value[0].AreaID;
      await setData();
    }
  }
};

const setData = async () => {
  if (!selectedAreaData.value) {
    return;
  }
  const response = await setWorkArea(selectedAreaData.value);
  if (response.Code === 1) {
    localStorage.setItem(STORAGE_KEYS.GLOBAL_WORK_AREA, selectedAreaData.value);
  }
}
</script>

<style scoped>
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
  /* 可选：隐藏滚动条 */
}

*,
*::before,
*::after {
  box-sizing: border-box;
}

.layout {
  height: calc(100dvh - 8px);
  min-height: 700px;
  min-width: 1366px;
  width: 100%;
  margin: 0;
  padding: 0;
  /* overflow: hidden; */
}

.navbar {
  width: 100%;
  min-width: 1366px;
  display: flex;
  align-items: center;
  background: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-height: 50px;
  /* 设置最小高度防止内容过小时高度塌陷 */
  height: 55px;
  overflow: hidden;
  padding: 0;
  margin: 0;
  /* justify-content: space-around; */
}

.logo {
  font-weight: bold;
  margin-left: 1rem;
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.logo-img {
  width: 80px;
  height: 30px;
}

.log-text {
  font-size: 13px;
}

.nav-links {
  display: flex;
  list-style: none;
  gap: 1rem;
}

.nav-links a {
  text-decoration: none;
  color: #333;
  padding: 0.5rem;
  transition: color 0.3s;
}

.nav-links a:hover {
  color: #42b983;
}

.nav-links a.active {
  color: #42b983;
  border-bottom: 2px solid #42b983;
  font-weight: bold;
}

.user-info {
  flex-grow: 1;
  justify-content: flex-end;
}

.content {
  height: 100%;
  width: 100%;
  margin-top: 5px;
  padding: 0;
  overflow: hidden;
}

.div-area {
  justify-content: flex-end;
  margin-left: auto;
  margin-right: 30px;
}

.workArea {
  width: 100px;
  z-index: 1001;
  margin-right: 10px;
}
</style>
