<template>
  <div class="bg-breadcrumb">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item
        v-if="state.breadcrumbData.length >= 2"
        v-for="(item, index) in state.dataArr"
        :to="{ path: item.path }">
        {{ item.name }}
      </el-breadcrumb-item>
      <el-breadcrumb-item> {{ state.breadcrumbData[state.breadcrumbData.length - 1].name }} </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script setup>
import { reactive, ref, onBeforeMount, toRefs } from "vue";
import { useRouter, useRoute } from "vue-router";
import store from "@/store";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();

const state = reactive({
  dataArr: [],
  breadcrumbData: [],
});

const props = defineProps({
  isMenu: {
    type: Boolean,
    default: false,
  },
});

const getBreadcrumbData = (menuObj, menu, path) => {
  //获取整体需要路径
  let parentPath = menuObj[path].rowPath.slice(1, menuObj[path].rowPath.length).split(".");
  getFirstPath(parentPath, menu);
  //有2层以上的面包屑显示,则继续向下处理
  if (parentPath.length >= 2) {
    getOtherPath(parentPath, menu);
  }
};

const getFirstPath = (parentPath, menu) => {
  let tempMenu = menu[parentPath[0]];
  if (!props.isMenu) {
    tempMenu = tempMenu.children[parentPath[1]];
  }
  //目录则跳转第一个子类，菜单子菜单则跳转自身
  if (tempMenu.menuType == 0) {
    if (tempMenu.children && tempMenu.children.length) {
      for (let index = 0; index < tempMenu.children.length; index++) {
        const e = tempMenu.children[index];
        if (e.menuType !== 0) {
          state.breadcrumbData.push({
            path: e.path,
            name: tempMenu.menuName,
          });
          break;
        }
      }
    }
  } else {
    state.breadcrumbData.push({
      path: tempMenu.path,
      name: tempMenu.menuName,
    });
  }
};

const getOtherPath = (parentPath, menu) => {
  let tempMenu = menu[parentPath[0]];
  let index;
  if (!props.isMenu) {
    index = 2;
    tempMenu = tempMenu.children[parentPath[1]].children || [];
  } else {
    tempMenu = tempMenu.children || [];
    index = 1;
  }
  if (tempMenu.length && parentPath[index]) {
    getPath(tempMenu, parentPath, index);
  }
};

const getPath = (tempMenu, parentPath, index) => {
  if (!tempMenu[parentPath[index]]) {
    return;
  }
  tempMenu = tempMenu[parentPath[index]];
  index = index + 1;
  state.breadcrumbData.push({
    path: tempMenu.path,
    name: tempMenu.menuName,
  });
  if (tempMenu.children && tempMenu.children.length && parentPath[index]) {
    getPath(tempMenu.children, parentPath, index);
  }
};

onBeforeMount(() => {
  getBreadcrumbData(store.state.menuObj, store.state.menu, route.path);
  state.breadcrumbData.forEach((e, idx) => {
    if (idx !== state.breadcrumbData.length - 1) {
      state.dataArr.push(e);
    }
  });
});
</script>

<style scoped></style>
