<template>
  <div v-if="breadcrumbList.length > 0" class="breadcrumb-warp">
    <span class="home"><router-link :to="{path : this.$filters.ctxPath('/adm/main.page')}">홈</router-link> &gt; </span>
    <span v-for="(crumb, index) in breadcrumbList" :key="index">
      {{ crumb.menuNm }}
      <span v-if="index < breadcrumbList.length - 1"> &gt; </span>
    </span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      breadcrumbList: [],
    };
  },
  watch: {
    // 페이지 이동 시 동작
    $route: {
      immediate: true,
      handler() {
        this.generateBreadcrumb();
      }
    },
    // 새로고침 시 동작
    '$store.state.menuList': {
      immediate: true,
      handler(val) {
        if (val && val.length > 0) {
          this.generateBreadcrumb();
        }
      }
    },
  },
  methods: {
    generateBreadcrumb() {
      const menuState = this.$store.state;
      const currentPath = this.$route.path;
      const basePath = currentPath.substring(0, currentPath.lastIndexOf('/')); // 현재 경로에서 마지막 '/' 이전까지의 경로
      // const pathType = currentPath.substring(currentPath.lastIndexOf('/') + 1);
      const upPath = basePath + '/list.page'; // 상위 경로(목록)로 생성

      // 관리자: childList 기반
      const findFromTree = (menus, path, trail = [], isOwnPath) => {
        for (const menu of menus) {
          const newTrail = [...trail, menu];
          if (menu.routerUrl === path) {
            findCurrent.isOwnPath = isOwnPath; // 본인 경로 여부
            this.$store.commit('setMenu', menu);
            return newTrail;
          }
          if (menu.childList?.length) {
            const found = findFromTree(menu.childList, path, newTrail);
            if (found) return found;
          }
        }
        return null;
      };

      // 사용자: upMenuId 기반
      const findFromFlat = (flatMenus, path, isOwnPath) => {
        const findCurrent = flatMenus.find(menu => menu.routerUrl === path);
        if (!findCurrent) return [];

        findCurrent.isOwnPath = isOwnPath; // 본인 경로 여부
        this.$store.commit('setMenu', findCurrent);

        const buildTrail = (menu, trail = []) => {
          const parent = flatMenus.find(m => m.menuId === menu.upMenuId);
          if (parent) {
            return buildTrail(parent, [parent, ...trail]);
          }
          return trail;
        };

        const trail = buildTrail(findCurrent);
        return [...trail, findCurrent];
      };

      // 메뉴 리스트 펼치기
      const flattenMenus = (menus) => {
        const result = [];

        for (const menu of menus) {
          result.push(menu);
          if (menu.childList?.length) {
            result.push(...flattenMenus(menu.childList));
          }
        }

        return result;
      }

      let breadcrumb = [];

      // 구조 판단
      if (menuState.menuList?.length) {
        // 사용자용
        // const flatMenus = menuState.menuList.flatMap(menu =>
        //   [menu, ...(menu.childList || [])]
        // );
        const flatMenus = flattenMenus(menuState.menuList);
        const matchMenu = flatMenus.find(menu => menu.routerUrl === currentPath); // 현재 경로가 메뉴에 있는지 확인
        let path = currentPath;
        let isOwnPath = true; // 본인 경로임
        if(!matchMenu) {
          path = upPath; // 현재 경로가 메뉴에 없다면 상위 경로 사용
          isOwnPath = false; // 본인 경로가 아님
        }

        breadcrumb = findFromFlat(flatMenus, path, isOwnPath);
      } else if (menuState.menu?.childList?.length) {
        // 관리자용
        breadcrumb = findFromTree(menuState.menu.childList, path, isOwnPath);
      }

      this.breadcrumbList = breadcrumb;
    },

  },
  mounted(){
    // this.generateBreadcrumb();
  }
};
</script>