<template>
  <nav class="pc-menu">
    <ul class="main-menu flex justify-start align-center">
      <li
        v-for="(mainMenu, index) in menuList"
        :key="index"
        :class="{
          'pd15 pt30 pb30 cursor': true,
          active: currentActiveIndex === index,
        }"
        @mouseenter="showAllSubMenus(index)"
        @mouseleave="hideAllSubMenus"
        @click="selectMenu(index, mainMenu)"
      >
        <p class="text-ct">{{ mainMenu.menuNm }}</p>
        <ul
          v-if="mainMenu.childList.length > 0"
          class="sub-menu "
          :class="{
            show: currentOpenIndex === index,
            'company-sub-menu':
              pageRole == 'potal'
          }"
        >
            <div class="sub-menu-inner" >
              <!-- 이벤트 버블링 현상을 막기 위해 click.stop으로 사용 -->
              <li
                v-for="(subMenu, subIndex) in mainMenu.childList"
                :key="subIndex"
                @click.stop="selectSubMenu(index, subIndex, subMenu)"
              >
                <p>{{ subMenu.menuNm }}</p>
                <ul
                  class="sub-sub-menu "
                  :class="{ show: currentOpenIndex === index }"
                >
                  <!-- 이벤트 버블링 현상을 막기 위해 click.stop으로 사용 -->
                  <li
                    v-for="(subSubMenu, subSubIndex) in subMenu.childList"
                    :key="subSubIndex"
                    class=""
                    @click.stop="
                      selectSubSubMenu(index, subIndex, subSubIndex, subSubMenu)
                    "
                  >
                    <p>{{ subSubMenu.menuNm }}</p>
                  </li>
                </ul>
              </li>
            </div>
        </ul>
      </li>
    </ul>
  </nav>
  <nav class="mobile-menu">
    <input type="checkbox" />

    <span></span>
    <span></span>
    <span></span>
    <ul class="main-menu">
      <li
        v-for="(mainMenu, index) in menuList"
        :key="index"
        :class="{ 'gd-12 cursor': true, active: currentActiveIndex === index }"
        @click="showAllSubMenus(index)"
      >
        <p class="text-lf pd10">{{ mainMenu.menuNm }}</p>
        <ul
          v-if="mainMenu.childList.length > 0"
          class="msub-menu pd30"
          :class="{
            show: currentOpenIndex === index,
            'company-sub-menu':
              pageRole == 'potal',
          }"
        >
          <div class="w1400">
            <div style="width: 100%">
              <!-- 이벤트 버블링 현상을 막기 위해 click.stop으로 사용 -->
              <li
                v-for="(subMenu, subIndex) in mainMenu.childList"
                :key="subIndex"
                @click.stop="selectSubMenu(index, subIndex, subMenu)"
              >
                <p>{{ subMenu.menuNm }}</p>
                <ul
                  class="msub-sub-menu pl20"
                  :class="{ show: currentOpenIndex === index }"
                >
                  <!-- 이벤트 버블링 현상을 막기 위해 click.stop으로 사용 -->
                  <li
                    v-for="(subSubMenu, subSubIndex) in subMenu.childList"
                    :key="subSubIndex"
                    class="pt10 pb10"
                    @click.stop="
                      selectSubSubMenu(index, subIndex, subSubIndex, subSubMenu)
                    "
                  >
                    <p>{{ subSubMenu.menuNm }}</p>
                  </li>
                </ul>
              </li>
            </div>
          </div>
        </ul>
      </li>
    </ul>
  </nav>
</template>

<script>
import store from "../../views/pages/AppStore";
import { findBySysMenu } from "../../resources/api/menu";
import queryParams from "../../resources/js/queryParams";
import { defaultSearchParams } from "../../resources/js/defaultSearchParams";
import cntnStatsSave from "../../resources/js/cntnStatsSave";

export default {
  mixins: [queryParams, cntnStatsSave],
  props: {},
  data() {
    return {
      pageRole: this.$store.state.userType,
      currentOpenIndex: null,
      roles: store.state.roles || [],
      menuList: [],
      currentActiveIndex: null,
      currentSubActiveIndex: null,
      currentSubSubActiveIndex: null,

      resetSearch: {
        ...defaultSearchParams,
      },
    };
  },
  created() {
    this.findAll();
  },
  methods: {
    // 목록 조회
    async findAll() {
      if (this.roles.length > 0) {
        this.roles = this.roles.map((auth) => auth.authority);
      }
      try {
        const params = {
          roles: this.roles,
          menuType: 'portal',
        };
        console.log('params', params);
        const res = await findBySysMenu(params);
        if (res.status == 200) {
          this.menuList = res.data.data.menuList;
          // 전체 메뉴 트리 store에 저장
          this.$store.commit('setMenuList', this.menuList);
          console.log('this.menuList', this.menuList);
          this.fnMenuActive(this.$route.path);
        }
      } catch (error) {
        alert("에러가 발생했습니다.\n관리자에게 문의하세요");
      }
    },
    showAllSubMenus(index) {
      this.currentOpenIndex = index;
    },
    hideAllSubMenus() {
      this.currentOpenIndex = null;
    },
    async selectMenu(index, menu) {
      this.currentActiveIndex = index;
      this.currentSubActiveIndex = null;
      this.currentSubSubActiveIndex = null;
      await this.cntnStatsSave(menu.menuId);
      if (menu.routerUrl !== "") {
        this.saveQueryParams("queryParams", this.resetSearch); // 검색조건 초기화
        if (menu.linkType === "0") {
          // 현재창
          this.$router.push({ path: menu.routerUrl });
        } else if (menu.linkType === "1") {
          // 새창
          window.open(menu.routerUrl, "_blank");
        }
        this.$router.push({ path: menu.routerUrl });
      }
    },
    async selectSubMenu(mainIndex, subIndex, menu) {
      this.saveQueryParams("queryParams", this.resetSearch); // 검색조건 초기화
      this.currentActiveIndex = mainIndex;
      this.currentSubActiveIndex = subIndex;
      this.currentSubSubActiveIndex = null;
      await this.cntnStatsSave(menu.menuId);
      if (menu.linkType === "0") {
        // 현재창
        this.$router.push({ path: menu.routerUrl });
      } else if (menu.linkType === "1") {
        // 새창
        window.open(menu.routerUrl, "_blank");
      }
    },
    async selectSubSubMenu(mainIndex, subIndex, subSubIndex, menu) {
      this.saveQueryParams("queryParams", this.resetSearch); // 검색조건 초기화
      this.currentActiveIndex = mainIndex;
      this.currentSubActiveIndex = subIndex;
      this.currentSubSubActiveIndex = subSubIndex;
      await this.cntnStatsSave(menu.menuId);
      if (menu.linkType === "0") {
        // 현재창
        this.$router.push({ path: menu.routerUrl });
      } else if (menu.linkType === "1") {
        // 새창
        window.open(menu.routerUrl, "_blank");
      }
    },
    fnMenuActive(path) {
      let menuIndex = -1; // 인덱스를 저장할 변수 초기화
      const url = this.$store.state.path;
      // 메인일 때
      if (url == "/portal" || url == "/company/main.page") {
        return (this.currentActiveIndex = null);
      }
      const lastSlashIndex = path.lastIndexOf("/"); // 마지막 '/' 인덱스
      const subStringPath = path.substring(0, lastSlashIndex);
      // 메뉴 리스트 에 routerUrl이 같은 메뉴가 있는지 확인하여 index 가져오기
      menuIndex = this.menuList.findIndex((menu) =>
        menu.routerUrl.includes(subStringPath)
      );

      // 만약 메뉴 리스트에서 찾지 못했다면, 각 메뉴의 childList에서 찾기
      if (menuIndex < 0) {
        for (let i = 0; i < this.menuList.length; i++) {
          let parentMenu = this.menuList[i];
          if (parentMenu.childList) {
            let childMenu = parentMenu.childList.find((child) =>
              child.routerUrl.includes(subStringPath)
            );
            if (childMenu) {
              menuIndex = i; // 인덱스를 저장
              break;
            }
          }
        }
      }
      this.currentActiveIndex = menuIndex; // 인덱스를 저장
    },
  },
  watch: {
    currentActiveIndex: function (newV, oldV) {},

    $route(to, from) {
      this.fnMenuActive(to.path);
    },
  },
  computed: {},
  mounted() {},
};
</script>