<!--
  Program: main page
  Author: SDL
  Brief: main layout template
-->
<template>
  <div id="mainWrapperDiv" class="ui--wrapper ui---footer" :class="{
    'ui---lnb-collapsed': isFoldSideMenu && !isHideSideMenu,
    'aside-hide': !isHideSideMenu,
    's-main': isHideSideMenu,
    'ui---lnb': !isHideSideMenu,
  }">
    <!--aside-hide aside-collapsed-->
    <!-- GNB -->
    <top-menu :is-main-index="isHideSideMenu"></top-menu>
    <!-- SUB Layout -->
    <section class="ui--section-container" :class="{ 'only-main': isHideSideMenu }">
      <!-- SUB Contents -->

      <!-- <template v-if="$route.path.startsWith('/embo/')"> -->
      <template v-if="$route.path==='/'">        
        <router-view :key="$route.path"></router-view>
      </template>
      <template v-else>
        <!-- 탭 영역 -->
        <div class="tabs">
          <div v-for="tab in tabs" :key="tab.path" class="tab" :class="{ active: isActive(tab) }">
            <router-link :to="tab.path"> {{ getLabel(tab.tabMenuObj) }}

            </router-link>
            <button @click="closeTab(tab)">&times;</button>
          </div>
        </div>

        <!-- keep-alive로 상태 유지 :key="$route.path"-->
        <router-view v-slot="{ Component }">
          <keep-alive :include="cachedComponents">
            <component :is="Component" :key="$route.meta.menuId" />

          </keep-alive>
        </router-view>
        <!-- <tab-page :key="$route.path"></tab-page>-->
        <!-- <pre>{{ JSON.stringify(tabs,null,2) }}</pre>  -->
        <!-- <pre>{{ JSON.stringify($route,null,2) }}</pre> -->

      </template>
      



      <!-- LEFT Navigation -->
      <side-menu v-if="!isHideSideMenu" @fold-event="isFoldSideMenu = !isFoldSideMenu" @hide-event="displaySideMenu" />
      <!-- Offsider -->
      <!--offsider></offsider-->
    </section>
    <!-- Footer -->
    <footer class="ui--footer-container">
      <div class="ui--footer-in">
        <span>&copy; Samsung</span>
        <a class="ms-3" href="javascript:" @click="showTermPopup('PERSONAL_USE', $event)">{{
          $t('sdl.privacyPolicy.policy')
        }}</a>
        <span class="ms-2 me-2 ui--slide">|</span>
        <a href="javascript:" class="me-4" @click="showTermPopup('AGREE_USE', $event)">{{
          $t('sdl.privacyPolicy.termsUse')
        }}</a>
        <span class="ui-footer-confidential">confidential</span>
      </div>
    </footer>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import axios from 'axios';
import TopMenu from './MainTopMenu.vue';
import SideMenu from './MainSideMenu.vue';
import Offsider from './MainOffsider.vue';
import { SDLUtil } from '@/utils';
import TermPopup from '@/components/common/popup/TermPopup.vue';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  name: 'MainPage',
  mixins: [SDLLocale],
  components: {
    TopMenu,
    SideMenu,
    Offsider,
  },
  data() {
    return {
      isFoldSideMenu: false,
      isHideSideMenu: false,
      tabs: [],
    };
  },
  computed: {
    ...mapGetters({
      locale: 'getLocale',
    }),
    // keep-alive에 포함할 컴포넌트 목록
    cachedComponents() {

      let name = this.tabs.map(tab => tab.componentName);
      console.log('cachedComponents:' + name);

      return name;
    }
  },
  methods: {

    // 현재 활성 탭 확인
    isActive(tab) {
      return tab.menuId === this.$route.meta.menuId;
    },
    // 탭 닫기 핸들러
    closeTab(tab) {
      const index = this.tabs.findIndex(t => t.path === tab.path)
      if (index !== -1) {
        const wasActive = tab.menuId === this.$route.meta.menuId
        this.tabs.splice(index, 1)

        if (wasActive && this.tabs.length > 0) {
          const newTab = this.tabs[Math.max(index - 1, 0)]
          this.$router.push(newTab.path)
        }
      }
    },

    ...mapActions(['getMenus']),
    displaySideMenu(flag) {
      this.isHideSideMenu = flag;
    },
    showTermPopup(termsTypeCode, event) {
      SDLUtil.showLoadingBar(true);
      const title = event.currentTarget.textContent;
      axios
        .get(`${SDLUtil.API_URL}/privacypolicy/terms/${termsTypeCode}/valid?langType=${this.locale}`)
        .then(({ data }) => {
          SDLUtil.show(
            TermPopup,
            {
              title,
              term: data,
            },
            {
              width: 1000,
              height: 850,
            },
          );
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
  },
  watch: {
    /* $route() {
       console.log('watch $route1');
       this.isHideSideMenu = this.$route.meta.menuId === undefined;
     },*/

    '$route': {
      handler(newRoute) {

        this.isHideSideMenu = this.$route.meta.menuId === undefined;
        const existingTab = this.tabs.find(tab => tab.menuId === newRoute.meta.menuId)

        if (!existingTab && newRoute.meta.componentName) {
          this.tabs.push({
            menuId: newRoute.meta.menuId,
            path: newRoute.path,

            tabMenuObj: newRoute.meta.tabMenuObj || newRoute.name,
            componentName: newRoute.meta.componentName
          })
        }
      },
      immediate: true,
      deep: true
    }

  },
  created() {
    // document.querySelector('body').classList.remove('ui--login-wrap', 'sdl-wrap');
    // Hide side menu area without menuId
    this.isHideSideMenu = this.$route.meta.menuId === undefined;
  },
  beforeCreate() {
    const redirect = this.$router.currentRoute.value.query.redirect || '';
    if (redirect) {
      this.$router.replace(redirect);
    }
  },
  mounted() {
    // eslint-disable-next-line no-undef
  },
  updated() {
    // eslint-disable-next-line no-undef
  },
};
</script>

<style scoped>
.only-main {
  padding: 0 0 0 0 !important;
}


.tabs {
  display: flex;
  border-bottom: 1px solid #ccc;
  margin: 1rem 0;
}

.tab {
  padding: 0.5rem 1rem;
  border: 1px solid #ccc;
  border-bottom: none;
  margin-right: 0.5rem;
  display: flex;
  align-items: center;
  background: white;
  border-radius: 4px 4px 0 0;
}

.tab.active {
  background: #eee;
  border-color: #999;
}

.tab a {
  text-decoration: none;
  color: inherit;
}

.tab button {
  margin-left: 0.5rem;
  border: none;
  background: none;
  cursor: pointer;
  color: #666;
}

.tab button:hover {
  color: #333;
}
</style>
