<template>
  <nav class="bg-neutral-700">
    <div class="mx-auto px-4" :class="[showNavbarBreadcrumb? 'min-h-12': 'h-12']">
      <div class="flex justify-between items-center flex-wrap" v-show="showNavbarBreadcrumb">
        <div class="flex flex-1 items-center">
          <!-- 回 Files 頁 -->
          <router-link to="/files" class="mr-4" v-if="showIcon" id="backPage">
            <span class="material-symbols-outlined text-neutral-10 !leading-loose">
              arrow_back
            </span>
          </router-link>
          <h2 class="mr-14 py-3 text-2xl font-black text-neutral-10">{{ navViewName }}</h2>
          <ul class="flex justify-center items-center space-x-4 text-xl font-semibold text-neutral-300 cursor-pointer">
            <li @click="switchNavItem($event, item)" v-for="(item, index) in navViewData[navViewName]" :key="index" :class="{'active': isActive === item}">{{ item }}</li>
          </ul>
        </div>
        <!-- Files Page: Search and Upload -->
        <div class="flex justify-end items-center" v-if="navViewName === 'FILES'">
          <!-- <form role="search">
            <label for="searchFiles" class="mr-4 relative">
              <input type="search" id="searchFiles" placeholder="Search" class="px-5 py-2 w-72 rounded-full text-sm align-middle duration-300 border border-neutral-500 hover:border-neutral-300 focus:outline-none focus:ring focus:border-neutral-300">
              <span class="absolute top-2 bottom-1.5 right-0.5 flex justify-center items-center gap-2">
                <IconSetting class="w-6 h-6 cursor-pointer"></IconSetting>
                <span class="w-px h-6 block after:border after:border-neutral-300 after:content-['']"></span>
                <button class="pr-2">
                  <IconSearch class="w-6 h-6"></IconSearch>
                </button>
              </span>
            </label>
          </form> -->
          <!-- <label class="btn btn-sm btn-neutral cursor-pointer">
            <input id="uploadFiles" class="hidden" type="file">
            Upload
          </label> -->
          <div class="btn btn-sm btn-neutral cursor-pointer" @click="uploadModal = true">
            Upload
            <UploadModal :visible="uploadModal" @closeModal="uploadModal = $event"></UploadModal>
          </div>
        </div>
        <!-- Upload, Performance, Compare 無按鈕行為 -->
        <div v-else-if="noShowSaveButton"></div>
        <!-- Other Page: Save and Download -->
        <!-- Save 有 data 跳重新命名，沒有 data 跳要不要儲存，沒有動都不跳 -->
        <div v-else class="space-x-4">
          <button class="btn btn-sm" :class="[ disabledSave ? 'btn-disable' : 'btn-neutral']" :disabled="disabledSave" @click="saveModal">Save</button>
          <!-- <button class="btn btn-sm btn-neutral">Download</button> -->
        </div>
      </div>
    </div>
  </nav>
</template>

<script>
import { storeToRefs } from 'pinia';
import filesStore from '@/stores/files.js';
import AllMapDataStore from '@/stores/allMapData.js';
import ConformanceStore from '@/stores/conformance.js';
import IconSearch from '@/components/icons/IconSearch.vue';
import IconSetting from '@/components/icons/IconSetting.vue';
import { saveFilter, savedSuccessfully, saveConformance } from '@/module/alertModal.js';
import UploadModal from './File/UploadModal.vue';

export default {
  setup() {
    const store = filesStore();
    const allMapDataStore = AllMapDataStore();
    const conformanceStore = ConformanceStore();
    const { logId, tempFilterId, createFilterId, filterName, postRuleData, isUpdataFilter } = storeToRefs(allMapDataStore);
    const { conformanceRuleData, conformanceLogId, conformanceFilterId, conformanceLogTempCheckId, conformanceFilterTempCheckId, conformanceLogCreateCheckId, conformanceFilterCreateCheckId, isUpdataConformance, conformanceFileName } = storeToRefs(conformanceStore);

    return { store, allMapDataStore, logId, tempFilterId, createFilterId, filterName, postRuleData, isUpdataFilter, conformanceStore, conformanceRuleData, conformanceLogId, conformanceFilterId, conformanceLogTempCheckId, conformanceFilterTempCheckId, conformanceLogCreateCheckId, conformanceFilterCreateCheckId, isUpdataConformance, conformanceFileName }
  },
  components: {
    IconSearch,
    IconSetting,
    UploadModal,
  },
  data() {
    return {
      showNavbarBreadcrumb: false,
      navViewData:
      {
        // FILES: ['ALL', 'DISCOVER', 'COMPARE', 'DESIGN'],
        FILES: ['ALL', 'DISCOVER', 'COMPARE'],
        // DISCOVER: ['MAP', 'CONFORMANCE', 'PERFORMANCE', 'DATA']
        DISCOVER: ['MAP', 'CONFORMANCE', 'PERFORMANCE'],
        // COMPARE: ['PROCESS MAP', 'DASHBOARD']
        COMPARE: ['DASHBOARD']
      },
      navViewName: 'FILES',
      isActive: null,
      uploadModal: false,
    };
  },
  computed: {
    disabledSave: function () {
      switch (this.$route.name) {
        case 'Map':
        case 'CheckMap':
          // 沒有 filter Id, 沒有暫存 tempFilterId Id 就不能存檔
          return this.tempFilterId ? false : true;
        case 'Conformance':
        case 'CheckConformance':
          return this.conformanceFilterTempCheckId || this.conformanceLogTempCheckId ? false : true;
      }
    },
    showIcon: function() {
      let result = true;

      result = ['FILES', 'UPLOAD'].includes(this.navViewName) ? false : true;
      return result;
    },
    noShowSaveButton: function() {
      return this.navViewName === 'UPLOAD' || this.navViewName === 'COMPARE' || this.isActive === 'PERFORMANCE' ? true : false;
    }
  },
  watch: {
    '$route':'getNavViewName',
    filterName: function(newVal, oldVal) {
      this.filterName = newVal;
    },
  },
  mounted() {
    if(this.$route.params.type === 'filter') this.createFilterId= this.$route.params.fileId;
    this.showNavbarBreadcrumb = this.$route.matched[0].name !== ('AuthContainer') ? true : false;
    this.getNavViewName();
  },
  methods: {
    /**
     * switch navbar item
     */
    switchNavItem(event) {
      let type;
      let fileId;

      this.isActive = event.target.innerText;
      switch (this.navViewName) {
        case 'FILES':
          this.store.filesTag = event.target.innerText;
          break;
        case 'DISCOVER':
          type = this.$route.params.type;
          fileId = this.$route.params.fileId;

          switch (event.target.innerText) {
            case 'MAP':
              if(type === 'rule') this.$router.push({name: 'CheckMap'});
              else this.$router.push({name: 'Map', params: { type: type, fileId: fileId }});
              break;
            case 'CONFORMANCE':
              if(type === 'rule') this.$router.push({name: 'CheckConformance'});
              else this.$router.push({name: 'Conformance', params: { type: type, fileId: fileId }});
              break
            case 'PERFORMANCE':
              if(type === 'rule') {
                type = this.$route.params.checkType;
                fileId = this.$route.params.checkFileId;
              }
              this.$router.push({name: 'Performance', params: { type: type, fileId: fileId }});
              break;
          }
          break;
        case 'COMPARE':
          break
      }
    },
    getNavViewName() {
      let name = this.$route.name;

      if(this.$route.name === 'NotFound404') return;
      this.navViewName = this.$route.matched[1].name.toUpperCase();
      this.store.filesTag = 'ALL';
      switch (this.navViewName) {
        case 'FILES':
          this.isActive = this.store.filesTag;
          break;
        case 'DISCOVER':
          switch (name) {
            case 'Map':
            case 'CheckMap':
              this.isActive = 'MAP';
              break;
            case 'Conformance':
            case 'CheckConformance':
              this.isActive = 'CONFORMANCE';
              break;
            case 'Performanc':
              this.isActive = 'PERFORMANCE';
              break;
          }
          break;
        case 'COMPARE':
          switch(name) {
            case 'CompareDashboard':
              this.isActive = 'DASHBOARD'
              break;
          }
          break;
      }
      // if(this.navViewName === 'DISCOVER') {
      //   if(name === 'Map' || name === 'CheckMap') this.isActive = 'MAP';
      //   else if(name === 'Conformance' || name === 'CheckConformance') this.isActive = 'CONFORMANCE';
      // }
    },
    /**
     * Save button' modal
     */
    async saveModal() {
      // 傳給 Map，通知 Sidebar 要關閉。
      this.$emitter.emit('saveModal', false);
      // 判斷在哪個子頁面
      switch (this.$route.name) {
        case 'Map':
          // 先判斷有沒有 filter Id，有就儲存 return，沒有就往下走
          // 沒有 filter Id, 有暫存 tempFilterId Id 可以另存新檔
          if(this.createFilterId) {
            await this.allMapDataStore.updataFilter();
            if(this.isUpdataFilter) await savedSuccessfully(this.filterName);
          }else if(this.logId){
            await saveFilter(this.allMapDataStore.addFilterId);
            // 存檔後為 filterID，換網址不跳頁，使用 push 記錄歷史路由
            await this.$router.push(`/discover/map/filter/${this.createFilterId}`);
          };
          break;
        case 'CheckMap':
          // 無論 parentLog, parentFilter，做新 filter 皆另存新檔
          await saveFilter(this.allMapDataStore.addFilterId);
          // 存檔後為 filterID，換網址不跳頁，使用 push 記錄歷史路由
          await this.$router.push(`/discover/map/filter/${this.createFilterId}`);
        case 'Conformance':
        case 'CheckConformance':
          // 先判斷有沒有 check Id，有就儲存 return，沒有就往下走
          // 沒有 check Id, 有暫存 temp Id 可以另存新檔
          if(this.conformanceFilterCreateCheckId || this.conformanceLogCreateCheckId){
            await this.conformanceStore.updataConformance();
            if(this.isUpdataConformance) await savedSuccessfully(this.conformanceFileName);
          } else {
            await saveConformance(this.conformanceStore.addConformanceCreateCheckId);
            // 存檔後為 checkID，換網址不跳頁，使用 push 記錄歷史路由
            if(this.conformanceLogId) await this.$router.push(`/rule/log/${this.conformanceLogCreateCheckId}/conformance/${this.conformanceLogId}`);
            else if(this.conformanceFilterId) await this.$router.push(`/rule/filter/${this.conformanceFilterCreateCheckId}/conformance/${this.conformanceFilterId}`);
          }
          break;
      }
    }
  },
}
</script>

<style scoped>
#searchFiles::-webkit-search-cancel-button{
  appearance: none;
}
</style>
