<template>
  <FlexCol>
    <FlexCol v-if="errorMessage" :padding="30" :gap="30" center height="100%">
      <Result status="error" :description="errorMessage" />
      <Button type="primary" @click="loadPageConfig">重新加载</Button>
    </FlexCol>
    <CommonCategoryListBlock
      v-else-if="currentCommonCategoryDefine && currentCommonCategoryContentDefine"
      :currentCommonCategoryDefine="currentCommonCategoryDefine"
      :currentCommonCategoryContentDefine="currentCommonCategoryContentDefine"
      :pageStartTab="pageStartTab"
      :pageQuerys="pageQuerys"
      @error="errorMessage = $event"
    />
    <LoadingPage v-else />
  </FlexCol>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { injectCommonCategory } from './CommonCategoryGlobalLoader';
import { type IHomeCommonCategoryDefine, type IHomeCommonCategoryListDefine } from './CommonCategoryDefine';
import Result from '@/components/feedback/Result.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';
import Button from '@/components/basic/Button.vue';
import CommonCategoryListBlock from './CommonCategoryListBlock.vue';
import { getIsDevtoolsPlatform } from '@/common/utils/MpVersions';
import { waitTimeOut } from '@imengyu/imengyu-utils';

/**
 * 动态通用内容 - 通用列表页
 */

const errorMessage = ref('');
const currentCommonCategoryDefine = ref<IHomeCommonCategoryDefine['page'][0]>();
const currentCommonCategoryContentDefine = ref<IHomeCommonCategoryListDefine>();
const commonCategory = injectCommonCategory();

const props = defineProps({
  pageConfigName: {
    type: String,
    default: '',
  },
  pageStartTab: {
    type: Number,
    default: 0,
  },
  pageQuerys: {
    type: Object as () => Record<string, string|number|number[]|undefined>,
    default: () => ({}),
  },
});

async function loadPageConfig() {
  if (!props.pageConfigName) {
    errorMessage.value = '配置有误';
    return;
  }
  currentCommonCategoryDefine.value = commonCategory.value.page.find((item) => item.name === props.pageConfigName);
  if (!currentCommonCategoryDefine.value) {
    await waitTimeOut(1000);
    currentCommonCategoryDefine.value = commonCategory.value.page.find((item) => item.name === props.pageConfigName);
  }
  if (!currentCommonCategoryDefine.value) {
    errorMessage.value = '未找到指定的分类配置：' + props.pageConfigName;
    return;
  }
  if (currentCommonCategoryDefine.value.content.type !== 'CommonList') {
    errorMessage.value = '分类配置：' + props.pageConfigName + ' 不是列表类型';
    return;
  }
  currentCommonCategoryContentDefine.value = 
    currentCommonCategoryDefine.value.content as IHomeCommonCategoryListDefine;
  uni.setNavigationBarTitle({
    title: currentCommonCategoryDefine.value?.title || '',
  })
}

watch(() => props.pageConfigName, loadPageConfig);
onMounted(loadPageConfig);
</script>