<template>
  <div class="trademark mr-8 flex items-center text-white">
    <img :src="loginLogin" class="w-10 h-10 mr-4" />
    <div class="text-nowrap">客户管家</div>
  </div>
  <div class=" flex flex-row justify-start items-center text-white flex-1 parentDiv" ref="parentDiv">
    <div v-for="(routerItem, routerItemIdex) in routerList"
      :class="`border-b-2 border-transparent hover:border-white p-2 mr-4 cursor-pointer multipleyHeader ${activeRouter?.path === routerItem.path ? 'border-white' : ''}`"
      :key="routerItem.path" ref="childDivs" v-show="visibleItems.includes(routerItemIdex)">
      <div v-if="routerItem.children && routerItem.children.length <= 0 && routerItem?.isMenu" @click="setCurrentRouter(routerItem)" class="text-nowrap">
        {{ routerItem.name }}
      </div>
      <div v-if="routerItem.children && routerItem.children.length > 0" class="flex justify-center items-center">
        <el-dropdown>
          <div class="text-white w-full h-full headerText">
            {{ routerItem.name }}
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="child in routerItem.children" :key="child.path" @click="setCurrentRouter(child)">
                {{ child.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
  <div class="flex flex-row justify-start items-center text-white header-right">
    <el-icon :size="26" class="ml-4 cursor-pointer">
      <Bell />
    </el-icon>
    <div>
      <img class="w-8 h-8 rounded-full ml-4 cursor-pointer" :src="defaultCover" alt="" @click="logout()">
    </div>
    <el-icon :size="26" class="ml-4 cursor-pointer">
      <Grid />
    </el-icon>
  </div>
</template>
  
<script lang="ts" setup>
import { onMounted, ref, watchEffect, watch } from 'vue';
import { RouteRecordRaw, useRouter, useRoute } from 'vue-router';
import { useStore } from "../../store/index"
import defaultCover from "../../assets/defaultCover.png";
import loginLogin from '../../assets/login/login_logo.png'
const { routers, clearStore } = useStore()
const router = useRouter();
const route = useRoute()
// const routerList = ref<RouteRecordRaw[]>([]);
const routerList = ref<any[]>([]);
const activeRouter = ref<RouteRecordRaw>();

const visibleItems = ref<number[]>([]);
const parentDiv = ref<HTMLElement | null>(null);

const updateVisibleItems = () => {
  const parentWidth = parentDiv.value?.offsetWidth || 10;
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');

  let textWidthList: any = [] // 所有文字的宽度
  let totalWidth = 0;
  let temporaryIndex: any = []
  
  if(context) {
    context.font = '16px 微软雅黑';
    textWidthList = routerList.value.map((item: any) => {
      const metrics = context.measureText(item.name);
      return Math.ceil(metrics.width) + 32; // 32是padding和margin的宽度
    })
  }
  for(let i in textWidthList) {
    if(totalWidth + textWidthList[i] > parentWidth) {
      break;
    }
    totalWidth += textWidthList[i];
    temporaryIndex.push(+i);
  }

  // 替换最后一个元素
  let lastIndex = textWidthList.length - 1;
  temporaryIndex.splice(temporaryIndex.length -1, 1, lastIndex)

  visibleItems.value = temporaryIndex;
  //console.log(visibleItems.value)
};

const setCurrentRouter = (item: RouteRecordRaw) => {
  activeRouter.value = item;
  if (item.children && item.children.length > 0) {
    router.push({ path: item.children[0].path });
    return
  }
  router.push({ path: item.path });
};
const logout = () => {
  clearStore();
  router.push({ path: '/login' });
};
onMounted(() => {
  routerList.value = routers;
  activeRouter.value = routerList.value.find((item) => item.path === router.currentRoute.value.path);

  window.addEventListener('resize', updateVisibleItems);
  setTimeout(() => {
    updateVisibleItems();
  }, 500);
})
watchEffect(() => {
  updateVisibleItems();
  watch(() => route.path, (newPath, _oldPath) => {  
      activeRouter.value = routerList.value.find((item) => item.path === newPath);
    }, { 
      immediate: false 
    }
  );  
});
</script>
  
<style scoped lang="scss">
.trademark {
  font-size: 20px;
}
.multipleyHeader {
  height: 96%;
  display: flex;
  align-items: center;
  text-wrap: nowrap;

  .headerText {
    font-size: 16px;
  }
}
.parentBox {
  // max-width: 80%;
  // min-width: 300px;
  flex: 1;
  overflow: hidden;
}
.header-right {
  width: 135px;
}
.parentDiv {
  width: 50%;
}
</style>