<template>
  <div class=" w-full h-full">
      <div class="h-[calc(100%_-_58px)] border-b border-neutral-400 mb-2 scrollbar overflow-x-hidden overflow-y-auto">
        <div v-if="this.temporaryData.length === 0" class="h-full flex justify-center items-center">
          <span class="text-neutral-500">No Filter.</span>
        </div>
        <div v-else>
          <div class="text-primary h2 flex items-center justify-start my-4">
            <span class="material-symbols-outlined m-2">info</span>
            <p>Disabled filters will not be saved.</p>
          </div>
          <Timeline :value="ruleData">
            <template #content="rule">
              <div class="border-b border-neutral-300 flex justify-between items-center space-x-2">
                <!-- content -->
                <div class="pl-2 mb-2">
                  <p class="text-sm font-medium leading-5">{{ rule.item.type }}:&nbsp;<span class="text-neutral-500">{{ rule.item.label }}</span></p>
                </div>
                <!-- button -->
                <div class="min-w-fit">
                  <InputSwitch v-model="rule.item.toggle" @input="isRule($event, rule.index)"/>
                  <button type="button" class="m-2 focus:ring focus:ring-danger/20 text-neutral-500 hover:text-danger" @click.stop="deleteRule(rule.index)">
                    <span class="material-symbols-outlined">delete</span>
                  </button>
                </div>
              </div>
            </template>
          </Timeline>
        </div>
      </div>
      <!-- Button -->
      <div>
        <div class="float-right space-x-4 px-4 py-2">
          <button type="button" class="btn btn-sm " :class="[ temporaryData.length === 0 ? 'btn-disable' : 'btn-neutral']" :disabled="temporaryData.length === 0" @click="deleteRule('all')">Delete All</button>
          <button type="button" class="btn btn-sm" :class="[ temporaryData.length === 0 ? 'btn-disable' : 'btn-neutral']" :disabled="temporaryData.length === 0" @click="submitAll">Apply All</button>
        </div>
      </div>
    </div>
</template>

<script>
import { storeToRefs } from 'pinia';
import LoadingStore from '@/stores/loading.js';
import AllMapDataStore from '@/stores/allMapData.js';

export default {
  setup() {
    const loadingStore = LoadingStore();
    const allMapDataStore = AllMapDataStore();
    const { isLoading } = storeToRefs(loadingStore);
    const { hasResultRule, temporaryData, postRuleData, ruleData, isRuleData, tempFilterId } = storeToRefs(allMapDataStore);

    return { isLoading, hasResultRule, temporaryData, postRuleData, ruleData, isRuleData, allMapDataStore, tempFilterId, allMapDataStore }
  },
  methods: {
    /**
     * @param {boolean} e ture | false
     * @param {numble} index rule's index
     */
    isRule(e, index){
      let rule = this.isRuleData[index];
      // 先取得 rule object
      // 為了讓 data 順序不亂掉，將值指向 0，submitAll 時再刪掉
      if(!e) this.temporaryData[index] = 0;
      else this.temporaryData[index] = rule;
    },
    /**
     * header:Funnel 刪除全部的 Funnel
     */
    async deleteRule(index) {
      if(index === 'all') {
        this.temporaryData = [];
        this.isRuleData = [];
        this.ruleData = [];
        if(this.tempFilterId) {
          this.isLoading = true;
          this.tempFilterId = await null;
          await this.allMapDataStore.getAllMapData();
          await this.allMapDataStore.getAllTrace(); // SidebarTrace 要連動
          await this.$emit('submit-all');
          this.isLoading = false;
        }
        this.$toast.success('Filter(s) deleted.');
      }else{
        this.$toast.success(`Filter deleted.`);
        this.temporaryData.splice(index, 1);
        this.isRuleData.splice(index, 1);
        this.ruleData.splice(index, 1);
      }
    },
    /**
     * header:Funnel 發送暫存的選取資料
     */
    async submitAll() {
      this.postRuleData = this.temporaryData.filter(item => item !== 0); // 取得 submit 的資料，有 toggle button 的話，找出並刪除陣列中為 0 的項目
      if(!this.postRuleData?.length) return this.$toast.error('Not selected');
      await this.allMapDataStore.checkHasResult(); // 後端快速檢查有沒有結果

      if(this.hasResultRule === null) return;
      else if(this.hasResultRule) {
        this.isLoading = true;
        await this.allMapDataStore.addTempFilterId();
        await this.allMapDataStore.getAllMapData();
        await this.allMapDataStore.getAllTrace(); // SidebarTrace 要連動
        if(this.temporaryData[0]?.type) {
          this.allMapDataStore.traceId = await this.allMapDataStore.traces[0]?.id;
        }
        await this.$emit('submit-all');
        this.isLoading = false;
        this.$toast.success('Filter(s) applied.');
      }else {
        this.isLoading = true;
        await new Promise(resolve => setTimeout(resolve, 1000));
        this.isLoading = false;
        this.$toast.warning('No result.');
      };
    },
  }
}
</script>

<style scoped>
/* TimeLine */
:deep(.p-timeline) {
  @apply leading-none my-4
}
:deep(.p-timeline-event-opposite) {
  @apply hidden
}
:deep(.p-timeline-event-separator) {
  @apply mx-4
}
:deep(.p-timeline-event-marker) {
  @apply !bg-primary !border-primary !w-2 !h-2
}
:deep(.p-timeline-event-connector) {
  @apply !bg-primary my-2 !w-[1px]
}
:deep(.p-timeline-event-content) {
  @apply !px-0
}
</style>
