<template>
  <div class="layout-header">
    <div class="logo"></div>
    <div class="menu">
      <el-menu :default-active="currentPath" ref="menuRef" class="el-menu-demo" mode="horizontal">
        <el-menu-item :index="item.path" v-for="item in routeList" :key="item.name" :class="{ 'external-link-item': isExternalLink(item.path) }"
          @click="handleMenuClick(item.path)">{{ item.title }}</el-menu-item>
      </el-menu>
    </div>
    <!-- 机构切换下拉 -->
    <div style="align-self: center; margin-right: 16px;">
      <el-select v-model="currentOrg" placeholder="请选择机构" style="width: 160px" @change="changeOrg">
        <el-option v-for="org in orgList" :key="org.id" :label="org.organ_name" :value="org.id" />
      </el-select>
    </div>
    <!-- 用户下拉 -->
    <div style="align-self: center;">
      <el-dropdown style="margin-top:10px">
        <div style="font-size:medium;font-weight: bold; color:#000">{{ user.full_name }}</div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>用户资料</el-dropdown-item>
            <el-dropdown-item @click="editPassShow = true">修改密码</el-dropdown-item>
            <el-dropdown-item @click="handleLogout">登出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
  <EditPasswordDialog v-model="editPassShow" />
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount,getCurrentInstance } from 'vue'
import { useMenuStore } from "@/stores/menu.js"
import { useRoute, useRouter } from "vue-router";
import { getSessionVar, clearSessionVar, saveSessionVar } from '@/utils/session'
import EditPasswordDialog from "@/components/EditPasswordDialog.vue"
import { knowledgeGraphAddr } from "@/utils/config"
const { updateRouteList } = useMenuStore();
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
let timer

const menuRef = ref()
const { routeList } = useMenuStore()
const user = ref({
  id: "0",
  full_name: 'John Doe',
  username: 'johndoe',
})
user.value = {
  id: getSessionVar('user_id') || "0",
  full_name: getSessionVar('full_name') || 'John Doe',
  username: getSessionVar('username') || 'johndoe',
}

// 机构相关
const orgList = ref([])
const currentOrg = ref(getSessionVar('org_id') || '') // 当前机构id

// 获取机构列表
const fetchOrgList = async () => {
  // 假设接口返回 { records: [{id, name}, ...] }
  const { records } = await proxy.$http.get('/open-platform/sys/loadSURO')
  orgList.value = records
  // 默认选中第一个
  const res =  await proxy.$http.get('/open-platform/sys/currSURO')
  console.log('当前机构11:', res)
    currentOrg.value = res
    saveSessionVar('org_id', res)

  console.log('机构列表:', orgList.value)
  console.log('当前机构:', currentOrg.value)
}

// 切换机构
const changeOrg = async (orgId) => {
  // 可调用后端切换机构接口
 const res =  await proxy.$http.post(`/open-platform/sys/changeSURO/${orgId}`)
 console.log('切换机构结果:', res)
  saveSessionVar('org_id', orgId)
  // 可选：刷新页面或重新拉取权限/菜单等
  updateRouteList([]);
  let knowledageSystem = '';
    let routeList = [{
      path: '/kmplatform/home',
      name: 'kmplatform-home',
      title: "主页",
      children: []
    }]
    res.records[0].menu_permissions.sort((a, b) => {
      return a.id - b.id;
    });
    res.records[0].menu_permissions.forEach((item) => {
      if (item.menu_name == "知识更新管理") {
        knowledageSystem = 'true';
        routeList.push({
          path: knowledgeGraphAddr,
          name: '',
          title: item.name,
          children: item.children,
        });
      } else if (item.menu_route) {
        routeList.push({
          path: item.menu_route,
          name: item.menu_route.split("/")[2],
          title: item.name,
          children: item.children,
        });
      }
    });
    console.log("knowledageSystem", knowledageSystem);
    saveSessionVar("knowledageSystem", knowledageSystem);
    saveSessionVar('routeList', JSON.stringify(routeList))

    updateRouteList(routeList);
  // window.location.reload()
}

let editPassShow = ref(false)
const currentPath = computed(() => {
  let temp = ""
  for (let i = 0; i < routeList.length; i++) {
    for (let j = 0; j < route.matched.length; j++) {
      if (routeList[i].path === route.matched[j].path) {
        temp = route.matched[j].path
        break
      }
    }
    if (temp) break;
  }
  return temp
})
const handleLogout = () => {
  router.push({ path: '/login' });
  clearSessionVar()
}

const isExternalLink = (path) => {
  return /^https?/g.test(path);
};

function handleMenuClick(path) {
  if (/^https?/g.test(path)) {
    const newWindow = window.open(path, '_blank');
    timer = setInterval(() => {
      newWindow?.postMessage({ type: 'login', username: getSessionVar("full_name"), userID: getSessionVar("user_id") }, "*")
    }, 1000)
    menuRef.value.updateActiveIndex(currentPath.value)
  } else {
    if (route.path.includes(path)) return
    router.push({ path: path })
  }
}
function handleLogin(event) {
  const { type, status } = event.data
  if (type === 'login' && status === 'ok') {
    clearInterval(timer)
  }
}
onMounted(() => {
  window.addEventListener('message', handleLogin);
  fetchOrgList()
})

onBeforeUnmount(() => {
  window.removeEventListener('message', handleLogin);
  clearInterval(timer)
})
</script>

<style lang="less" scoped>
.layout-header {
  display: flex;
  border-bottom: 1px solid #C4C2C2;
  // padding-bottom: 10px;

  .logo {
    width: 200px;
    // height: 60px;
    // border: 1px solid skyblue;
    flex: 0 0 auto;
    margin-right: 50px;
    background: url('../assets/images/logo.jpg') no-repeat center;
    background-size: 100% 100%;
  }

  .menu {
    flex: 1 1 auto;

    // .el-menu--horizontal>.el-menu-item.is-active {
    //   border: none;
    // }

    .el-menu--horizontal.el-menu {
      border: none;
    }

    ::v-deep .el-menu {
      .el-menu-item {
        font-size: 20px;
      }
    }
    .external-link-item {
      // 覆盖激活效果
      &.is-active {
        background-color: transparent !important;
        color: inherit !important;
      }

      // 覆盖点击效果
      &:focus {
        background-color: transparent !important;
        color: inherit !important;
      }
    }
  }
}
</style>
