<template>
    <!-- 모바일용 메뉴 -->
    <nav class="mobile">
      <button class="icon-btn"  @click="toggleMenu" aria-label="mobile menu" aria-expanded="menuOpen"><svg-icon type="mdi" :path="menuPath" role="img" aria-labelledby="mobile menu"></svg-icon></button>
      <ul :class="{ 'mobile-menu': true, show: menuOpen }">
        <li v-if="menuOpen" class="close-button flex justify-end">
          <button @click="toggleMenu" aria-label="menu close"><svg-icon type="mdi" :path="closePath" rol="img" aria-labelledby="menu close"></svg-icon></button>
        </li>
        <li v-for="(mainMenu, index) in menuList" :key="index"
          :class="{ 'cursor relative': true, active: currentActiveIndex === index }" 
          @click="toggleSubMenu(index)">
          <p role="menuitem" tabindex="0" aria-haspopup="true" 
             :aria-expanded="currentOpenIndex === index" class="pd10">{{ mainMenu.menuNm }}</p>
          <ul v-if="currentOpenIndex === index && mainMenu.childList.length > 0" 
              :class="{ 'sub-menu': true, show: currentOpenIndex === index }">
            <li v-for="(subMenu, subIndex) in mainMenu.childList" :key="subIndex" @click.stop="selectSubMenu(index, subIndex, subMenu, mainMenu)"
              role="none">
              <p role="menuitem" tabindex="-1">{{ subMenu.menuNm }}</p>
            </li>
          </ul>
        </li>
      </ul>
    </nav>
    </template>
    
    <script>
    import { mdiTemperatureCelsius } from "@mdi/js";
    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";
    import { mdiMenu, mdiWindowClose } from '@mdi/js';

    
    export default {
      mixins: [queryParams, cntnStatsSave],
      props: {},
      data() {
        return {
          currentOpenIndex: null,
          hideTimeout: null,
          menuOpen: false,
          currentActiveIndex: null,
          roles: store.state.roles || [],
          menuList: [],
          currentActiveIndex: null,
          currentSubActiveIndex: null,
          currentSubSubActiveIndex: null,
          menuPath:mdiMenu,
          closePath:mdiWindowClose,
          resetSearch: { ...defaultSearchParams },
        };
      },
      created() {
        this.findAll();
      },
      methods: {
      //  메뉴 처리 이벤트
      
        // 모바일 메뉴
        toggleMenu() {
        this.menuOpen = !this.menuOpen;
      },
      toggleSubMenu(index) {
        if (this.currentOpenIndex === index) {
          this.currentOpenIndex = null;
        } else {
          this.currentOpenIndex = index;
        }
      },
      checkMobile() {
      this.isMobile = window.innerWidth <= 768;    
    },
    
        // 목록 조회
        async findAll() {
          const vm = this;
          if (this.roles.length > 0) {
            this.roles = this.roles.map((auth) => auth.authority);
          }
          try {
            const params = {
              roles: this.roles,
              menuType: store.state.userType,
            };
            const res = await findBySysMenu(params);
            if (res.status == 200) {            
              this.menuList = res.data.data.menuList;
              this.$store.commit('setMenuList', this.menuList );
            }
          } catch (error) {
            // alert("에러가 발생했습니다.\n관리자에게 문의하세요.!!!");
            alert(vm.$getCmmnMessage('err005'));
          }
        },
    
        async selectMenu(index, menu) {
          this.saveQueryParams("queryParams", this.resetSearch); // 검색조건 초기화
          this.currentActiveIndex = index;
          this.currentSubActiveIndex = null;
          this.currentSubSubActiveIndex = null;
          //await this.cntnStatsSave(menu.menuId);
          this.currentOpenIndex = null;
          if (menu.linkTypeNm === "0") {
            // 현재창
            this.$router.push({
              path: menu.routerUrl,
            });
          } else if (menu.linkTypeNm === "1") {
            // 새창
            window.open(menu.routerUrl, "_blank");
          }
        },
        async selectSubMenu(mainIndex, subIndex, subMenu, mainMenu) {
          this.saveQueryParams("queryParams", this.resetSearch); // 검색조건 초기화
          this.currentActiveIndex = mainIndex;
          this.currentSubActiveIndex = subIndex;
          this.currentSubSubActiveIndex = null;
          this.menuOpen = false;
          await this.cntnStatsSave(subMenu.menuId);
    
          // 메뉴 정보 스토리지 생성
          this.$store.commit('`setMenu`', subMenu);
         // this.$store.commit('setMenuInfo', { 'menuNm': subMenu.menuNm, 'menuCn': subMenu.menuCn });
        // this.$store.commit('setPageNaviInfo', { 'main': mainMenu.menuNm, 'sub': subMenu.menuNm });
          this.$store.commit('setCurrentMenu', subMenu.menuId);
          this.currentOpenIndex = null;
          if (subMenu.linkTypeNm === "0") {
            // 현재창
            this.$router.push({
              path: subMenu.routerUrl,
            });
          } else if (subMenu.linkTypeNm === "1") {
            // 새창
            window.open(subMenu.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.linkTypeNm === "0") {
            // 현재창
            this.$router.push({
              path: menu.routerUrl,
            });
          } else if (menu.linkTypeNm === "1") {
            // 새창
            window.open(menu.routerUrl, "_blank");
          }
        },
      },
      watch: {
        currentActiveIndex: function (newV, oldV) {         
        },
      },
      computed: {
        maxSubMenuHeight: function () {
          let maxSubItems = Math.max(...this.menuList.map(menu => menu.childList.length));
          return (maxSubItems * 45) + 30;
        }
      },
      mounted() {
        this.checkMobile();
        window.addEventListener('resize', this.checkMobile);
      },
      beforeDestroy() {
        window.removeEventListener('resize', this.checkMobile);
      },
    };
    </script>
    