<template>
  <div class="vue-page">
    <div v-if="loading" class="loading-wrapper">
      <a-spin tip="加载中..." />
    </div>
    <div v-else-if="error" class="error-wrapper">
      <a-result
        status="error"
        title="渲染失败"
        :sub-title="error"
      />
    </div>
    <div v-else class="container-wrapper">
      <VueSfcComponent :value="code" :globalProp="globalProp"/>
    </div>
  </div>
</template>

<script>
import VueSfcComponent from '@vue2-client/base-client/components/VueSfcComponent/VueSfcComponent'
import { getConfigByNameAsync } from '@vue2-client/services/api/common'

export default {
  name: 'VuePage',
  components: {
    VueSfcComponent
  },
  data() {
    return {
      code: '',
      loading: true,
      error: '',
      globalProp: {}
    }
  },
  mounted() {
    this.loadCode()
  },
  methods: {
    async loadCode() {
      try {
        const searchParams = new URLSearchParams(window.location.search)
        const codeParam = searchParams.get('code')
        const configName = searchParams.get('configName') || this.$route.meta.configName
        const serviceName = searchParams.get('serviceName') || this.$route.meta.serviceName

        if (codeParam) {
          this.code = decodeURIComponent(codeParam)
          this.globalProp = {
            name: 'urlCode',
            namespaceName: 'urlCode',
            version: Date.now()
          }
        } else if (configName) {
          const config = await getConfigByNameAsync(configName, serviceName || undefined)
          if (!config || !config.source) {
            this.error = '配置内容为空'
            return
          }
          this.globalProp = config.$globalProp
          this.code = typeof config.source === 'string' ? config.source : JSON.stringify(config.source)
        } else {
          this.error = '未提供预览代码或配置名称'
        }
      } catch (e) {
        this.error = '代码解析失败: ' + e.message
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.vue-page {
  height: 100%;
  .loading-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
  .error-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
  .container-wrapper {
    height: 100%;
  }
}
</style>
