<template>
  <div class="result-panel">
    <div v-if="!previewVideoUrl" class="result-placeholder">
      <h3>生成的视频将在这里显示</h3>
    </div>

    <div v-else class="result-content">
      <div class="result-section">
        <h3>生成的数字人视频</h3>
        <video :src="previewVideoUrl" controls class="generated-video"></video>
        <div class="video-actions">
          <Button @click="downloadVideo">下载视频</Button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { toast } from 'vue-sonner'
import { Button } from '@/components/ui/button'
import { getDigitalHumanTask } from '@/api/digitalHuman'

const props = defineProps({
  taskId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['videoLoaded'])

const previewVideoUrl = ref('')

const loadLastTask = async () => {
  try {
    const lastTaskId = localStorage.getItem('digital_human_last_task_id')
    if (!lastTaskId) return

    const res = await getDigitalHumanTask(lastTaskId)
    if (res.code === 0 && res.data) {
      const task = res.data

      if (task.status === 'SUCCESS' && task.resultVideoUrl) {
        previewVideoUrl.value = task.resultVideoUrl
        emit('videoLoaded', task.resultVideoUrl)
      }
    }
  } catch (error) {
    localStorage.removeItem('digital_human_last_task_id')
  }
}

const downloadVideo = () => {
  if (!previewVideoUrl.value) return toast.warning('没有可下载的视频')
  const link = document.createElement('a')
  link.href = previewVideoUrl.value
  link.download = `数字人视频_${Date.now()}.mp4`
  link.click()
}

defineExpose({
  loadLastTask,
  previewVideoUrl
})

onMounted(async () => {
  await loadLastTask()
})
</script>

<style scoped>
.result-panel {
  background: var(--muted);
  border-radius: var(--radius-lg);
  padding: var(--space-6);
}

.result-placeholder {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--muted-foreground);
}

.result-content {
  color: var(--foreground);
}

.result-section {
  margin-bottom: var(--space-6);
}

.result-section h3 {
  margin-bottom: var(--space-3);
  font-size: var(--font-size-lg);
}

.generated-video {
  width: 100%;
  max-height: 400px;
  border-radius: var(--radius);
  margin-top: var(--space-3);
}

.video-actions {
  margin-top: var(--space-4);
  display: flex;
  justify-content: center;
}
</style>
