<template>
  <nav class="admin-sub-menu pt50 pb50">
    <div class="pd30 pt0 pb15">
      <div class="admin-info pd15 mb10">
        <div class="flex justify-center align-center mb10">
          <p class="admin-name">{{ mbrNm }}</p>
          <p class="pd10 pl5 relative admin-alarm  cursor" aria-label="alarm" @click.stop="modalshow">
            <svg-icon type="mdi" :width="23" :height="23" :path="bellPath" :color="'#fff'" role="img"
              aria-labelledby="alarm"></svg-icon>
            <span class="alarm-number notranslate">{{ alarmList.length }}</span>
          </p>
        </div>
        <div class="flex justify-center align-center">
          <button class="admin-btn pr10" @click="fnlogOut">로그아웃</button>
          <button class="admin-btn pl10" @click="fnSiteMove">사이트이동</button>
        </div>
      </div>
      <div>
        <button class="large-btn darkg-border-btn" @click="cacheClean()">변경사항 적용</button>
      </div>
    </div>
    <ul class="side-menu pt10 pb10">
      <template v-if="menuList.length > 0">
        <li v-for="(sub, subidx) in menuList" :key="subidx" :class="{ 'sub-active': isActive(sub.routerUrl) }">
          <div :class="{ 'pt10 pb10 pl30 cursor': true }" @click="menuClick(sub, 1)">
            <span>{{ sub.menuNm }}</span>
            <!-- <router-link :to="sub.routerUrl">{{ sub.menuNm }}</router-link> -->
          </div>
          <ul v-show="sub.childList.length > 0">
            <li v-for="(third, thirdIdx) in sub.childList" :key="thirdIdx" :class="{
              'pt10 pb10 pl60 cursor': true,
              'sub-active': isActive(third.routerUrl),
            }" @click="menuClick(third, 2, sub)">
              <span>{{ third.menuNm }}</span>
              <!-- <router-link :to="{ path: third.routerUrl }"> {{ third.menuNm }} </router-link> -->
            </li>
          </ul>
        </li>
      </template>
    </ul>

    <!-- 관리자 알림 -->
    <div class="alarm-modal pd15 border admin-alarm-modal" v-show="alarmModal" v-click-outside="closeModal">
      <div class="flex justify-end">
        <button class="icon-btn" @click="closeModal"><svg-icon type="mdi" :path="closePath" role="img"
            aria-labelledby="modal close"></svg-icon></button>
      </div>
      <div class="border-b pb10">
        <div class="flex justify-between align-center">
          <p>알람 <span>{{ alarmList.length }}</span>건</p>
          <button class="icon-btn small-text" @click="readAll()">전체읽기</button>
        </div>
      </div>
      <ul class="pt10 pb10 overflow-y" style="height:calc(100% - 27px)" v-if="alarmList.length > 0">
        <li class=" alarm-item pd10 mb5" v-for="(itm, indx) in alarmList" :key="indx">
          <div @click="readEvent(itm)">
            <div class="flex justify-start align-start">
              <div class="pd5 alarm-itmcon">
                <svg-icon type="mdi" :width="20" :height="20" :path="bellPath" role="img"
                                    aria-labelledby="alarm icon"></svg-icon><span>알람</span>
              </div>
              <div class="ml10">
                <p>{{ itm.evt_cn }}</p>
                <p class="small-text">{{ $filters.dateTime(itm.dsptch_dt) }}</p>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <ul class="pt10 pb10" v-else style="height:calc(100% - 27px)">
          <div class="flex flex-column justify-center align-center content">
              알림 내역이 없습니다.
          </div>
      </ul>
    </div>
  </nav>


</template>

<script>
import store from "../../views/pages/AppStore";
import queryParams from "../../resources/js/queryParams";
import { defaultSearchParams } from "../../resources/js/defaultSearchParams";
import { mapActions } from "vuex";
import cntnStatsSave from "../../resources/js/cntnStatsSave";
import { cacheReSet } from "../../resources/api/cacheReSet";
import { mdiBell, mdiClose } from '@mdi/js';

import { findAllEvent, readEvent, readAllEvent } from "../../resources/api/eventAlarm";

export default {
  mixins: [queryParams, cntnStatsSave],
  components: {},
  props: {},
  data() {
    return {
      mbrNm: store.state.mbrNm,
      currentPath: this.$route.path,
      resetSearch: { ...defaultSearchParams },
      menuList: [],
      bellPath: mdiBell,
      closePath: mdiClose,
      alarmModal: false,
      alarmList: [],
      timer: {},
    };
  },
  created() {
    this.menuCheck();
  },
  methods: {
    // 알람 모달
    modalshow() {
      this.alarmModal = !this.alarmModal
    },
    closeModal() {
      this.alarmModal = false;
    },
    menuCheck() {
      const menu = store.state.menu;
      if (menu != null && menu != "" && menu != undefined) {
        this.menuList = menu.childList;
      }
    },
    async menuClick(menu, depth, sub) {
      this.saveQueryParams("queryParams", this.resetSearch); // 검색조건 초기화
      // await this.cntnStatsSave(menu.menuId);

      // if(depth == 1){
      //   this.$store.commit('setPageNaviInfo', { 'main': this.$store.state.pageNaviInfo.main , 'sub': menu.menuNm });
      // }else{
      //   this.$store.commit('setPageNaviInfo', { 'main': this.$store.state.pageNaviInfo.main , 'sub':sub.menuNm , 'third' :  menu.menuNm });
      // }


      if (menu.linkTypeNm === '0') { // 현재창
        this.$router.push({
          path: menu.routerUrl,
        });
      } else if (menu.linkTypeNm === '1') { // 새창
        window.open(menu.routerUrl, '_blank');
      }

      this.$store.commit('setCurrentMenu', menu.menuId);
    },
    isActive(subPath) {
      return this.currentPath === subPath;
    },
    // 사이트 이동
    fnSiteMove() {
      this.$router.push({
        path: "/",
      });
    },
    ...mapActions(["logout"]),
    // 로그 아웃
    async fnlogOut() {
      if (!confirm(this.$getCmmnMessage("cnf001"))) return;

      await this.logout();
      this.$router.push({
        path: "/login.page",
      });
    },
    // 캐시 초기화
    async cacheClean() {
      if (!confirm(this.$getCmmnMessage("cnf014","변경사항을 "))) return;
      const res = await cacheReSet();
      alert(res.data.message);
    },

    // 알람정보 확인 
    async alarmCheck() {
            let vm = this;
            if (store.state.authorization != null) {
                // 실행
                try {
                    const response = await findAllEvent();
                    vm.alarmList = response.data.data;
                } catch (error) {
                    const errorData = error.response.data;
                    if (errorData.message != null && errorData.message != "") {
                        //  alert(error.response.data.message);
                    } else {
                        // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                    }
                }
            }
        },

    // 알람 읽음
    async readEvent(item) {
            let vm = this;
            this.alarmModal = false;
            // 실행
            try {
                const response = await readEvent(item);
                vm.alarmList = response.data.data;
                vm.goUrl(item.url);
            } catch (error) {
                const errorData = error.response.data;
                if (errorData.message != null && errorData.message != "") {
                    alert(error.response.data.message);
                } else {
                    // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                    alert(vm.$getCmmnMessage('err005'));
                }
            }
        },

    // 전체 알람 읽음
    async readAll() {
      let vm = this;
      // 실행
      try {
        const response = await readAllEvent();
        vm.alarmList = response.data.data;
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
          alert(error.response.data.message);
        } else {
          // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
          alert(vm.$getCmmnMessage('err005'));
        }
      }
    },

    goUrl: function (url) {
        // 현재 페이지의 URL을 가져옵니다. location.href에서 도메인과 프로토콜을 제외한 path만 비교하기 위해 window.location.pathname을 사용합니다.
        var currentUrl = window.location.pathname;

        // URL 객체를 생성하여 비교를 용이하게 합니다. 이 방법은 절대 경로와 상대 경로 모두에 대응할 수 있습니다.
        var incomingUrl = new URL(url, window.location.origin).pathname;

        // 제공된 URL이 현재 페이지와 동일한 경우 페이지를 새로 고침합니다.
        if (currentUrl === incomingUrl) {
            window.location.reload();
        } else {
            // 다른 경우, 제공된 URL로 이동합니다.
            window.location.href = url;
        }
    },
  },
  watch: {
    // 나중에 네비게이션 가드에서 form 받을 수 있으면 form adm/main으로 갈때 sotre.state값0로 바꿔주기
    $route(to) {
      this.currentPath = to.path;
    },
    async "$store.state.menu"(newVal) {
      if (newVal == null || newVal == "" || newVal == undefined) {
        this.menuList = [];
      } else {
        this.menuList = newVal.childList;
        if (newVal && this.menuList.length > 0) {
          // await this.cntnStatsSave(this.menuList[0].menuId);
          this.$router.push(this.menuList[0].routerUrl);
          this.$store.commit('setCurrentMenu', this.menuList[0].menuId);
          // this.$store.commit('setPageNaviInfo', { 'main': newVal.menuNm, 'sub': this.menuList[0].menuNm });
        }
      }
    },
    "$store.state.mbrNm"(newVal) {
      this.mbrNm = newVal;
    },
  },
  computed: {},
  mounted() {
        let vm = this;
        setTimeout(function () {
            vm.alarmCheck();
        }, 500);
        this.timer = setInterval(this.alarmCheck, 5000);
    },
    beforeUnmount() {
        clearInterval(this.timer);
    } 
};
</script>
