<template>
  <div class="creation-container">
    <!-- 加载中提示 -->
    <div v-if="loading" class="loading-wrapper">
      <div class="spinner"></div>
      <p class="loading-text">正在加载创作工坊...</p>
      <p v-if="loadError" class="load-error">{{ loadError }}</p>
      <a-button v-if="loadError" type="primary" @click="initLeai" style="margin-top: 12px">
        重新加载
      </a-button>
    </div>
    <!-- iframe 嵌入乐读派 H5 -->
    <iframe
      v-if="iframeSrc"
      ref="leaiFrame"
      :src="iframeSrc"
      class="creation-iframe"
      allow="camera;microphone"
      frameborder="0"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { leaiApi } from '@/api/public'

const router = useRouter()
const leaiFrame = ref<HTMLIFrameElement | null>(null)
const iframeSrc = ref<string>('')
const loading = ref(true)
const loadError = ref<string>('')

/** 初始化乐读派 iframe */
const initLeai = async () => {
  loading.value = true
  loadError.value = ''

  try {
    const data = await leaiApi.getToken()
    iframeSrc.value = `${data.h5Url}/?token=${encodeURIComponent(data.token)}&orgId=${encodeURIComponent(data.orgId)}&phone=${encodeURIComponent(data.phone)}&embed=1`
  } catch (err: any) {
    const errMsg = err?.response?.data?.message || err?.message || '加载失败'
    loadError.value = errMsg
    message.error('加载创作工坊失败：' + errMsg)
  } finally {
    if (!loadError.value) {
      loading.value = false
    }
  }
}

/** 监听乐读派 H5 postMessage 事件 */
const handleMessage = (event: MessageEvent) => {
  const msg = event.data
  // 只处理乐读派 H5 的消息
  if (!msg || msg.source !== 'leai-creation') return

  console.log('[创作工坊] 收到消息:', msg.type, msg.payload)

  switch (msg.type) {
    case 'READY':
      console.log('[创作工坊] H5已就绪')
      break

    case 'TOKEN_EXPIRED':
      handleTokenExpired(msg.payload)
      break

    case 'WORK_CREATED':
      console.log('[创作工坊] 作品创建:', msg.payload?.workId)
      break

    case 'WORK_COMPLETED':
      console.log('[创作工坊] 作品完成:', msg.payload?.workId)
      break

    case 'NAVIGATE_BACK':
      router.push('/p/works')
      break

    case 'CREATION_ERROR':
      message.error('创作遇到问题：' + (msg.payload?.error || '未知错误'))
      break
  }
}

/** 处理 Token 过期：刷新并回传新 Token */
const handleTokenExpired = async (payload: any) => {
  try {
    const data = await leaiApi.refreshToken()
    leaiFrame.value?.contentWindow?.postMessage({
      source: 'leai-creation',
      version: 1,
      type: 'TOKEN_REFRESHED',
      payload: {
        messageId: payload?.messageId,
        token: data.token,
        orgId: data.orgId,
        phone: data.phone,
      },
    }, '*')
    console.log('[创作工坊] Token已刷新')
  } catch (err) {
    console.error('[创作工坊] Token刷新失败:', err)
    message.error('Token刷新失败，请刷新页面重试')
  }
}

onMounted(() => {
  initLeai()
  window.addEventListener('message', handleMessage)
})

onUnmounted(() => {
  window.removeEventListener('message', handleMessage)
})
</script>

<style scoped lang="scss">
$primary: #6366f1;

.creation-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.creation-iframe {
  flex: 1;
  width: 100%;
  height: 100%;
  border: none;
  min-height: calc(100vh - 120px);
}

.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  text-align: center;
}

.spinner {
  width: 48px;
  height: 48px;
  border: 4px solid rgba($primary, 0.1);
  border-top-color: $primary;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  font-size: 15px;
  color: #6b7280;
  margin: 0;
}

.load-error {
  font-size: 13px;
  color: #ef4444;
  margin: 8px 0 0;
}
</style>
