<template>
  <div v-if="state.isReload && state.pageType === PageTemplateType.GRID" :class="props.configId ? 'pt-2.5' : ''" style="height: 100%">
    <GridPage
      ref="gridPageRef"
      :platform-grid-config="state.pageConfig"
      :grid-before-request-data="gridBeforeRequestData"
      :grid-before-editor-data-submit="gridBeforeEditorDataSubmit"
    ></GridPage>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, nextTick, watch } from 'vue';
import { useRoute } from 'vue-router';
import { axios, Environment } from 'platform-core';

import { getPageConfig, PageTemplateType, Page } from './page.ts';
import GridPage from './grid/GridPage.vue';

const gridPageRef = ref();
const props = defineProps({
  configId: { type: String, default: '' },
  gridBeforeRequestData: { type: Function, default: () => {} },
  gridBeforeEditorDataSubmit: { type: Function, default: () => {} },
  gridInitLoadData: { type: Boolean, default: false },
});

const route = useRoute();
const state = reactive({
  isReload: true,
  pageType: '',
  pageConfig: {},
});

watch(
  () => props.configId,
  (newVal, oldVal) => {
    reload();
  },
);

const reload = () => {
  state.isReload = false;
  nextTick(() => {
    state.isReload = true;
    getConfig();
  });
};

const getJsonStr = async () => {
  // 两种接收参数的方式，一种是页面嵌套该组件为子组件，将configId传进来，另一种是通过路由将参数传进来。
  const result = await getPageConfig((props.configId ? props.configId : route.query.id) as string);
  if (result) {
    state.pageConfig = eval('(' + result.config + ')');
    state.pageType = result.type;
  }
};

const getConfig = async () => {
  const resp = await axios.get(Environment.apiContextPath('api/template/config/fetch/') + (props.configId ? props.configId : route.query.id));
  if (resp && resp.data && resp.data.templateConfig?.templatePageLoadType === 'JSON') {
    getJsonStr();
  } else if (resp && resp.data) {
    const templateConfig = resp.data.templateConfig;
    const templateGrid = resp.data.templateGrid;
    const templateGridFields = resp.data.templateGridFields;

    state.pageType = templateConfig.templateType;
    // 根据配置组装数据对象
    const page = new Page(templateConfig, templateGrid, templateGridFields);
    state.pageConfig = page.buildGridConfig();
  }
};

const refresh = () => {
  gridPageRef.value.refresh();
};

onMounted(async () => {
  await getConfig();
  if (props.gridInitLoadData) {
    gridPageRef.value.refresh();
  }
});

defineExpose({
  refresh,
});
</script>
