<script>
import { getConfigByNameAsync } from '@vue2-client/services/api/common'
import { loadModule } from 'vue3-sfc-loader/vue2'
import { VueSfcModuleCache } from '@vue2-client/utils/module-loader'

export default {
  name: 'CloudVueSfcComponent',
  props: {
    configName: {
      type: String,
      required: true
    },
    serviceName: {
      type: String,
      default: process.env.VUE_APP_SYSTEM_NAME
    }
  },
  data() {
    return {
      componentDefinition: null,
      loading: false,
      error: null,
      injectedStyles: []
    }
  },
  computed: {
    previewStyles() {
      return {
        width: '100%',
        height: '100%',
        overflow: 'auto'
      }
    }
  },
  created() {
    this.loadSfcFromCloud()
  },
  beforeDestroy() {
    this.cleanupInjectedStyles()
  },
  methods: {
    cleanupInjectedStyles() {
      if (this.injectedStyles && this.injectedStyles.length > 0) {
        this.injectedStyles.forEach(style => {
          if (style.parentNode) {
            style.parentNode.removeChild(style)
          }
        })
        this.injectedStyles = []
      }
    },

    /**
     * 刷新组件 - 重新从云端获取并渲染
     */
    refresh() {
      this.loadSfcFromCloud()
    },

    /**
     * 从云端加载 SFC
     */
    async loadSfcFromCloud() {
      this.loading = true
      this.error = null
      this.cleanupInjectedStyles()

      try {
        // 1. 获取云端配置
        const config = await getConfigByNameAsync(this.configName, this.serviceName)

        if (!config || !config.source) {
          this.error = '配置内容为空'
          this.componentDefinition = null
          return
        }

        const sfcCode = typeof config.source === 'string' ? config.source : JSON.stringify(config.source)

        if (!sfcCode || !sfcCode.trim()) {
          this.error = '配置内容为空'
          this.componentDefinition = null
          return
        }

        // 2. 获取 moduleCache
        const moduleCache = VueSfcModuleCache.toObject()

        // 3. 准备编译选项
        const timestamp = Date.now()
        const virtualUrl = `cloud-sfc.vue?t=${timestamp}`

        const options = {
          moduleCache,
          getFile: (url) => {
            if (url.startsWith('cloud-sfc.vue')) {
              return {
                getContentData: (asBinary) => asBinary ? null : sfcCode,
                type: '.vue'
              }
            }
            console.warn('[CloudVueSfcComponent] getFile 被非 cloud-sfc 路径调用:', url)
            return {
              getContentData: () => null,
              type: ''
            }
          },
          addStyle: (textContent) => {
            const style = document.createElement('style')
            style.textContent = textContent
            document.head.appendChild(style)
            this.injectedStyles.push(style)
          }
        }

        // 4. 编译 SFC
        const component = await loadModule(virtualUrl, options)

        if (component && typeof component === 'object') {
          this.componentDefinition = component
        } else {
          this.error = '组件加载失败，返回结果为空'
          this.componentDefinition = null
        }
      } catch (e) {
        console.error('[CloudVueSfcComponent] 加载错误:', e)
        this.error = this.formatError(e)
        this.componentDefinition = null
      } finally {
        this.loading = false
      }
    },

    formatError(e) {
      if (e.message) {
        return e.message.replace(/https?:\/\/[^\s]+/g, '').trim() || '组件渲染失败'
      }
      if (typeof e === 'string') {
        return e
      }
      return '组件渲染失败'
    }
  },
  render(h) {
    if (this.loading) {
      return h('div', {
        class: 'cloud-vue-sfc-component',
        style: this.previewStyles
      }, [
        h('div', {
          class: 'loading-wrapper',
          style: { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }
        }, [
          h('a-spin', { props: { size: 'large' } }),
          h('span', { style: { marginLeft: '12px', color: '#666' } }, '正在加载云端组件...')
        ])
      ])
    }

    if (this.error) {
      return h('div', {
        class: 'cloud-vue-sfc-component',
        style: this.previewStyles
      }, [
        h('div', {
          class: 'error-wrapper',
          style: { padding: '16px', color: '#f5222d' }
        }, [
          h('a-icon', { props: { type: 'close-circle', theme: 'filled', style: { fontSize: '20px', marginRight: '8px' } } }),
          h('span', { style: { fontWeight: '500' } }, '加载错误'),
          h('pre', {
            style: {
              marginTop: '8px',
              padding: '12px',
              background: '#fff2f0',
              borderRadius: '4px',
              fontSize: '12px',
              whiteSpace: 'pre-wrap',
              wordBreak: 'break-all'
            }
          }, this.error),
          h('a-button', {
            props: { type: 'link', icon: 'reload', style: { marginTop: '8px' } },
            on: { click: this.refresh }
          }, '重试')
        ])
      ])
    }

    if (this.componentDefinition) {
      try {
        return h(this.componentDefinition, { props: this.$attrs })
      } catch (err) {
        console.error('[CloudVueSfcComponent] 渲染错误:', err)
        return h('div', {
          style: { padding: '16px', color: '#f5222d' }
        }, '渲染组件时出错: ' + err.message)
      }
    }

    return h('div', {
      class: 'cloud-vue-sfc-component',
      style: this.previewStyles
    }, [
      h('div', {
        class: 'empty-wrapper',
        style: { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', color: '#999' }
      }, [
        h('a-empty', {
          props: { description: '暂无云端组件内容' }
        })
      ])
    ])
  }
}
</script>

<style scoped lang="less">
.cloud-vue-sfc-component {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

.loading-wrapper,
.error-wrapper,
.content-wrapper,
.empty-wrapper {
  width: 100%;
  height: 100%;
}
</style>
