<template>
  <el-container class="smart-city-container">
    <!-- 顶部Header -->
    <el-header class="city-header">
      <div class="header-left">
        <img src="@/assets/images/logo.png" alt="" />
        <!-- <span class="city-name">123123</span> -->
      </div>
      <div class="header-right">
        <div class="message-wrap" @click="toMessagePage">
          <el-icon size="20">
            <ChatDotSquare />
          </el-icon>
          <div v-if="messageCount" class="count">{{ messageCount }}</div>
        </div>
        <div>
          <el-dropdown>
            <span class="username">
              {{ userInfo.name }}
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleLogout"
                  >退出登录</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-header>

    <el-container class="container-main">
      <!-- 侧边Aside -->
      <el-aside width="220px" class="city-aside">
        <left-menu></left-menu>
      </el-aside>

      <!-- 主内容Main -->
      <el-main class="city-main">
        <template v-if="route?.path && isExcludeRoute(route.path)">
          <div class="tabs-view" v-if="visitedViews && visitedViews.length > 0">
            <el-tabs
              v-model="activePath"
              type="card"
              closable
              @tab-click="handleTabClick"
              @tab-remove="handleTabRemove"
            >
              <el-tab-pane
                v-for="view in visitedViews"
                :key="view.path"
                :label="view.title"
                :name="view.path"
              />
            </el-tabs>
          </div>
        </template>
        <!-- 路由视图 -->
        <div class="view-content">
          <router-view />
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { computed, ref, onMounted, getCurrentInstance, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/stores/user.js";
import windowConfig from "@/window";
import LeftMenu from "./leftMenu.vue";
import axios from "axios"; // watch中使用proxy会有warning
const userStore = useUserStore();
const proxyRef = ref(null);
const { proxy } = getCurrentInstance();
const excludeTabs = ["/homePage"];

// 2. 判断是否包含目标路由的核心方法
const isExcludeRoute = (path) => {
  return !excludeTabs.includes(path);
};

// 在 setup 中设置
const instance = getCurrentInstance();
if (instance) {
  proxyRef.value = instance.proxy;
}
let userInfo = ref(
  sessionStorage.getItem("userInfo")
    ? JSON.parse(sessionStorage.getItem("userInfo"))
    : [],
);
const router = useRouter();
const route = useRoute();

// ========== 路由标签页相关 ==========
const visitedViews = ref([]); // 已访问的路由列表
const activePath = ref(""); // 当前激活的路由路径
// 添加路由到已访问列表
const addView = (view) => {
  // 检查路由是否已存在
  const index = visitedViews.value.findIndex((v) => v.path === view.path);
  if (index === -1) {
    // 不存在则添加，优先使用 title，其次 meta.title，最后 name
    visitedViews.value.push({
      path: view.path,
      title: view.title || view.meta?.title || view.name || "未命名",
    });
    console.log(visitedViews, "visitedViewsvisitedViews");
  }
  // 设置当前激活的路由
  activePath.value = view.path;
};

// 点击标签切换路由
const handleTabClick = (tab) => {
  const path = tab.paneName;
  if (path !== route.path) {
    router.push(path);
  }
};

// 关闭标签
const handleTabRemove = (targetPath) => {
  const index = visitedViews.value.findIndex((v) => v.path === targetPath);
  if (index !== -1) {
    // 移除路由
    visitedViews.value.splice(index, 1);

    // 如果关闭的是当前路由，则跳转到上一个路由
    if (targetPath === route.path) {
      if (visitedViews.value.length > 0) {
        // 跳转到相邻路由（优先后面的，如果没有则前面的）
        const nextView =
          visitedViews.value[index] || visitedViews.value[index - 1];
        if (nextView) {
          router.push(nextView.path);
        }
      } else {
        // 如果没有其他路由，跳转到首页
        router.push("/");
      }
    }
  }
};

// ========== 路由标签页相关结束 ==========

// 获取资源库数据
const getResourceData = () => {
  axios
    .post(windowConfig.baseUrl + "/api/resource/listResourceAll", {})
    .then((res) => {
      sessionStorage.setItem("resourceData", JSON.stringify(res.data));
    });
};
// 获取未读消息数量
let messageCount = ref(0);
const getMessageCount = () => {
  axios
    .post(windowConfig.baseUrl + "/api/message/getMesCount", {})
    .then((res) => {
      messageCount.value = res.data.count;
    });
};
// 跳转消息列表页
const toMessagePage = () => {
  router.push("/message");
};
onMounted(() => {
  getResourceData();
  getMessageCount();
  addView(route); // 初始化时添加当前路由
});

watch(
  () => route.path,
  () => {
    getMessageCount();
    addView(route); // 路由变化时添加到标签页
  },
);
// 处理退出登录
const handleLogout = () => {
  // 清除登录状态
  proxy.$post({
    url: "/api/user/logout",
    data: {},
    callback: (data) => {
      userStore.clearUserInfo();
      router.replace("/login");
    },
  });
};
</script>

<style scoped lang="less">
.smart-city-container {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .container-main {
    flex: 1;
    height: 0;
  }
}

/* 选中菜单项样式 */
.el-menu-item {
  color: #666;
  background-color: #fff;
}
.el-menu-item.is-active {
  background-color: #ecf3fd;
  color: #3d84ee;
  border-right: 4px solid #3d84ee;
}

/* 完全去掉系统管理子菜单的背景色 */
:deep(.el-sub-menu__title) {
  color: #666;
  background-color: #fff !important;
}

.city-header {
  width: 100%;
  height: 64px;
  background: #3db8c5 url("@/assets/images/header-bg.png") no-repeat fixed top
    left / 100% 64px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .header-left {
    padding-left: 25px;
  }
}

.city-name {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 10px;
  color: #fff;
  cursor: pointer;
}

.city-aside {
  background-color: #fff;
  width: 240px;
  height: 100%;
  box-shadow: 0 6px 10px 0 rgba(36, 36, 63, 0.05);
  overflow: auto;
}

.city-main {
  height: calc(100vh - 60px);
  overflow-y: auto;
  background-color: #ecf2f8;
  --el-main-padding: 0;
  display: flex;
  flex-direction: column;
}

// 标签页容器样式
.tabs-view {
  background: #fff;
  margin: 16px 16px 0 16px;
  padding: 10px 16px;
  border-radius: 8px;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  :deep(.el-tabs) {
    .el-tabs__header {
      margin: 0;
      border-bottom: none;
    }

    .el-tabs__nav {
      border: none;
    }

    .el-tabs__item {
      height: 32px;
      line-height: 32px;
      border: 1px solid #d8dce5;
      border-radius: 3px;
      margin-right: 8px;
      color: #495060;
      font-size: 12px;
      padding: 0 12px;
      background: #fff;
      transition: all 0.2s;

      border-top: 2px solid #d8dce5;

      &:hover {
        color: #3d84ee;
        background: #ecf3fd;
      }

      &.is-active {
        color: #3d84ee;
        background: #ecf3fd;
        border-color: #3d84ee;
      }
    }

    .el-tabs__item .el-icon-close {
      width: 14px;
      height: 14px;
      font-size: 12px;

      &:hover {
        background-color: #3d84ee;
        color: #fff;
        border-radius: 50%;
      }
    }
  }
}

// 路由视图内容
.view-content {
  flex: 1;
  overflow-y: auto;
  height: 0;
}
.header-right {
  display: flex;
  align-items: center;
  .message-wrap {
    position: relative;
    margin-right: 10px;
    cursor: pointer;
    .count {
      position: absolute;
      top: -5px;
      right: -5px;
      min-width: 14px;
      height: 14px;
      border-radius: 50%;
      background-color: red;
      color: #fff;
      font-size: 10px;
      text-align: center;
      line-height: 14px;
    }
  }
}
</style>
