<template>
  <SimplePageListContentLoader class="d-flex flex-col mt-3 flex-fill" :loader="loader">
    <Tab v-if="mainBodyColumnAsTabs" v-model="activeSubTab" :tabs="mainBodyColumnAsTabs.map(p => ({ label: p }))" autoSize />
    <GridList 
      class="flex-fill"
      :list="loader.list.value"
      :defaultImage="defaultImage" 
      :playAudio="detailPageName === 'Play'"
      @itemClick="handleClick"
    />
    <SimplePageListContentPager :loader="loader" />
  </SimplePageListContentLoader>
</template>

<script setup lang="ts">
import { useSimplePagerDataLoader } from '@/composeable/SimplePagerDataLoader';
import { useRouter } from 'vue-router';
import { computed, ref, watch, type PropType } from 'vue';
import CommonContent, { GetContentListItem, GetContentListParams } from '@/api/CommonContent';
import SimplePageListContentLoader from '@/components/SimplePageListContentLoader.vue';
import SimplePageListContentPager from '@/components/SimplePageListContentPager.vue';
import GridList from '@/components/small/GridList.vue';
import Tab from '@/components/small/Tab.vue';

const props = defineProps({
  modelId: {
    type: Number,
    default: undefined,
  },
  mainBodyColumnId: {
    type: [Number,Array],
    default: undefined,
  },
  mainBodyColumnAsTabs: {
    type: Array as PropType<string[]>,
    default: undefined,
  },
  detailPageNames: {
    type: [String, Array],
    default: undefined,
  },
  defaultImage: {
    type: String,
    default: undefined,
  },
})

const emit = defineEmits(['itemClick']);
const activeSubTab = ref(0);
const router = useRouter();
const loader = useSimplePagerDataLoader(16, async (page, size) => {
  let modelId = props.modelId as number;
  let mainBodyColumnId = props.mainBodyColumnId as number | 
    number[] | 
    { modelId: number, mainBodyColumnId: number | number[] }[]
  ;
  if (Array.isArray(mainBodyColumnId) && props.mainBodyColumnAsTabs) {
    const item = mainBodyColumnId[activeSubTab.value];
    if (typeof item === 'object' && item.modelId && item.mainBodyColumnId) {
      modelId = item.modelId;
      mainBodyColumnId = item.mainBodyColumnId;
    } else
      mainBodyColumnId = item as number
  }
  return CommonContent.getContentList(new GetContentListParams()
    .setModelId(modelId)
    .setMainBodyColumnId(mainBodyColumnId as number)
  , page, size)
});
const detailPageName = computed(() => {
  let detailPageNames = props.detailPageNames as string|string[];
  if (!detailPageNames)
    detailPageNames = 'ArticleDetail';
  if (Array.isArray(detailPageNames))
    detailPageNames = detailPageNames[activeSubTab.value];
  return detailPageNames;
})

watch(activeSubTab, () => loader.loadData(undefined, true))

function handleClick(item: GetContentListItem) {
  if (detailPageName.value === 'Custom') {
    emit('itemClick', item);
    return;
  }
  router.push({
    name: detailPageName.value,
    query: {
      id: item.id,
    }
  })
}
</script>