<template>
    <div id="account_menu" v-if="isAcctMenuOpen" class="absolute top-0 w-[232px] bg-white right-[0px] rounded shadow-lg bg-[#ffffff]">
        <div id="greeting" class="w-full border-b border-[#CBD5E1]">
          <span class="m-4 h-[48px]">
          {{ i18next.t("AcctMgmt.hi") }}{{ userData.name }}
          </span>
        </div>
        <ul class="w-full min-h-10">
          <!-- 這裡不使用迴圈是因為src值用變數的話會沒辦法顯示svg -->
        <li v-if="isAdmin" id="btn_acct_mgmt"
          class="w-full h-[40px] flex py-2 px-4 hover:text-[#000000] hover:bg-[#F1F5F9] cursor-pointer
          items-center" @click="onBtnAcctMgmtClick">          
            <span class="w-[24px] h-[24px] flex"><img src="@/assets/icon-crown.svg" alt="accountManagement"></span>
            <span class="flex ml-[8px]">{{i18next.t("AcctMgmt.acctMgmt")}}</span>
        </li>
        <li id="btn_mang_ur_acct"
          class="w-full h-[40px] flex py-2 px-4 hover:text-[#000000] hover:bg-[#F1F5F9] cursor-pointer
          items-center">
            <span class="w-[24px] h-[24px] flex"><img src="@/assets/icon-head-black.svg" alt="head-black"></span>
            <span class="flex ml-[8px]">{{i18next.t("AcctMgmt.mangUrAcct")}}</span>
        </li>
        <li id="btn_logout_in_menu"
          class="w-full h-[40px] flex py-2 px-4 hover:text-[#000000] hover:bg-[#F1F5F9] cursor-pointer
          items-center" @click="onLogoutBtnClick">
            <span class="w-[24px] h-[24px] flex"><img src="@/assets/icon-logout.svg" alt="logout"></span>
            <span class="flex ml-[8px]">{{i18next.t("AcctMgmt.Logout")}}</span>
        </li>
        </ul>
    </div>
</template>

<script>
import { computed, onMounted, ref, } from 'vue';
import { mapActions, mapState, storeToRefs } from 'pinia';
import i18next from '@/i18n/i18n';
import LoginStore from '@/stores/login.ts';
import AcctMgmtStore from '@/stores/acctMgmt.ts';
import AllMapDataStore from '@/stores/allMapData.js';
import ConformanceStore from '@/stores/conformance.js';
import { leaveFilter, leaveConformance } from '@/module/alertModal.js';

export default {
  setup() {
    const { logOut } = LoginStore();
    const loginStore = LoginStore();
    const allMapDataStore = AllMapDataStore();
    const conformanceStore = ConformanceStore();
    const acctMgmtStore = AcctMgmtStore();
    const { tempFilterId } = storeToRefs(allMapDataStore);
    const { conformanceLogTempCheckId } = storeToRefs(conformanceStore);

    const loginUserData = ref(null);
    const currentViewingUserDetail = computed(() => acctMgmtStore.currentViewingUser.detail);
    const isAdmin = ref(false);

    const getIsAdminValue = async () => {
        await loginStore.getUserData();
        loginUserData.value = loginStore.userData;
        await acctMgmtStore.getUserDetail(loginUserData.value.username);
        if(currentViewingUserDetail.value.roles.find(role => role.code === 'admin')) {
          isAdmin.value = true;
        }
      };

    onMounted(async () => { 
        await getIsAdminValue();
    });
    
    return {
      logOut,
      tempFilterId,
      conformanceLogTempCheckId,
      allMapDataStore,
      conformanceStore,
      isAdmin,
    };
  },
  data() {
    return {
      i18next: i18next,
    }
  },
  computed: {
    ...mapState(LoginStore, ['userData']),
    ...mapState(AcctMgmtStore, ['isAcctMenuOpen']),
  },
  methods: {
    clickOtherPlacesThenCloseMenu(){
      const acctMgmtButton = document.getElementById('acct_mgmt_button');
      const acctMgmtMenu = document.getElementById('account_menu');

      document.addEventListener('click', (event) => {
          if (!acctMgmtMenu.contains(event.target) && !acctMgmtButton.contains(event.target)) {
            this.closeAcctMenu();
          }
      });
    },
    onBtnAcctMgmtClick(){
      this.$router.push({name: 'AcctAdmin'});
      this.closeAcctMenu();
    },
    onLogoutBtnClick(){
      if ((this.$route.name === 'Map' || this.$route.name === 'CheckMap') && this.tempFilterId) {
        // 傳給 Map，通知 Sidebar 要關閉。
        this.$emitter.emit('leaveFilter', false);
        leaveFilter(false, this.allMapDataStore.addFilterId, false, this.logOut)
      } else if((this.$route.name === 'Conformance' || this.$route.name === 'CheckConformance')
        && (this.conformanceLogTempCheckId || this.conformanceFilterTempCheckId)) {
        leaveConformance(false, this.conformanceStore.addConformanceCreateCheckId, false, this.logOut)
      } else {
        this.logOut();
      }
    },
    ...mapActions(LoginStore, ['getUserData']),
    ...mapActions(AcctMgmtStore, ['closeAcctMenu']),
  },
  created() {
    this.getUserData();
  },
  mounted(){
    this.clickOtherPlacesThenCloseMenu();
  },
};
</script>

<style>
#account_menu {
  z-index: 2147483648;
}
</style>