<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">
          <a-button type="primary" @click="downloadVideo">下载视频</a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
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 message.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: rgba(255, 255, 255, 0.05);
  border-radius: 16px;
  padding: 24px;
}

.result-placeholder {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #94a3b8;
}

.result-content {
  color: #fff;
}

.result-section {
  margin-bottom: 24px;
}

.result-section h3 {
  margin-bottom: 12px;
  font-size: 18px;
}

.generated-video {
  width: 100%;
  max-height: 400px;
  border-radius: 8px;
  margin-top: 12px;
}

.video-actions {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style>
