<!--
  Program: common layout offsider
  Author: SDL
  Brief: common layout offsider
-->
<template>
  <!-- Aside -->
  <aside class="ui--aside">
    <ul class="ui--aside-inner">
      <!-- user -->
      <li class="ui--aside-icon" :class="{ active: offsider === 'user' }">
        <a href="javascript:" @click="changeOffsider('user')">
          <div>
            <span class="ui--user-last">{{ lastUserName }}</span>
          </div>
        </a>
        <div class="ui--aside-item ui--user" v-show="offsider === 'user'">
          <h4>
            <span class="ui--blind">My Profile</span>
            <button type="button" class="close btn-close" @click="changeOffsider('user')"></button>
          </h4>
          <ul class="ui--user-info">
            <li class="mb-3">
              <strong>{{ userInfo.userName }}</strong
              >{{ $t('sdl.offsider.label.honorific') }}<button class="btn ui--btn-logout" @click="goLoginPage">Logout</button>
            </li>
            <li class="mb-1">{{ userInfo.email }}</li>
            <li class="mb-1">{{ userInfo.deptName }}/{{ userInfo.compName }}</li>
            <li>
              <a class="ui--link-user" href="javascript:" @click="changePasswordPopup">{{ $t('sdl.identity.label.pwdChange') }}</a>
              <span class="me-1 ms-1 ui--slide">|</span>
              <a class="ui--link-user" href="javascript:" @click="entrustApprovalPopup">{{ $t('sdl.offsider.label.agencyAppr') }}</a>
            </li>
          </ul>
          <ul class="d-flex ui--contact-info">
            <li class="flex-fill"><a class="ui--btn-contact" href="javascript:">Contact US</a></li>
            <li class="flex-fill"><a class="ui--btn-contact" href="javascript:">IT VOC</a></li>
          </ul>
        </div>
      </li>
      <!-- // user -->

      <!-- sitemap -->
      <li class="ui--aside-icon" :class="{ active: offsider === 'sitemap' }">
        <a href="javascript:" title="Sitemap" @click="changeOffsider('sitemap')"><i class="bi bi-grid-3x3-gap-fill"></i></a>
        <!-- sitemap -->
        <div class="ui--aside-item ui--sitemap-container">
          <div class="modal-header">
            <h4 class="modal-title">Sitemap</h4>
            <button type="button" class="btn-close" @click="changeOffsider('sitemap')"></button>
          </div>
          <template v-for="(row, index) in siteMapRows" :key="index">
          <div class="modal-body">
            <div class="row">
              <div class="col-3" v-for="menu in getRootMenus(index)" :key="menu.menuId">
                <!-- 1depth -->
                <h3 class="ui--menu-title cursor-pointer" v-if="menu.externalUrlUsed === true" @click="openExternalUrl(menu.externalUrl)">{{ getLabel(menu) }} <i class="bi bi-arrow-up-right"></i></h3>
                <h3 class="ui--menu-title" v-else-if="menu.defaultPage">{{ getLabel(menu) }} <i class="bi bi-chevron-right"></i></h3>
                <h3 class="ui--menu-title" v-else>{{ getLabel(menu) }}</h3>
                <!--// 1depth -->
                <ul class="ui--menu-group">
                  <li v-for="submenu in getSubmenu(menu.menuId)" :key="submenu.menuId">
                    <!-- 2depth -->
                    <strong v-if="submenu.externalUrlUsed === true" @click="openExternalUrl(submenu.externalUrl)" class="cursor-pointer"> {{ getLabel(submenu) }} <i class="bi bi-arrow-up-right"></i></strong>
                    <strong v-else-if="submenu.defaultPage" @click="moveMenu(submenu.defaultPage.pagePath)" class="cursor-pointer"> {{ getLabel(submenu) }} <i class="bi bi-chevron-right"></i></strong>
                    <strong v-else>{{ getLabel(submenu) }}</strong>
                    <!--// 2depth -->
                    <ul class="ui--menu-list">
                      <li v-for="item in getSubmenu(submenu.menuId)" :key="item.menuId">
                        <div v-if="item.externalUrlUsed === true">
                          <a href="javascript:" @click="openExternalUrl(item.externalUrl)">
                            {{ getLabel(item) }}
                          </a>
                          <i class="bi bi-arrow-up-right"></i>
                        </div>

                        <a v-else href="javascript:" @click="moveMenu(item.menuUrl)">{{ getLabel(item) }}</a>
                      </li>
                    </ul>
                  </li>
                </ul>
              </div>
            </div>
            <hr class="mb-5 border-0" />
          </div>
          </template>
        </div>
      </li>
      <!-- // sitemap -->

      <!-- quick -->
      <li class="ui--aside-icon" :class="{ active: offsider === 'quick' }">
        <a href="javascript:" title="Quick Menu" @click="(quickSubmenu = false), changeOffsider('quick')">
          <i class="bi bi-star-fill"></i>
        </a>
        <div class="ui--aside-item ui--aside-quick">
          <!-- quick list -->
          <div class="ui--quick-menu">
            <div class="ui--quick-header">
              <h5>Quick Menu</h5>
              <div class="ui--button-right">
                <button class="btn" title="Open Settings" @click="quickSubmenu = !quickSubmenu">
                  <i class="bi bi-gear-fill"></i>
                </button>
                <!-- 설정버튼 클릭시 .ui--aside-quick .setting 이 부분이 display:block 되면 됩니다. -->
                <button class="btn bs-tooltip-auto" title="Close Setting" @click="(quickSubmenu = false), changeOffsider('quick')">
                  <i class="bi bi-x-lg"></i>
                </button>
              </div>
            </div>

            <!--            <div class="ui--quick-list">-->
            <draggable v-bind="dragOptions" v-model="userMenus" class="ui--quick-list" tag="ul" @change="moveMenuList" handle=".drag-handle" item-key="menuId">
              <template #item="{ element, index }">
                <li>
                  <a :href="element.externalUrl.startsWith('http') ? element.externalUrl : `http://${element.externalUrl}`" v-if="element.externalUrlUsed" target="_blank">
                    <i title="Move Menu" class="bi bi-grip-vertical" v-show="quickSubmenu" style="cursor: move"></i>
                    {{ getLabel(element) }} <i class="bi bi-arrow-up-right"></i>
                  </a>
                  <router-link :to="element.pagePath" v-else>
                    <i title="Move Menu" class="bi bi-grip-vertical" v-show="quickSubmenu" style="cursor: move"></i>
                    {{ getLabel(element) }}
                  </router-link>

                  <button class="btn ui--btn-xs" :title="$t('sdl.common.label.delete')" @click="removeQuickMenu(element.menuId, index)" v-show="quickSubmenu">
                    <i class="bi bi-dash"></i>
                  </button>
                </li>
              </template>
            </draggable>
            <!--            </ul>-->
          </div>
          <!-- quick setting -->
          <div class="ui--aside-item ui--aside-quick ui--setting" v-show="quickSubmenu">
            <!-- quick list -->
            <div class="ui--quick-menu">
              <div class="ui--quick-header">
                <input class="form-control" type="text" :placeholder="$t('sdl.offsider.label.searchMenu')" autocomplete="on" v-model="searchQuickMenu" @input="searchQuickMenu = $event.target.value" @keyup.esc="searchQuickMenu = ''" />
                <div class="ui--button-right">
                  <button class="btn bs-tooltip-auto" title="Close Setting" @click="(quickSubmenu = false), (searchQuickMenu = '')">
                    <i class="bi bi-x-lg"></i>
                  </button>
                </div>
              </div>
              <ul class="ui--quick-list">
                <li v-for="menu in filteredQuickMenus" :key="menu.menuId" :class="{ selected: menu.selected }">
                  <a href="javascript:">
                    {{ getLabel(menu) }}
                    <i class="bi bi-arrow-up-right" v-show="menu.externalUrlUsed"></i>
                  </a>
                  <button class="btn ui--btn-xs" :title="$t('sdl.common.label.add')" @click="addQuickMenu(menu)">
                    <i class="bi bi-plus-lg"></i>
                  </button>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </li>
      <!-- // quick -->

      <!-- U Trans -->
      <li class="ui--aside-icon" title="Translation" :class="{ active: offsider === 'trans' }">
        <a href="javascript:" @click="openTrans"><i class="bi bi-translate"></i></a>
      </li>
      <!-- // U Trans -->

      <!-- language -->
      <li class="ui--aside-icon" :class="{ active: offsider === 'language' }">
        <a href="javascript:" :title="$t('sdl.common.language.select')" @click="changeOffsider('language')"
          ><span>{{ $t('sdl.common.language.code') }}</span></a
        >
        <div class="ui--aside-item ui--aside-language">
          <ul class="ui--language-list">
            <li v-for="locale in availableLocales" :key="locale" :data-locale="locale" :class="{ selected: locale === $i18n.locale }">
              <a href="javascript:" @click="changeLocale(locale)">{{ getLocaleLabel(locale) }}</a>
            </li>
          </ul>
        </div>
      </li>
      <!-- // language -->
      <!-- timezone -->
      <li class="ui--aside-icon" :class="{ active: offsider === 'timezone' }">
        <!-- active -->
        <a href="javascript:" @click="changeOffsider('timezone')" title="GMT"><i class="bi bi-clock"></i></a>
        <div class="ui--aside-item ui--aside-timezone">
          <div class="modal-header">
            <h5 class="modal-title">Timezone</h5>
            <button type="button" class="btn-close" @click="changeOffsider('timezone')"></button>
          </div>
          <div class="modal-body ui--timezone">
            <h5 class="mb-4">{{ userTimezoneLabel }}</h5>
            <div class="row mb-3">
              <div class="col-12">
                <label>{{ $t('sdl.common.timezone.setting') }}</label>
                <div class="input-group">
                  <select class="form-select" required="" style="flex-basis: 110px" v-model="timeZoneArea" @change="timeZoneId = ''">
                    <option value="Africa">{{ $t('sdl.common.timezone.Africa') }}</option>
                    <option value="America">{{ $t('sdl.common.timezone.America') }}</option>
                    <option value="Asia">{{ $t('sdl.common.timezone.Asia') }}</option>
                    <option value="Atlantic">{{ $t('sdl.common.timezone.Atlantic') }}</option>
                    <option value="Australia">{{ $t('sdl.common.timezone.Australia') }}</option>
                    <option value="Europe">{{ $t('sdl.common.timezone.Europe') }}</option>
                    <option value="Indian">{{ $t('sdl.common.timezone.Indian') }}</option>
                    <option value="Pacific">{{ $t('sdl.common.timezone.Pacific') }}</option>
                    <option value="Etc">{{ $t('sdl.common.timezone.Etc') }}</option>
                  </select>
                  <select class="form-select" required="" style="flex-basis: 250px" v-model="timeZoneId">
                    <option value="" disabled>{{ $t('sdl.offsider.label.select') }}</option>
                    <option :value="time.timeZoneId" v-for="time in filteredTimeZoneList" :key="time.timeZoneId">
                      {{ time.displayTimeZone }}
                    </option>
                  </select>
                  <button class="btn btn-secondary" @click="saveTimezone()" :disabled="timeZoneId === ''">
                    {{ $t('sdl.common.label.save') }}
                  </button>
                </div>
              </div>
            </div>
            <ul>
              <li>{{ $t('sdl.common.timezone.settingDesc1') }}</li>
              <li>{{ $t('sdl.common.timezone.settingDesc2') }}</li>
              <li style="display: none">{{ $t('sdl.common.timezone.settingDesc3') }}</li>
            </ul>
          </div>
        </div>
      </li>
      <!-- //timezone -->
    </ul>
  </aside>
</template>
<script>
import { mapActions, mapGetters } from 'vuex';
import axios from 'axios';
import draggable from 'vuedraggable';
import _ from 'lodash';
import store from '@/vuex/store';
import { SDLUtil, StringUtil } from '@/utils';
import SDLLocale from '@/mixin/SDLLocale';
import loginService from '@/service/loginService';
import EntrustApprovalPopup from '@/components/common/popup/EntrustApprovalPopup.vue';
import ChangePasswordPopup from '@/components/common/popup/ChangePasswordPopup.vue';

export default {
  name: 'Offsider',
  mixins: [SDLLocale],
  data() {
    return {
      userInfo: null,
      offsider: '',
      quickSubmenu: false,
      searchQuickMenu: '',
      quickMenus: [],
      userMenus: [],
      timeZoneList: [],
      timeZoneArea: '',
      timeZoneId: '',
      timeZoneAreaList: ['Africa', 'America', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific'], // etc 제외
      dragOptions: {
        animation: 200,
        group: 'quickList',
        disabled: false,
        ghostClass: 'ghost',
      },
    };
  },
  created() {
    this.userInfo = SDLUtil.getLoginedUserInfo();
    // Import Quick Menu
    // this.getUserQuickMenus();
  },
  computed: {
    ...mapGetters({
      menus: 'getMenus', // Receive menus with getter
    }),
    userTimezoneLabel() {
      return `${this.userInfo.timeZoneId} (${this.userInfo.timeZoneCode})`;
    },
    filteredTimeZoneList() {
      if (this.timeZoneArea === 'Etc') {
        // return _.sortBy(this.timeZoneList.filter(zone => !this.timeZoneAreaList.includes(zone.timeZoneArea)), [
        //   'displayTimeZone',
        // ]);
        return this.timeZoneList.filter(zone => !this.timeZoneAreaList.includes(zone.timeZoneArea));
      }
      // return _.sortBy(this.timeZoneList.filter(zone => zone.timeZoneArea === this.timeZoneArea), 'displayTimeZone');
      return this.timeZoneList.filter(zone => zone.timeZoneArea === this.timeZoneArea);
    },
    rootMenus() {
      return _.sortBy(
        this.menus.filter(menu => menu.menuLevel === 1 && menu.menuId !== 'COMM_URL'),
        ['menuSequence'],
      ); // Excluding standard platform menu exposure
    },
    siteMapRows() {
      return Math.ceil(this.rootMenus.length / 4);
    },
    lastUserName() {
      return this.userInfo.userName && this.userInfo.userName.toUpperCase().split('')[0];
    },
    filteredQuickMenus() {
      return _.orderBy(
        this.quickMenus.filter(menu => {
          menu.curLabel = this.getLabel(menu);
          return this.getLabel(menu).toUpperCase().includes(this.searchQuickMenu.toUpperCase());
        }),
        'curLabel',
        'asc',
      );
    },
    availableLocales() {
      return this.$i18n.availableLocales;
    },
  },
  methods: {
    ...mapActions(['logout', 'setLocale']),
    init() {
      this.offsider = '';
      this.searchQuickMenu = '';
      document.querySelector('body').classList.remove('overflow-hidden');
    },
    changeOffsider(menu) {
      this.offsider = this.offsider === menu ? '' : menu;
      // Remove scrolling to body if full size area
      const withoutScrollMenus = ['sitemap'];
      if (!withoutScrollMenus.includes(this.offsider)) {
        document.querySelector('body').classList.remove('overflow-hidden');
      } else {
        document.querySelector('body').classList.add('overflow-hidden');
      }
      // time zone area call
      if (this.offsider === 'timezone') {
        axios.get(`${SDLUtil.API_URL}/auth/users/timezone`).then(({ data }) => {
          this.timeZoneList = data.timeZoneList.map(zone => ({
            ...zone,
            // isEtc,
            timeZoneArea: zone.timeZoneId.split('/')[0],
          }));
          this.timeZoneArea = data.timeZoneArea;
          this.timeZoneId = data.timeZoneId;
        });
      }
      if (this.offsider === 'quick') {
        this.getUserQuickMenus();
      }
    },
    goLoginPage() {
      this.$router.push(`${this.$CONTEXT}/logout`);
    },
    getRootMenus(idx) {
      const result = [];
      for (let i = idx * 4, nMax = idx * 4 + 4; i < nMax; i += 1) {
        if (this.rootMenus[i] === undefined) {
          break;
        }
        result.push(this.rootMenus[i]);
      }
      return result;
    },
    getSubmenu(parentId) {
      return _.sortBy(
        this.menus.filter(menu => menu.parentId === parentId),
        ['menuSequence'],
      );
    },
    getUserQuickMenus() {
      // quick 메뉴 전체, All quick menu
      // 외부 링크 사용 혹은 default Page 가 있는 메뉴
      this.quickMenus = this.menus
        .filter(menu => {
          // 외부 링크 사용
          if (menu.externalUrlUsed) {
            return true;
          }
          // default Page 가 있는 메뉴
          return menu.pages.length > 0 && _.find(menu.pages, ['defaulted', true]);
        })
        .map(menu => {
          const defaultPage = _.find(menu.pages, ['defaulted', true]);
          return {
            ...menu,
            ...defaultPage,
            selected: false,
          };
        });

      axios.get(`${SDLUtil.API_URL}/auth/quick-menus`).then(({ data }) => {
        this.userMenus = [];
        data.forEach(menuId => {
          const menu = _.find(this.quickMenus, ['menuId', menuId]);
          if (menu) {
            menu.selected = true;
            this.userMenus.push(menu);
          }
        });
      });
    },
    changeLocale(locale) {
      this.$i18n.locale = locale;
      this.setLocale(locale);
      this.updateUserToken({ language: locale });
      this.changeOffsider('language');
    },
    getLocaleLabel(locale) {
      return this.$i18n.getLocaleMessage(locale)['sdl.common.language.label'];
    },
    removeQuickMenu(menuId, index) {
      axios.delete(`${SDLUtil.API_URL}/auth/quick-menus/${menuId}`).then(() => {
        this.userMenus.splice(index, 1);
        // default quick Menu add
        const menu = _.find(this.quickMenus, ['menuId', menuId]);
        if (menu) {
          menu.selected = false;
        }
      });
    },
    addQuickMenu(menu) {
      menu.selected = true;
      SDLUtil.showLoadingBar(true);
      this.userMenus = [...this.userMenus, menu];
      this.saveQuickMenu()
        .then(() => {
          // console.info('success', data);
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
          this.userMenus.pop();
        });
    },
    saveQuickMenu() {
      // console.info('params', this.userMenus.map(menu => menu.menuId));
      return axios.post(
        `${SDLUtil.API_URL}/auth/quick-menus`,
        this.userMenus.map(menu => menu.menuId),
      );
    },
    moveMenuList(event) {
      if (event.moved) {
        // api call
        this.saveQuickMenu();
      }
    },
    saveTimezone() {
      SDLUtil.showLoadingBar(true);
      axios
        .put(`${SDLUtil.API_URL}/auth/users/timezone?${StringUtil.queryStringfy({ timeZoneId: this.timeZoneId })}`)
        .then(({ data }) => {
          // 성공
          console.info('success');
          SDLUtil.showLoadingBar(false);
          // loginService.setToken(data.jwtToken);
          this.updateUserToken({ timeZoneId: this.timeZoneId, timeZoneCode: data });
        })
        .catch(err => {
          SDLUtil.errorAlert(err);
          SDLUtil.showLoadingBar(false);
        });
    },
    moveMenu(pagePath) {
      // Initialize saved parameters when forced to move from the menu
      store.commit('PARAMS', {});
      this.$router.push({ path: pagePath });
    },
    updateUserToken(param) {
      const params = {
        language: this.userInfo.language,
        timeZoneId: this.userInfo.timeZoneId,
        timeZoneCode: this.userInfo.timeZoneCode,
        ...param,
      };

      axios.put(`${SDLUtil.API_URL}/auth/users/user-token`, params).then(({ data }) => {
        loginService.setToken(data.jwtToken);
        this.userInfo = SDLUtil.getLoginedUserInfo();
      });
    },
    openExternalUrl(url) {
      window.open(url.startsWith('http') ? url : `http://${url}`, '_blank');
    },
    changePasswordPopup() {
      SDLUtil.show(ChangePasswordPopup, null, {
        width: 600,
        height: 400,
      });
    },
    entrustApprovalPopup() {
      SDLUtil.show(EntrustApprovalPopup, null, {
        width: 600,
        height: 'auto',
      });
    },
    /**
     * Open Trans Popup
     */
    openTrans() {
      const width = 1100;
      const height = 670;
      const leftPosition = Math.ceil((window.screen.width - width) / 2);
      const topPosition = Math.ceil((window.screen.height - height) / 2);

      window.open(`${SDLUtil.WEB_CONTEXT_PATH}/transPopup`, 'popup', `width=${width},height=${height},top=${topPosition},left=${leftPosition},location=0,directories=0,resizable=0,status=0,toolbar=0,menubar=0`, '_blank');
    },
  },
  watch: {
    $route() {
      this.init();
    },
  },
  components: {
    draggable,
  },
};
</script>
