<template>
  <el-container class="smart-city-container">
    <!-- 顶部Header -->
    <el-header class="city-header">
      <div class="header-left">
        <img src="@/assets/images/logo.png" alt="" />
        <div class="Split"></div>
        <div class="header_subtitle">投资决策分析系统</div>
      </div>
      <div class="header-right">
        <div class="message-wrap" @click="toMessagePage">
          <el-badge
            :hidden="messageCount <= 0"
            :value="messageCount"
            :max="999"
            class="badge"
          >
            <el-icon size="20"> <Bell /> </el-icon>
          </el-badge>
          <span> 消息中心 </span>
        </div>
        <div class="Split"></div>
        <span class="avatar">
          <el-icon size="20"><Avatar /></el-icon>
        </span>
        <el-dropdown @visible-change="changeVisible">
          <span class="username">
            {{ userInfo.name }}
            <el-icon size="14">
              <ArrowUp v-if="isIcon" />
              <ArrowDown v-else />
            </el-icon>
          </span>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleLogout"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </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.fullPath"
                :label="view.title"
                :name="view.fullPath"
              />
            </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";
import { Bell, Avatar, ArrowUp, ArrowDown } from "@element-plus/icons-vue"; // 补充导入图标

const userStore = useUserStore();
const proxyRef = ref(null);
const { proxy } = getCurrentInstance();
const excludeTabs = ["/homePage"];

const isIcon = ref(false);
const changeVisible = (bool) => {
  isIcon.value = Boolean(bool);
};

// 判断是否包含目标路由的核心方法
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 basePath = view.path;
  const fullPath = view.fullPath || view.path;

  // 1. 先找同基础路径的路由
  const samePathIndex = visitedViews.value.findIndex(
    (v) => v.path === basePath,
  );

  if (samePathIndex !== -1) {
    // 2. 如果存在同路径路由，更新它的参数和fullPath（不新增）
    visitedViews.value[samePathIndex] = {
      ...visitedViews.value[samePathIndex],
      fullPath: fullPath,
      query: { ...view.query },
      params: { ...view.params },
    };
  } else {
    // 3. 不存在则新增
    visitedViews.value.push({
      path: basePath,
      fullPath: fullPath,
      query: { ...view.query },
      params: { ...view.params },
      title: view.title || view.meta?.title || view.name || "未命名",
    });
  }

  // 更新激活状态
  activePath.value = fullPath;
};

// 点击标签切换路由（优化：确保切换时参数正确）
const handleTabClick = (tab) => {
  const fullPath = tab.paneName;
  if (fullPath !== route.fullPath) {
    const targetView = visitedViews.value.find((v) => v.fullPath === fullPath);
    if (targetView) {
      router.push({
        path: targetView.path,
        query: targetView.query,
        params: targetView.params,
      });
    } else {
      // 备用方案：直接通过fullPath跳转
      router.push(fullPath);
    }
  }
};

// 修复后的关闭标签方法
const handleTabRemove = (targetFullPath) => {
  // 1. 找到要删除的标签索引
  const index = visitedViews.value.findIndex(
    (v) => v.fullPath === targetFullPath,
  );

  // 如果没找到，直接返回
  if (index === -1) return;

  // 2. 获取要删除的视图
  const targetView = visitedViews.value[index];

  // 3. 删除该标签
  visitedViews.value.splice(index, 1);

  // 4. 如果删除的是当前激活的标签，需要跳转到其他标签
  if (targetFullPath === route.fullPath) {
    // 优先跳转到下一个标签，如果没有则跳转到上一个
    const nextIndex = index < visitedViews.value.length ? index : index - 1;

    if (nextIndex >= 0 && visitedViews.value[nextIndex]) {
      // 跳转到下一个/上一个标签
      router.push(visitedViews.value[nextIndex].fullPath);
    } else {
      // 如果没有剩余标签，跳转到首页
      router.push("/");
    }
  }

  // 5. 更新激活的标签路径
  if (visitedViews.value.length > 0) {
    activePath.value =
      visitedViews.value[visitedViews.value.length - 1].fullPath;
  } else {
    activePath.value = "";
  }
};
// ========== 路由标签页相关结束 ==========

// 获取资源库数据
const getResourceData = () => {
  axios
    .post(windowConfig.baseUrl + "/api/resource/listResourceAll", {})
    .then((res) => {
      sessionStorage.setItem("resourceData", JSON.stringify(res.data));
    })
    .catch((err) => console.error("获取资源库数据失败：", err)); // 增加错误处理
};

// 获取未读消息数量
let messageCount = ref(0);
const getMessageCount = () => {
  axios
    .post(windowConfig.baseUrl + "/api/message/getMesCount", {})
    .then((res) => {
      messageCount.value = res.data.count || 0; // 增加默认值
    })
    .catch((err) => console.error("获取消息数量失败：", err)); // 增加错误处理
};

// 跳转消息列表页
const toMessagePage = () => {
  router.push("/message");
};

onMounted(() => {
  getResourceData();
  getMessageCount();
  addView(route); // 初始化时添加当前路由
});

// 优化watch：监听完整的route变化，而不只是path
watch(
  () => route,
  (newRoute) => {
    getMessageCount();
    addView(newRoute); // 路由变化时添加到标签页
  },
  { immediate: false, deep: true }, // 深度监听路由对象
);

// 处理退出登录
const handleLogout = () => {
  // 优先使用axios，避免依赖proxy
  axios
    .post(windowConfig.baseUrl + "/api/user/logout", {})
    .then(() => {
      userStore.clearUserInfo();
      sessionStorage.removeItem("userInfo"); // 清除本地存储
      router.replace("/login");
    })
    .catch((err) => console.error("退出登录失败：", err));

  // // 如果需要保留proxy方式，使用下面的代码
  // if (proxy) {
  //   proxy.$post({
  //     url: "/api/user/logout",
  //     data: {},
  //     callback: (data) => {
  //       userStore.clearUserInfo();
  //       sessionStorage.removeItem("userInfo");
  //       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;
  }
}

/* 选中菜单项样式 */
::v-deep .el-menu-item {
  color: #666;
  font-size: 14px;
  background-color: #fff;
  height: 40px;
  line-height: 40px;
}
::v-deep .el-menu {
  border-right: none;
}
::v-deep .el-sub-menu {
  color: #666;
  font-size: 14px;
  background-color: #fff;
  .el-sub-menu__title {
    height: 40px;
    line-height: 40px;
  }
}
:deep(.el-menu-item.is-active) {
  color: #0084ff;
  background-color: #f1f7ff;
}

/* 子菜单被激活时，父菜单也高亮 */
:deep(.el-sub-menu.is-active > .el-sub-menu__title) {
  color: #0084ff !important;
}

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

/* 图标样式 */
:deep(.el-menu-item .el-icon),
:deep(.el-sub-menu__title .el-icon) {
  font-size: 14px;
  margin-right: 8px;
}

.city-header {
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 50%, #69c0ff 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;

  .Split {
    margin: 4px 10px;
    width: 1px;
    height: 16px;
    opacity: 1;
    background: #ffffff;
  }
  .header-left {
    display: flex;
    height: 24px;
    .header_subtitle {
      font-size: 15px;
      font-weight: 700;
      letter-spacing: 0px;
      line-height: 24px;
      color: #ffffff;
      text-align: right;
      vertical-align: top;
    }
    img {
      height: 24px;
    }
  }
}

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

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

.avatar {
  display: flex;
  margin-right: 4px;
}
.username {
  display: flex;
  color: #fff;
  cursor: pointer;
  align-items: center;
  i {
    margin-left: 8px;
  }
}

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

.city-main {
  overflow-y: auto;
  background-color: #ecf2f8;
  --el-main-padding: 0;
  display: flex;
  flex-direction: column;
}

// 标签页容器样式
.tabs-view {
  background: #fff;
  padding: 8px;

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

    .el-tabs__nav {
      border: none;
    }

    .el-tabs__item {
      margin-top: 0;
      height: 32px;
      line-height: 32px;
      border-radius: 3px;
      margin-right: 8px;
      color: #495060;
      font-size: 12px;
      padding: 0 10px 0 12px !important;
      background: #f5f5f5;
      transition: all 0.2s;

      &:hover {
        color: #fff;
        background: #1890ff;
      }

      &.is-active {
        padding: 0 10px 0 12px;
        color: #fff;
        background: #1890ff;
        border-color: #1890ff;
      }
    }

    .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;
  margin: 16px 16px 0 16px;
  background: #fff;
}
.header-right {
  display: flex;
  align-items: center;
  .badge {
    display: flex;
    margin-right: 6px;
  }
  .message-wrap {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 14px;
  }
}
</style>
