<template>
  <div class="ai-create-page">
    <!-- 左侧侧边栏 -->
    <div class="sidebar-container">
      <TextToVideoSidebar 
        v-if="currentMode === 'text'" 
        @switch-mode="switchMode"
        @task-update="handleTaskUpdate"
        :remake-prompt="remakePrompt"
        :remake-aspect-ratio="remakeAspectRatio"
        :remake-model-name="remakeModelName"
        @remake-done="remakePrompt = ''; remakeAspectRatio = ''; remakeModelName = ''"
      />
      <ImageToVideoSidebar 
        v-if="currentMode === 'image'" 
        @switch-mode="switchMode"
        @task-update="handleTaskUpdate"
        :remake-prompt="remakePrompt"
        :remake-image-url="remakeImageUrl"
        :remake-aspect-ratio="remakeAspectRatio"
        :remake-model-name="remakeModelName"
        :remake-source-task-no="remakeSourceTaskNo"
        @remake-done="handleImageRemakeDone"
      />
      <StoryboardVideoSidebar 
        v-if="currentMode === 'storyboard'" 
        @switch-mode="switchMode"
        @switch-to-image-mode="handleSwitchToImageMode"
        @task-update="handleTaskUpdate"
        :remake-prompt="remakePrompt"
        :remake-image-url="remakeImageUrl"
        :remake-aspect-ratio="remakeAspectRatio"
        @remake-done="handleStoryboardRemakeDone"
      />
    </div>
    
    <!-- 右侧主内容区 -->
    <div class="main-content">
      <keep-alive>
        <component 
          :is="currentComponent"
          @remake="handleRemake"
          :refresh-trigger="refreshTrigger"
          :is-storyboard="currentMode === 'storyboard'"
        />
      </keep-alive>
    </div>

    <!-- 续作任务弹窗 -->
    <ContinuationTaskDialog 
      v-model:visible="showContinuationDialog"
      :initial-data="continuationData"
      @submit-success="handleTaskUpdate"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../store'
import { provideVideoPlayback } from '../../composables/useVideoPlayback'
import TextToVideoSidebar from '../../components/CreateSidebars/TextToVideoSidebar.vue'
import ImageToVideoSidebar from '../../components/CreateSidebars/ImageToVideoSidebar.vue'
import StoryboardVideoSidebar from '../../components/CreateSidebars/StoryboardVideoSidebar.vue'
import TextToVideoContent from '../../components/CreateContent/TextToVideoContent.vue'
import ImageToVideoContent from '../../components/CreateContent/ImageToVideoContent.vue'
import ContinuationTaskDialog from '../../components/ContinuationTaskDialog.vue'

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()

// 提供视频播放控制，确保同时只能播放一个视频
provideVideoPlayback()

// 创作模式数据
const modes = [
  { key: 'text', label: '文生视频', taskType: 'text_to_video' },
  { key: 'image', label: '图生视频', taskType: 'image_to_video' },
  { key: 'storyboard', label: '分镜视频', taskType: 'storyboard_to_video' }
]

// 当前模式
const currentMode = ref('text')
const remakePrompt = ref('')
const remakeImageUrl = ref('')
const remakeAspectRatio = ref('')
const remakeModelName = ref('')
const remakeSourceTaskNo = ref('')
const refreshTrigger = ref(0)
const showContinuationDialog = ref(false)
const continuationData = ref({})

// 根据当前模式动态选择内容组件
const contentComponents = {
  text: TextToVideoContent,
  image: ImageToVideoContent,
  storyboard: ImageToVideoContent
}
const currentComponent = computed(() => contentComponents[currentMode.value])

// 加载状态
const loading = ref(false)

// 轮询定时器
let pollTimer = null

// 计算当前模式信息
const currentModeInfo = computed(() => {
  return modes.find(mode => mode.key === currentMode.value) || modes[0]
})

// 切换模式
const switchMode = (modeKey) => {
  currentMode.value = modeKey
}

// 合并 'remake' 事件处理
const handleRemake = (data) => {
  if (currentMode.value === 'text') {
    handleRemakeRequest(data)
  } else if (currentMode.value === 'image') {
    handleImageRemakeRequest(data)
  } else if (currentMode.value === 'storyboard') {
    handleStoryboardRemakeRequest(data)
  }
}

// 文生视频做同款
// data 期望为 { prompt, aspectRatio, modelName, sourceTaskNo }
const handleRemakeRequest = (data) => {
  // 兼容旧形态（直接传字符串）
  if (typeof data === 'string') {
    remakePrompt.value = data
    remakeAspectRatio.value = ''
    remakeModelName.value = ''
  } else if (data && typeof data === 'object') {
    // 检查是否是续作请求（带有 sourceTaskNo）
    if (data.sourceTaskNo) {
      console.log('检测到文生视频列表的续作请求，打开续作弹窗', data)
      continuationData.value = data
      showContinuationDialog.value = true
      return
    }

    remakePrompt.value = data.prompt || ''
    remakeAspectRatio.value = data.aspectRatio || ''
    remakeModelName.value = data.modelName || ''
  }

  currentMode.value = 'text'
}

// 图生视频做同款
// data 期望为 { prompt, referenceImageUrl, aspectRatio, modelName, sourceTaskNo }
const handleImageRemakeRequest = (data) => {
  console.log('父组件收到图生视频做同款数据:', data)
  
  // 检查是否是续作请求（带有 sourceTaskNo）
  if (data.sourceTaskNo) {
    console.log('检测到图生视频列表的续作请求，打开续作弹窗', data)
    continuationData.value = data
    showContinuationDialog.value = true
    return
  }
  
  remakePrompt.value = data?.prompt || ''
  remakeImageUrl.value = data?.referenceImageUrl || ''
  remakeAspectRatio.value = data?.aspectRatio || ''
  remakeModelName.value = data?.modelName || ''
  remakeSourceTaskNo.value = data?.sourceTaskNo || ''
}

const handleImageRemakeDone = () => {
  remakePrompt.value = ''
  remakeImageUrl.value = ''
  remakeAspectRatio.value = ''
  remakeModelName.value = ''
  remakeSourceTaskNo.value = ''
}

// 处理分镜视频的"做同款"请求
const handleStoryboardRemakeRequest = (data) => {
  console.log('父组件收到分镜视频做同款数据:', data)
  // 切换到分镜视频模式，并传递数据到 StoryboardVideoSidebar
  currentMode.value = 'storyboard'
  remakePrompt.value = data.prompt || ''
  remakeImageUrl.value = data.referenceImageUrl || ''
  remakeAspectRatio.value = data.aspectRatio || ''
  remakeModelName.value = data.modelName || ''
}

const handleStoryboardRemakeDone = () => {
  remakePrompt.value = ''
  remakeImageUrl.value = ''
  remakeAspectRatio.value = ''
  remakeModelName.value = ''
}

const handleTaskUpdate = () => {
  refreshTrigger.value++
  // 任务更新时刷新用户信息（更新积分）
  if (userStore.fetchUserInfo) {
    userStore.fetchUserInfo().catch(err => {
      console.error('刷新用户信息失败:', err)
    })
  }
}

// 处理从分镜视频切换到图生视频模式（用户提交分镜视频任务后）
const handleSwitchToImageMode = () => {
  currentMode.value = 'image'
}

onMounted(() => {
  console.log('AI创作页面已加载')
  
  // 从URL query参数填充模式和数据
  const { mode, imageUrl, prompt, aspectRatio, modelName } = route.query;
  
  console.log('接收到的查询参数:', { mode, imageUrl, prompt, aspectRatio, modelName });
  
  // 先切换模式
  if (mode && modes.some(m => m.key === mode)) {
    currentMode.value = mode;
    console.log('切换模式到:', mode);
  }
  
  // 使用 nextTick 确保组件已经渲染完成后再填充数据
  if (imageUrl || prompt || aspectRatio || modelName) {
    nextTick(() => {
      // 延迟填充，确保子组件已经挂载并且 watch 已经设置
      setTimeout(() => {
        if (imageUrl) {
          remakeImageUrl.value = imageUrl;
          console.log('填充图片URL:', imageUrl);
        }
        if (prompt) {
          remakePrompt.value = prompt;
          console.log('填充提示词:', prompt);
        }
        if (aspectRatio) {
          remakeAspectRatio.value = aspectRatio;
          console.log('填充尺寸比例:', aspectRatio);
        }
        if (modelName) {
          remakeModelName.value = modelName;
          console.log('填充模型名称:', modelName);
        }
        
        // 提示用户
        ElMessage.success('已自动填充参数，请检查并点击生成按钮');
        
        // 延迟清理URL，给watch足够的时间响应
        setTimeout(() => {
          router.replace({ query: {} });
          console.log('已清理URL参数');
        }, 1000);
      }, 500);
    });
  }
  
  // 进入页面时查询一次用户信息
  if (userStore.fetchUserInfo) {
    userStore.fetchUserInfo().catch(err => {
      console.error('初始化用户信息失败:', err)
    })
  }
})

// 页面卸载时停止轮询
onUnmounted(() => {
  // stopPolling() // 该函数未在此组件定义，且轮询由子组件管理
})
</script>

<style scoped>
.ai-create-page {
  width: 100%;
  min-height: calc(100vh - 80px);
  background: rgba(21, 21, 21, 1);
  box-sizing: border-box;
  position: relative;
  display: flex;
  overflow: hidden;
}

/* 左侧侧边栏 */
.sidebar-container {
  width: 480px;
  height: calc(100vh - 80px);
  flex-shrink: 0;
  margin: 0;
  padding: 0;
}

/* 右侧主内容区 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 0;
  box-sizing: border-box;
}

/* 响应式 */
@media (max-width: 1200px) {
  .sidebar-container {
    width: 400px;
  }
}

@media (max-width: 768px) {
  .ai-create-page {
    min-height: calc(100vh - 70px);
    flex-direction: column;
  }

  .sidebar-container {
    width: 100%;
    height: auto;
    min-height: 300px;
  }

  .main-content {
    padding: 0;
  }
}

@media (max-width: 480px) {
  .ai-create-page {
    min-height: calc(100vh - 60px);
  }
}
</style>
