<template>
  <div class="layout" v-if="isShow">
    <div class="header">
      <div class="logo">
        <img class="logo" src="../../assets/imgs/logo.png" alt="logo" />
        <img src="@/assets/imgs/VWAG_Confidential.svg" alt="confidential" style="width: 105px; height: 55px; margin-left: 5px">
      </div>
      <div class="logout">
        <p><i class="iconfont icon-user"></i>{{ userName }}</p>
        <p @click="logout()"><i class="iconfont icon-logout"></i>Logout</p>
      </div>
    </div>
    <div class="menus">
      <el-menu
        :default-active="currentMenu"
        mode="horizontal"
        background-color="#0B2C55"
        text-color="#fff"
        active-text-color="#fff"
        ref="menu"
      >
        <el-menu-item
          v-for="item in menuList"
          :index="item.id"
          :key="item.id"
          @click="pushRoute(item)"
          >{{ item.name }}</el-menu-item
        >
      </el-menu>
    </div>
    <div class="main">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="(item, i) in breadcrumbList" :key='i' :to="{ path: item.path }">{{ item.name }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="content">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script>
import {ForceLogin, GetUserInfo,SameUserOnline, Logout} from "@/api/permission";
const allMenuList = [
  { id: '1', name: 'Group Management', path: '/groupManagement' },
  { id: '2', name: 'Ticket Management', path: '/ticketManagement' },
  { id: '3', name: 'Configuration Management', path: '/configurationManagement' },
  { id: '4', name: 'Permission Management', path: '/permissionManagement/userList' },
  { id: '5', name: 'Data Source Management', path: '/datasourceManagement' },
]
export default {
  name: "Layout",
  data() {
    return {
      isShow: true,
      userName: "Evan Yates",
      menuList: [],
      currentMenu: "1",
      breadcrumbList: [],
    };
  },
  mounted() {
    // this.menuList = allMenuList
    this.isSomeOneUseLogin();
    // this.getBreadcrumbList();
    // 添加 beforeunload 事件监听器
    // window.addEventListener('beforeunload', this.logout);
  },
  watch:{
    '$route'(to, from){
      allMenuList.map(item=>{
        if (item.path == to.path) {
          this.currentMenu = item.id;
        }
      })
     setTimeout(()=>{
          allMenuList.map(item=>{
            if (item.path == to.path) {
              this.$refs.menu.updateActiveIndex(item.id);
            }
          })
      },500)
      // this.getMenuList();
      this.getBreadcrumbList();
    },
  },
  methods: {
    isSomeOneUseLogin(){
      SameUserOnline().then(res => {
        if (res.sameUserOnline) {
          this.$confirm('There is already a user with the same login online. Do you want to overwrite their login?', 'Warning', {
            confirmButtonText: 'Confirm',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            ForceLogin().then(res => {
              if(res.code === 200) {
                this.getMenuList();
                this.getBreadcrumbList();
                // this.menuList = allMenuList
                // 重新加载页面，从缓存中加载
                window.location.reload();

                // this.getBreadcrumbList();
              }
            })
          }).catch(() => {
            Logout().then(res => {
              this.$keycloak.logout();
              this.$message({
                message: res.msg,
                type: 'success',
                showClose: true,
                duration: 24 * 60 * 1000
              });
            });
          });
        } else {
          this.getMenuList();
          this.getBreadcrumbList();
          // this.menuList = allMenuList
        }
      })

    },
    getBreadcrumbList(){
      this.breadcrumbList = [];
      this.$route.matched.forEach(item => {
        if(item.path && item.meta['title']){
          this.breadcrumbList.push({
            name: item.meta['title'],
            path: item.path
          })
        }
      })
    },
    getMenuList(){
      GetUserInfo().then(res => {
        this.userName = res.userName;
        if(res['status'] === 'DISABLE'){
          this.isShow = false;
          this.$message({
            message: 'This account has been disabled and you do not have permission to access this page!',
            type: 'error',
            showClose: true,
            duration: 24 * 60 * 1000
          });
          return;
        }
        if(res['resources'].length){
          this.isShow = true;
          this.menuList = allMenuList.filter(item => res['resources'].map(item => item['resname']).includes(item.name));
          if(this.menuList.length > 0){
            this.$router.push({ path:this.menuList[0].path })
            this.currentMenu = this.menuList[0]['id']
          }
        }else {
          this.isShow = false;
          this.$message({
            message: 'You do not have permission to access this page!',
            type: 'error',
            showClose: true,
            duration: 24 * 60 * 1000
          });
          // window.location.reload();
          setTimeout(() => {
            this.$keycloak.logout();
          }, 2000);
        }
      })
    },
    pushRoute(item){
      let localPath = this.$route.path;
      if ('/groupManagement/addVin' == localPath) {
          this.$refs.menu.updateActiveIndex('1');
      }
      if ('/ticketManagement/detail' == localPath) {
          this.$refs.menu.updateActiveIndex('2');
      }
      this.$router.push({ path: item.path })
    },
    logout() {
      Logout().then(res => {
        this.$keycloak.logout();
        sessionStorage.clear();
        this.$message({
          message: res.msg,
          type: 'success',
          showClose: true,
          duration: 24 * 60 * 1000
        });
      });
    },
  },
  // beforeunload() {
  //   window.removeEventListener('beforeunload', this.logout);
  // }
};
</script>

<style lang="scss" src="../../assets/css/layout.scss" />
