<template>
  <div class="generating-page">
    <div class="generating-card">
      <!-- 生成中 -->
      <div v-if="displayStatus === 'generating'" class="generating-content">
        <div class="spinner"></div>
        <h2>正在生成你的绘本...</h2>
        <p>{{ progressMessage || 'AI 正在根据你的画作和故事构思创作绘本，请稍候' }}</p>
        <div v-if="progress > 0" class="progress-bar-wrapper">
          <div class="progress-bar" :style="{ width: progress + '%' }"></div>
        </div>
        <p class="progress-text" v-if="progress > 0">{{ progress }}%</p>
      </div>

      <!-- 已完成 -->
      <div v-else-if="displayStatus === 'completed'" class="completed-content">
        <check-circle-outlined class="success-icon" />
        <h2>绘本生成完成！</h2>
        <p>你的绘本「{{ title || '未命名作品' }}」已保存到作品库</p>
        <a-space>
          <a-button type="primary" size="large" shape="round" @click="router.push(`/p/works/${workId}`)">
            查看绘本
          </a-button>
          <a-button size="large" shape="round" @click="router.push('/p/create')">
            继续创作
          </a-button>
        </a-space>
      </div>

      <!-- 已失败 -->
      <div v-else-if="displayStatus === 'failed'" class="failed-content">
        <close-circle-outlined class="fail-icon" />
        <h2>生成失败</h2>
        <p>{{ failReason || '抱歉，绘本生成遇到了问题，请重试' }}</p>
        <a-button type="primary" size="large" shape="round" @click="router.push('/p/create')">
          重新创作
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import { publicCreationApi } from '@/api/public'

const route = useRoute()
const router = useRouter()
const workId = Number(route.params.id)

// 状态（INT 类型：-1=FAILED, 0=DRAFT, 1=PENDING, 2=PROCESSING, 3+=完成）
const status = ref<number>(1)
const title = ref('')
const progress = ref(0)
const progressMessage = ref('')
const failReason = ref('')

let pollTimer: ReturnType<typeof setInterval> | null = null

// 计算显示状态
const displayStatus = computed<'generating' | 'completed' | 'failed'>(() => {
  if (status.value === -1) return 'failed'
  if (status.value >= 3) return 'completed'
  return 'generating'
})

const pollStatus = async () => {
  try {
    const result = await publicCreationApi.getStatus(workId)
    status.value = typeof result.status === 'number' ? result.status : parseInt(String(result.status)) || 0
    title.value = result.title || ''

    // 从新的 INT 状态字段读取进度
    if ('progress' in result) progress.value = (result as any).progress || 0
    if ('progressMessage' in result) progressMessage.value = (result as any).progressMessage || ''
    if ('failReason' in result) failReason.value = (result as any).failReason || ''

    // 完成或失败时停止轮询
    if (status.value === -1 || status.value >= 3) {
      if (pollTimer) clearInterval(pollTimer)
    }
  } catch {
    // 静默重试
  }
}

onMounted(() => {
  pollStatus()
  pollTimer = setInterval(pollStatus, 3000)
})

onUnmounted(() => {
  if (pollTimer) clearInterval(pollTimer)
})
</script>

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

.generating-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.generating-card {
  text-align: center;
  max-width: 400px;
  padding: 40px 24px;

  h2 { font-size: 20px; font-weight: 700; color: #1e1b4b; margin: 16px 0 8px; }
  p { font-size: 13px; color: #9ca3af; margin: 0 0 24px; }
}

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

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

.progress-bar-wrapper {
  width: 200px;
  height: 6px;
  background: #e5e7eb;
  border-radius: 3px;
  margin: 12px auto;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: $primary;
  border-radius: 3px;
  transition: width 0.5s ease;
}

.progress-text {
  font-size: 12px;
  color: #6b7280;
  min-height: 18px;
}

.success-icon { font-size: 64px; color: #10b981; }
.fail-icon { font-size: 64px; color: #ef4444; }
</style>
