<template>
  <Sidebar v-model:visible="visibleLeft" :dismissable="true" :closeIcon="'pi pi-chevron-left'" :modal="false" position="left">
    <template #header>
      <p class="h1">Visualization Setting</p>
    </template>
    <div>
      <!-- View -->
      <div class="my-4 border-b border-neutral-200">
        <p class="h2">View</p>
        <ul class="space-y-3 mb-4">
          <!-- 選擇 bpmn / processmap button -->
          <li class="btn-toggle-content">
            <span class="btn-toggle-item" :class="mapType === 'processMap'?'btn-toggle-show  ':''" @click="switchMapType('processMap')">
              Process map
            </span>
            <span class="btn-toggle-item" :class="mapType === 'bpmn'?'btn-toggle-show':''" @click="switchMapType('bpmn')">
              BPMN Model
            </span>
          </li>
          <!-- 選擇繪畫樣式 bezier / unbundled-bezier button-->
          <li class="btn-toggle-content">
            <span class="btn-toggle-item" :class="curveStyle === 'unbundled-bezier'?'btn-toggle-show  ':''" @click="switchCurveStyles('unbundled-bezier')">
              Curved
            </span>
            <span class="btn-toggle-item" :class="curveStyle === 'taxi'?'btn-toggle-show':''" @click="switchCurveStyles('taxi')">
              Elbow
            </span>
          </li>
          <!-- 直向 TB | 橫向 LR -->
          <li class="btn-toggle-content">
            <span class="btn-toggle-item" :class="rank === 'LR'?'btn-toggle-show  ':''" @click="switchRank('LR')">
              Horizontal
            </span>
            <span class="btn-toggle-item" :class="rank === 'TB'?'btn-toggle-show':''" @click="switchRank('TB')">
              Vertical
            </span>
          </li>
        </ul>
      </div>
      <!-- Data Layer -->
      <div>
        <p class="h2">Data Layer</p>
        <ul class="space-y-2">
          <li class="flex justify-between mb-3" @change="switchDataLayerType($event, 'freq')">
            <div class="flex items-center w-1/2">
              <input type="radio" id="freq" value="freq" name="dataLayer" class="peer hidden" checked/>
              <label for="freq" class="inline-block h-4 w-4 m-2 cursor-pointer rounded-full ring-2 ring-neutral-300 shadow-sm peer-checked:ring-2 peer-checked:ring-primary peer-checked:ring-offset-2 peer-checked:bg-primary">
              </label>
              <span class="inline-block ml-2">Frequency</span>
            </div>
            <div class="w-1/2">
              <select class="border border-neutral-500 rounded p-1 w-full focus-visible:outline-primary" :disabled="dataLayerType === 'duration'">
                <option v-for="(freq, index) in selectFrequency" :key="index" :value="freq.value" :disabled="freq.disabled" :selected="freq.value === selectedFreq">{{ freq.label }}</option>
              </select>
            </div>
          </li>
          <li class="flex justify-between mb-3" @change="switchDataLayerType($event, 'duration')">
            <div class="flex items-center w-1/2">
              <input type="radio" id="duration" value="duration" name="dataLayer" class="peer hidden" />
              <label for="duration" class="inline-block h-4 w-4 m-2 cursor-pointer rounded-full ring-2 ring-neutral-300 shadow-sm peer-checked:ring-2 peer-checked:ring-primary peer-checked:ring-offset-2 peer-checked:bg-primary"></label>
              <span class="inline-block ml-2">Duration</span>
            </div>
            <div class="w-1/2">
              <select class="border border-neutral-500 rounded p-1 w-full focus-visible:outline-primary" :disabled="dataLayerType === 'freq'">
                <option v-for="(duration, index) in selectDuration" :key="index" :value="duration.value" :disabled="duration.disabled" :selected="duration.value === selectedDuration">{{ duration.label }}</option>
              </select>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <!-- 測試用 -->
      <li class="mt-20">curve style: {{ curveStyle }}</li>
      <li >map type:  {{ mapType }}</li>
      <li >rank: {{ rank }}</li>
      <li >Data Layer Type: {{ dataLayerType }}</li>
      <li >Data Layer Option: {{ dataLayerOption }}</li>
</Sidebar>

  <!-- Switch data type Sidebar -->
  <div class="flex flex-col justify-between py-4 w-14 h-screen-main absolute bottom-0 left-0 z-10" :class="visibleLeft === true? 'bg-neutral-100':''">
    <ul class="space-y-4 flex flex-col justify-center items-center">
      <li class="inline-flex items-center justify-center border border-neutral-500  rounded-full w-9 h-9 cursor-pointer bg-neutral-100" @click="visibleLeft = true">
        <span class="material-symbols-outlined text-2xl text-neutral-500">
          track_changes
        </span>
      </li>
      <li class="inline-flex items-center justify-center border border-neutral-500  rounded-full w-9 h-9 cursor-pointer bg-neutral-100">
        <span class="material-symbols-outlined text-2xl text-neutral-500">
          tornado
        </span>
      </li>
      <li class="inline-flex items-center justify-center border border-neutral-500  rounded-full w-9 h-9 cursor-pointer bg-neutral-100">
        <span class="material-symbols-outlined text-2xl text-neutral-500">
          rebase
        </span>
      </li>
    </ul>

    <ul class="flex flex-col justify-center items-center">
      <li class="inline-flex items-center justify-center border border-neutral-500  rounded-full w-9 h-9 cursor-pointer bg-neutral-100">
        <span class="material-symbols-outlined text-2xl text-neutral-500">
          highlight
        </span>
      </li>
    </ul>
  </div>

  <!-- cytoscapeMap -->
  <div class="min-w-full h-screen-main bg-neutral-100 -z-40">
    <div id="cy" class="min-w-full h-screen-main "></div>
  </div>

  <div class="bg-transparent py-4 w-14 h-screen-main z-10 bottom-0 right-0 absolute">
    <ul class="flex flex-col justify-center items-center">
      <li class="inline-flex items-center justify-center border border-neutral-500  rounded-full w-9 h-9 cursor-pointer bg-neutral-100">
        <span class="material-symbols-outlined text-2xl text-neutral-500">
          info
        </span>
      </li>
    </ul>
  </div>


</template>

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

export default {
  setup() {
    const loadingStore = LoadingStore();
    const allMapDataStore = AllMapDataStore();
    const { isLoading } = storeToRefs(loadingStore);
    const { processMap, bpmn } = storeToRefs(allMapDataStore);

    return {
      isLoading,
      processMap,
      bpmn,
      allMapDataStore,
    }
  },
  data() {
    return {
      processMapData: {
        startId: 0,
        endId: 1,
        nodes: [],
        edges: [],
      },
      bpmnData: {
        startId: 0,
        endId: 1,
        nodes: [],
        edges: [],
      },
      selectFrequency: [
        { value:"total", label:"Total", disabled:false, },
        { value:"rel_freq", label:"Relative", disabled:false, },
        { value:"average", label:"Average", disabled:false, },
        { value:"median", label:"Median", disabled:false, },
        { value:"max", label:"Max", disabled:false, },
        { value:"min", label:"Min", disabled:false, },
        { value:"cases", label:"Number of cases", disabled:false, },
      ],
      selectDuration:[
        { value:"total", label:"Total", disabled:false, },
        { value:"rel_duration", label:"Relative", disabled:false, },
        { value:"average", label:"Average", disabled:false, },
        { value:"median", label:"Median", disabled:false, },
        { value:"max", label:"Max", disabled:false, },
        { value:"min", label:"Min", disabled:false, },
      ],
      curveStyle:'unbundled-bezier', // unbundled-bezier | taxi
      mapType: 'processMap', // processMap | bpmn
      dataLayerType: 'freq', // freq | duration
      dataLayerOption: 'total',
      selectedFreq: '',
      selectedDuration: '',
      rank: 'LR', // 直向 TB | 橫向 LR
      visibleLeft: false, // SideBar
    }
  },
  methods: {
    /**
     * switch map type
     * @param {string} type processMap | bpmn
     */
    switchMapType(type) {
      this.mapType = type;
      this.createCy(type);
    },
    /**
     * switch curve style
     * @param {string} style 直角 unbundled-bezier | taxi
     */
    switchCurveStyles(style) {
      this.curveStyle = style;
      this.createCy(this.mapType);
    },
    /**
     * switch rank
     * @param {string} rank 直向 TB | 橫向 LR
     */
    switchRank(rank) {
      this.rank = rank;
      this.createCy(this.mapType);
    },
    /**
     * switch Data Layoer Type or Option.
     * @param {string} e
     * @param {string} type freq | duration
     */
    switchDataLayerType(e, type){
      let value = e.target.type === 'select-one'? e.target.value: 'total';

      switch (type) {
        case 'freq':
          this.dataLayerType = type;
          this.dataLayerOption = value;
          this.selectedFreq = value;
          break;

        case 'duration':
          this.dataLayerType = type;
          this.dataLayerOption = value;
          this.selectedDuration = value;
          break;
      };

      this.createCy(this.mapType);
    },
    /**
     * 將 element nodes 資料彙整
     * @param {object} type processMapData | bpmnData
     */
     setNodesData(mapData) {
       let mapType = this.mapType;
       const logFreq = {
        "total": "",
        "rel_freq": "",
        "average": "",
        "median": "",
        "max": "",
        "min": "",
        "cases": ""
      };
      const logDuration = {
        "total": "",
        "rel_duration": "",
        "average": "",
        "median": "",
        "max": "",
        "min": "",
      };
      // BPMN 才有 gateway 類別
      const gateway = {
        parallel: "+",
        exclusive: "x",
        inclusive: "o",
      };

      // 避免每次渲染都重複累加
      mapData.nodes = [];
      // 將 api call 回來的資料帶進 node
      this[mapType].vertices.forEach(node => {
        switch (node.type) {
          // add type of 'bpmn gateway' node
          case 'gateway':
            mapData.nodes.push({
              data:{
                id:node.id,
                type:node.type,
                label:gateway[node.gateway_type],
                height:60,
                width:60,
                backgroundColor:'#FFF',
                bordercolor:'#003366',
                shape:"diamond",
                freq:logFreq,
                duration:logDuration,
              }
            })
            break;
          // add type of 'event' node
          case 'event':
            if(node.event_type === 'start') mapData.startId = node.id;
            else if(node.event_type === 'end') mapData.endId = node.id;

            mapData.nodes.push({
              data:{
                id:node.id,
                type:node.type,
                label:node.event_type,
                height:60,
                width:60,
                backgroundColor:'#FFCCCC',
                bordercolor:'#003366',
                shape:"ellipse",
                freq:logFreq,
                duration:logDuration,
              }
            });
            break;
          // add type of 'activity' node
          default:
          mapData.nodes.push({
              data:{
                id:node.id,
                type:node.type,
                label:node.label,
                height:80,
                width:100,
                backgroundColor:'#FFCCCC',
                bordercolor:'#003366',
                shape:"round-rectangle",
                freq:node.freq,
                duration:node.duration,
              }
            })
            break;
        }
      });
     },
    /**
     * 將 element edges 資料彙整
     * @param {object} type processMapData | bpmnData
     */
    setEdgesData(mapData) {
      let mapType = this.mapType;
      //add event duration is empty
      const logDuration = {
        "total": "",
        "rel_duration": "",
        "average": "",
        "median": "",
        "max": "",
        "min": "",
        "cases": ""
      };

      mapData.edges = [];
      this[mapType].edges.map(edge => {
        mapData.edges.push({
          data: {
            source:edge.tail,
            target:edge.head,
            freq:edge.freq,
            duration:edge.duration === null ? logDuration : edge.duration,
            style:'dotted',
            lineWidth:1,
          },
        });
      });
     },
    /**
     * get api data
     */
    async executeApi() {
      await this.allMapDataStore.getAllMapData();
      this.createCy(this.mapType);
    },
    /**
     * create cytoscape's map
     * @param {string} type this.mapType processMap | bpmn
     */
    createCy(type) {
      let graphId = document.getElementById('cy');
      let mapData = type === 'processMap'? this.processMapData: this.bpmnData;

      if(this[type].vertices.length !== 0){
        this.setNodesData(mapData);
        this.setEdgesData(mapData);
        cytoscapeMap(mapData, this.dataLayerType, this.dataLayerOption, this.curveStyle, this.rank, graphId);
      };
    },
  },
  created() {
    this.allMapDataStore.logId = this.$route.params.logId;
  },
  mounted() {
    this.isLoading = false;
    this.executeApi();
  },
}
</script>

<style>
.p-sidebar-left {
  @apply ml-14
}
.p-sidebar-mask {
  height: calc(100vh - 104px) !important;
  top: 104px !important;
}
.p-sidebar {
  @apply !shadow-[1px_0px_4px_rgba(0,0,0,0.25)]
}
.p-sidebar-header {
  @apply bg-neutral-200 border-b border-neutral-300 !py-2 !justify-between
};
</style>
