<template>
  <q-expansion-item
    v-if="children && children.length > 0"
    expand-separator
    default-opened
    :label="title"
    :caption="caption"
    switch-toggle-side
  >
    <q-item
      clickable
      active-class="bg-primary-bg-light"
      v-for="item in children"
      @click="expansionClick(item)"
      :key="item.link"
      :active="pageStore.activeRouter?.path === item.link ? true : false"
    >
      <q-item-section v-if="item.icon" avatar>
        <q-avatar size="md" square>
          <img :src="item.icon" />
        </q-avatar>
      </q-item-section>
      <q-item-section>
        <q-item-label>{{ item.title }}</q-item-label>
        <q-item-label caption v-if="item.caption">{{
          item.caption
        }}</q-item-label>
      </q-item-section>
    </q-item>
  </q-expansion-item>

  <q-item
    v-else
    clickable
    @click="onClick"
    :active="pageStore.activeRouter?.path === link ? true : false"
    active-class="bg-primary-bg-light"
  >
    <q-item-section v-if="icon" avatar>
      <q-avatar size="md" square>
        <img :src="icon" />
      </q-avatar>
    </q-item-section>

    <q-item-section>
      <q-item-label>{{ title }}</q-item-label>
      <q-item-label caption v-if="caption">{{ caption }}</q-item-label>
    </q-item-section>
  </q-item>
</template>

<script lang="ts">
import { defineComponent, PropType, reactive, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import { usePageStore } from 'src/common/hooks';
import { EssentialLinkType } from 'src/components/models';

export default defineComponent({
  name: 'EssentialLink',
  props: {
    active: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      required: true,
    },
    caption: {
      type: String,
      default: '',
    },
    link: {
      type: String,
      default: '#',
    },
    icon: {
      type: String,
      default: '',
    },
    children: {
      type: Array as PropType<EssentialLinkType[]>,
      default: () => [],
    },
  },
  setup(props) {
    const pageStore = usePageStore();
    const router = useRouter();
    const state = reactive({
      //
    });
    const onClick = () => {
      const currentRouter = router.currentRoute.value.path;
      if (currentRouter === props.link) return;
      router.push(props.link);
    };
    const expansionClick = (params: EssentialLinkType) => {
      const currentRouter = router.currentRoute.value.path;
      if (currentRouter === params.link) return;
      router.push(params.link as string);
    };
    return {
      ...toRefs(state),
      onClick,
      expansionClick,
      pageStore,
    };
  },
});
</script>
