<template>
  <div class="video-preview-modal" v-if="visible">
    <div class="modal-content">
      <div class="modal-header">
        <h3>课程视频预览</h3>
        <button class="close-btn" @click="close">×</button>
      </div>
      <div class="modal-body">
        <div class="video-container">
          <!-- 环节指示器 -->
          <div class="section-indicators">
            <div
              v-for="(section, index) in scriptData.sections"
              :key="index"
              class="section-indicator"
              :class="{ active: index === currentSectionIndex }"
              @click="jumpToSection(index)"
            >
              {{ section.name }}
            </div>
          </div>

          <!-- 背景图 -->
          <div class="background-container" :style="{ backgroundImage: `url(${currentSection?.backgroundImage?.url || getBackgroundUrl(currentSection?.backgroundImage?.prompt)})` }">
            <!-- 背景音信息 -->
            <div v-if="currentSection?.backgroundAudio?.type" class="background-music-info">
              <strong>当前背景音：</strong> {{ currentSection.backgroundAudio.type }}
            </div>
            
            <!-- 人物形象 - 数字人、提问和诗词对话显示 -->
            <div
              v-if="currentDialogue && (currentDialogue.type === 'digital' || currentDialogue.type === 'quest' || currentDialogue.type === 'poem')"
              :key="`character-${currentDialogue.roleName}-${currentDialogueIndex}`"
              class="character"
              :class="{
                'left': getCharacterSide(currentDialogue.roleName) === 'left',
                'right': getCharacterSide(currentDialogue.roleName) === 'right'
              }"
              :style="{ backgroundImage: `url(${getCharacterImage(currentDialogue.roleName)})` }"
            ></div>

            <!-- 对话卡片 - 数字人对话 -->
            <div
              v-if="currentDialogue && currentDialogue.type === 'digital'"
              :key="`dialogue-${currentDialogueIndex}`"
              class="dialogue-card"
              :class="{
                'left': getCharacterSide(currentDialogue.roleName) === 'left',
                'right': getCharacterSide(currentDialogue.roleName) === 'right'
              }"
            >
              <div class="dialogue-header">
                <span class="role-name">{{ getRoleName(currentDialogue.roleName) }}</span>
              </div>
              <div class="dialogue-content" v-html="parseMarkdown(currentDialogue.content)"></div>
            </div>

            <!-- 对话卡片 - 提问对话 -->
            <div
              v-if="currentDialogue && currentDialogue.type === 'quest'"
              :key="`dialogue-${currentDialogueIndex}`"
              class="dialogue-card"
              :class="{
                'left': getCharacterSide(currentDialogue.roleName) === 'left',
                'right': getCharacterSide(currentDialogue.roleName) === 'right'
              }"
            >
              <div class="dialogue-header quest-header">
                <span class="role-name">{{ getRoleName(currentDialogue.roleName) }}</span>
              </div>
              <div class="dialogue-content" v-html="parseMarkdown(currentDialogue.content)"></div>
            </div>

            <!-- 对话卡片 - 诗词对话 -->
            <div
              v-if="currentDialogue && currentDialogue.type === 'poem'"
              :key="`dialogue-${currentDialogueIndex}`"
              class="dialogue-card"
              :class="{
                'left': getCharacterSide(currentDialogue.roleName) === 'left',
                'right': getCharacterSide(currentDialogue.roleName) === 'right'
              }"
            >
              <div class="dialogue-header poem-header">
                <span class="role-name">{{ getRoleName(currentDialogue.roleName) }}</span>
              </div>
              <div class="dialogue-content" v-html="parseMarkdown(currentDialogue.content)"></div>
            </div>

            <!-- 用户回答状态 -->
            <div v-if="currentDialogue && currentDialogue.type === 'user'" class="user-input-section">
              <!-- 麦克风图标 -->
              <div 
                class="microphone-icon" 
                :class="{ 'recording': isRecording }"
                @click="toggleRecording"
              >
                <span class="mic-icon">{{ isRecording ? '⏹' : '🎤' }}</span>
                <span class="mic-text">{{ isRecording ? '点击停止' : '点击说话' }}</span>
              </div>
              
              <!-- 用户对话卡片 -->
              <div v-if="userInputContent" class="user-dialogue-card">
                <div class="dialogue-header user-header">
                  <span class="role-name">用户</span>
                </div>
                <div class="dialogue-content">{{ userInputContent }}</div>
              </div>
            </div>
          </div>

          <!-- 控制栏 -->
          <div class="video-controls">
            <button class="control-btn" @click="playPrevious" :disabled="currentSectionIndex === 0 && currentDialogueIndex === 0">
              上一句
            </button>
            <button class="control-btn primary" @click="togglePlay">
              {{ isPlaying ? '暂停' : '播放' }}
            </button>
            <button class="control-btn" @click="playNext" :disabled="currentSectionIndex === scriptData.sections.length - 1 && currentDialogueIndex === currentSection.dialogues.length - 1">
              下一句
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { marked } from 'marked'

const props = defineProps({
  visible: {
    type: Boolean,
    default: true
  },
  scriptData: {
    type: Object,
  },
  scriptRoles: {
    type: Array,
  }
})

const emit = defineEmits(['close'])

// 状态
const isPlaying = ref(false)
const currentSectionIndex = ref(0)
const currentDialogueIndex = ref(0)
const isRecording = ref(false)
const userInputContent = ref('')

// 音频对象
const backgroundAudio = ref(null)
const dialogueAudio = ref(null)
const mediaRecorder = ref(null)
const audioChunks = ref([])

// 计算属性
const currentSection = computed(() => {
  return props.scriptData.sections[currentSectionIndex.value]
})

const currentDialogue = computed(() => {
  if (!currentSection.value) return null
  return currentSection.value.dialogues[currentDialogueIndex.value]
})

// 方法
const close = () => {
  // 停止所有音频
  stopAllAudio()
  emit('close')
}

const stopAllAudio = () => {
  if (backgroundAudio.value) {
    backgroundAudio.value.pause()
    backgroundAudio.value.currentTime = 0
  }
  if (dialogueAudio.value) {
    dialogueAudio.value.pause()
    dialogueAudio.value.currentTime = 0
  }
}

const playBackgroundAudio = () => {
  // 停止之前的背景音
  if (backgroundAudio.value) {
    backgroundAudio.value.pause()
    backgroundAudio.value.currentTime = 0
  }

  // 播放当前环节的背景音
  if (currentSection.value?.backgroundAudio?.url && isPlaying.value) {
    backgroundAudio.value = new Audio(currentSection.value.backgroundAudio.url)
    backgroundAudio.value.loop = true
    backgroundAudio.value.volume = 1
    backgroundAudio.value.play().catch(e => console.error('背景音播放失败:', e))
  }
}

const playDialogueAudio = () => {
  // 停止之前的对话语音
  if (dialogueAudio.value) {
    dialogueAudio.value.pause()
    dialogueAudio.value.currentTime = 0
  }

  // 播放当前对话的语音
  if (currentDialogue.value?.voiceoverUrl) {
    dialogueAudio.value = new Audio(currentDialogue.value.voiceoverUrl)
    return new Promise((resolve) => {
      // 最短3秒跳转
      const minDelay = 3000
      let audioEnded = false

      // 音频结束事件
      dialogueAudio.value.onended = () => {
        audioEnded = true
        resolve()
      }

      // 播放音频
      dialogueAudio.value.play().catch(e => {
        console.error('对话语音播放失败:', e)
        // 播放失败时，2秒后跳转
        setTimeout(resolve, minDelay)
      })

      // 检查音频时长
      dialogueAudio.value.addEventListener('loadedmetadata', () => {
        const duration = dialogueAudio.value.duration
        // 如果音频时长小于2秒，2秒后跳转
        if (duration < 2) {
          setTimeout(() => {
            if (!audioEnded) {
              resolve()
            }
          }, minDelay)
        }
      })
    })
  }
  // 如果没有语音文件，2秒后跳转
  return new Promise(resolve => setTimeout(resolve, 2000))
}

const togglePlay = () => {
  isPlaying.value = !isPlaying.value
  if (isPlaying.value) {
    // 播放背景音
    playBackgroundAudio()
    // 开始播放序列
    playSequence()
  } else {
    // 暂停所有音频
    stopAllAudio()
  }
}

const playSequence = async () => {
  if (!isPlaying.value) return

  // 检查当前对话类型
  if (currentDialogue.value && currentDialogue.value.type === 'user') {
    // 用户回答类型，暂停自动播放，等待用户输入
    // 这里不需要播放音频，只需要等待用户输入
    return
  }

  // 播放当前对话语音
  await playDialogueAudio()

  // 播放下一个对话
  if (!playNext()) {
    // 播放完毕
    isPlaying.value = false
    // 停止所有音频，包括背景音
    stopAllAudio()
  } else {
    playSequence()
  }
}

const playPrevious = () => {
  // 停止当前音频
  stopAllAudio()

  if (currentDialogueIndex.value > 0) {
    currentDialogueIndex.value--
  } else if (currentSectionIndex.value > 0) {
    currentSectionIndex.value--
    const section = props.scriptData.sections[currentSectionIndex.value]
    currentDialogueIndex.value = section.dialogues.length - 1
  }

  // 播放背景音
  playBackgroundAudio()
  // 播放当前对话语音
  playDialogueAudio()
}

const playNext = () => {
  // 停止当前对话语音
  if (dialogueAudio.value) {
    dialogueAudio.value.pause()
    dialogueAudio.value.currentTime = 0
    // 清除音频对象引用
    dialogueAudio.value = null
  }

  if (currentSection.value && currentDialogueIndex.value < currentSection.value.dialogues.length - 1) {
    currentDialogueIndex.value++
    // 播放当前对话语音
    playDialogueAudio()
    return true
  } else if (currentSectionIndex.value < props.scriptData.sections.length - 1) {
    currentSectionIndex.value++
    currentDialogueIndex.value = 0
    // 播放背景音
    playBackgroundAudio()
    // 播放当前对话语音
    playDialogueAudio()
    return true
  }
  return false
}

const jumpToSection = (index) => {
  // 停止当前音频
  stopAllAudio()

  currentSectionIndex.value = index
  currentDialogueIndex.value = 0

  // 播放背景音
  playBackgroundAudio()
  // 播放当前对话语音
  playDialogueAudio()
}

const getRoleName = (roleName) => {
  const role = props.scriptRoles.find(r => r.name === roleName)
  return role ? role.name : '未知角色'
}

const getCharacterImage = (roleName) => {
  const role = props.scriptRoles.find(r => r.name === roleName)
  return role ? role.avatar : ''
}

const getCharacterSide = () => {
  return currentDialogueIndex.value % 2 === 0 ? 'left' : 'right'
}

const getBackgroundUrl = (prompt) => {
  if (!prompt) return ''
  return `https://neeko-copilot.bytedance.net/api/text2image?prompt=${encodeURIComponent(prompt)}&size=1024x512`
}

// 解析 Markdown 文本
const parseMarkdown = (text) => {
  if (!text) return ''
  return marked(text)
}

// 语音输入相关方法
const toggleRecording = async () => {
  if (!isRecording.value) {
    // 开始录音
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      mediaRecorder.value = new MediaRecorder(stream)
      audioChunks.value = []

      mediaRecorder.value.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunks.value.push(event.data)
        }
      }

      mediaRecorder.value.onstop = () => {
        const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' })
        convertSpeechToText(audioBlob)
      }

      mediaRecorder.value.start()
      isRecording.value = true
    } catch (error) {
      console.error('录音失败:', error)
      alert('无法访问麦克风，请检查权限设置')
    }
  } else {
    // 停止录音
    if (mediaRecorder.value) {
      mediaRecorder.value.stop()
      isRecording.value = false
    }
  }
}

const convertSpeechToText = (audioBlob) => {
  // 这里需要调用语音转文字的API
  // 由于没有实际的API，这里模拟一个转换过程
  setTimeout(() => {
    // 模拟转换结果
    userInputContent.value = '这是一段模拟的语音转文字内容'
    // 3秒后自动进入下一句
    setTimeout(() => {
      playNext()
    }, 3000)
  }, 1000)
}

// 监听环节变化
watch(currentSectionIndex, () => {
  playBackgroundAudio()
})

// 监听对话变化
watch(currentDialogue, () => {
  if (!isPlaying.value && props.visible) {
    playDialogueAudio()
  }
})

// 监听可见性变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 重置状态
    isPlaying.value = false
    currentSectionIndex.value = 0
    currentDialogueIndex.value = 0
    // 自动点击播放按钮
    setTimeout(() => {
      togglePlay()
    }, 500)
  } else {
    // 停止所有音频
    stopAllAudio()
  }
})

// 组件销毁时停止音频
onUnmounted(() => {
  stopAllAudio()
})
</script>

<style scoped>
.video-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 1000px;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafafa;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
  outline: none;
}

.close-btn:hover {
  background: #f0f0f0;
  color: #333;
}

.modal-body {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  min-height: 500px;
}

.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 500px;
  background: #f0f0f0;
  border-radius: 0;
  overflow: hidden;
}

/* 环节指示器 */
.section-indicators {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  display: flex;
  gap: 10px;
  overflow-x: auto;
  padding: 5px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-indicator {
  flex: 0 0 auto;
  padding: 6px 14px;
  background: #f0f0f0;
  border-radius: 16px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  border: 1px solid #e8e8e8;
}

.section-indicator:hover {
  background: #e6f7ff;
  color: #409EFF;
  border-color: #409EFF;
}

.section-indicator.active {
  background: #409EFF;
  color: white;
  border-color: #409EFF;
}

.background-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
}

/* 背景音信息 */
.background-music-info {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.7);
  color: black;
  padding: 6px 12px;
  border-radius: 12px;
  font-size: 14px;
  z-index: 5;
}

.character {
  position: absolute;
  bottom: 50px;
  width: 150px;
  height: 300px;
  background-size: contain;
  background-position: bottom;
  background-repeat: no-repeat;
  opacity: 0;
  transform: scale(0.5);
  animation: characterEnter 0.8s ease forwards;
}

.character.left {
  left: 20px;
}

.character.right {
  right: 20px;
}

@keyframes characterEnter {
  0% {
    opacity: 0;
    transform: scale(0.5);
    bottom: 50px;
  }
  70% {
    opacity: 0.9;
    transform: scale(1.05);
    bottom: 70px;
  }
  100% {
    opacity: 1;
    transform: scale(1);
    bottom: 50px;
  }
}

.dialogue-card {
  background: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  padding: 12px;
  max-width: 40%;
  min-width: 200px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  position: absolute;
  bottom: 130px;
  width: auto;
  display: inline-block;
}

.dialogue-card.left {
  left: 170px;
  animation: dialogueEnterLeft 0.6s ease forwards;
}

.dialogue-card.right {
  right: 170px;
  animation: dialogueEnterRight 0.6s ease forwards;
}

.dialogue-card.left::before {
  content: '';
  position: absolute;
  left: 0;
  bottom: 20px;
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-right: 15px solid rgba(255, 255, 255, 0.5);
  border-bottom: 10px solid transparent;
  transform: translateX(-100%);
}

.dialogue-card.right::before {
  content: '';
  position: absolute;
  right: 0;
  bottom: 20px;
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-left: 15px solid rgba(255, 255, 255, 0.5);
  border-bottom: 10px solid transparent;
  transform: translateX(100%);
}

@keyframes dialogueEnterLeft {
  from {
    opacity: 0;
    transform: translateX(-30px) translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0) translateY(0);
  }
}

@keyframes dialogueEnterRight {
  from {
    opacity: 0;
    transform: translateX(30px) translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0) translateY(0);
  }
}

.dialogue-header {
  position: absolute;
  top: -20px;
  left: 10px;
  background: #409EFF;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.dialogue-card.right .dialogue-header {
  left: 10px;
}

.dialogue-card.right .dialogue-header.quest-header {
  left: 10px;
}

.role-name {
  font-weight: 600;
  color: white;
  font-size: 14px;
}

.dialogue-content {
  font-size: 18px;
  line-height: 1.6;
  color: #333;
  text-align: left;
}

.dialogue-content h1,
.dialogue-content h2,
.dialogue-content h3,
.dialogue-content h4,
.dialogue-content h5,
.dialogue-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  line-height: 1.2;
}

.dialogue-content h1 { font-size: 24px; }
.dialogue-content h2 { font-size: 20px; }
.dialogue-content h3 { font-size: 18px; }
.dialogue-content h4 { font-size: 16px; }
.dialogue-content h5 { font-size: 14px; }
.dialogue-content h6 { font-size: 12px; }

.dialogue-content p {
  margin: 8px 0;
}

.dialogue-content ul,
.dialogue-content ol {
  margin: 8px 0;
  padding-left: 24px;
}

.dialogue-content li {
  margin: 4px 0;
}

.dialogue-content strong {
  font-weight: 600;
}

.dialogue-content em {
  font-style: italic;
}

.dialogue-content a {
  color: #409EFF;
  text-decoration: none;
}

.dialogue-content a:hover {
  text-decoration: underline;
}

.dialogue-content code {
  background: #f5f5f5;
  padding: 2px 4px;
  border-radius: 4px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
}

.dialogue-content pre {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 12px 0;
}

.dialogue-content pre code {
  background: none;
  padding: 0;
}

/* 用户输入部分 */
.user-input-section {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  z-index: 5;
}

.microphone-icon {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  border: 3px solid #409EFF;
}

.microphone-icon:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
}

.microphone-icon.recording {
  background: rgba(255, 87, 34, 0.8);
  border-color: #ff5722;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 87, 34, 0.7);
  }
  70% {
    box-shadow: 0 0 0 15px rgba(255, 87, 34, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 87, 34, 0);
  }
}

.mic-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.mic-text {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.microphone-icon.recording .mic-text {
  color: white;
}

.user-dialogue-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  padding: 16px;
  max-width: 400px;
  min-width: 300px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: dialogueEnterCenter 0.6s ease forwards;
}

@keyframes dialogueEnterCenter {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.dialogue-header.user-header {
  background: #67C23A;
  left: 50%;
  transform: translateX(-50%);
}

.dialogue-header.quest-header {
  background: #E6A23C;
}

.dialogue-header.poem-header {
  background: #909399;
}

/* 控制栏 */
.video-controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: center;
  gap: 20px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.8);
  padding: 10px 20px;
  border-radius: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.control-btn {
  padding: 10px 28px;
  border: 1px solid #d9d9d9;
  border-radius: 24px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  outline: none;
  font-size: 14px;
  min-width: 100px;
}

.control-btn:hover:not(:disabled) {
  border-color: #409EFF;
  color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  border-color: #f0f0f0;
  color: #bfbfbf;
}

.control-btn:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.control-btn.primary {
  background: #409EFF;
  color: white;
  border-color: #409EFF;
  font-weight: 600;
  min-width: 100px;
}

.control-btn.primary:hover:not(:disabled) {
  background: #1890ff;
  border-color: #1890ff;
  color: white;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.4);
}
</style>
