<template>
  <div class="editor-preview">
    <div v-if="!showPreview ||!selectedPage" class="preview-empty">请选择页面进行预览</div>
    <template v-else>
      <component
        :is="previewComponent"
        v-bind="previewProps"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import { provide, computed, toRef, markRaw, type Component, ref, watch } from 'vue';
import { COMMON_CATEGORY_KEY } from '../../CommonCategoryGlobalLoader';
import type { IHomeCommonCategoryDefine } from '../../CommonCategoryDefine';
import HomePage from '@/pages/home/index.vue';
import CommonArticleDetail from '@/pages/article/details.vue';
import CommonCategoryList from '@/pages/article/data/CommonCategoryList.vue';
import CommonCategoryDetail from '@/pages/article/data/CommonCategoryDetail.vue';
import { ObjectUtils, waitTimeOut } from '@imengyu/imengyu-utils';

const props = defineProps<{
  editorJson: IHomeCommonCategoryDefine;
  selectedPage: IHomeCommonCategoryDefine['page'][0] | null;
  testDetailId: number;
}>();

// 注入当前编辑的 JSON，供预览中的 home/list 通过 injectCommonCategory() 读取
const editorJsonRef = ref(props.editorJson);
const showPreview = ref(true);

provide(COMMON_CATEGORY_KEY, editorJsonRef);

watch(() => props.editorJson, (newJson) => {
  editorJsonRef.value = ObjectUtils.clone(newJson);
}, { deep: true, immediate: true });

const previewComponent = computed<Component | null>(() => {
  const page = props.selectedPage;
  if (!page?.content) 
    return null;
  const type = page.content.type;
  switch (type) {
    case 'Home':
      return markRaw(HomePage);
    case 'CommonList':
      return markRaw(CommonCategoryList);
    case 'Details':
      return markRaw(CommonCategoryDetail);
    case 'CommonDetails':
      return markRaw(CommonArticleDetail);
    default:
      console.error('未知页面类型:', type);
      return null;
  }
});

const previewProps = computed(() => {
  const page = props.selectedPage;
  if (!page) return {};
  if (page.content.type === 'CommonList') {
    return {
      pageConfigName: page.name,
      pageStartTab: 0,
      pageQuerys: {},
    };
  }
  if (page.content.type === 'Details') {
    return {
      pageConfigName: page.name,
      pageQuerys: {
        id: props.testDetailId,
      },
    };
  }
  return {};
});

defineExpose({
  refresh: async () => {
    showPreview.value = false;
    await waitTimeOut(100);
    showPreview.value = true;
  },
});
</script>

<style scoped>
.editor-preview {
  position: relative  ;
  width: 100%;
  height: 100%;
  overflow: hidden;
  overflow-y: scroll;
}
.preview-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 200px;
  color: #999;
  font-size: 14px;
}
</style>
