<template>
  <Teleport to="body">
    <transition name="modal">
      <div v-if="visible" class="continuation-modal" @click="handleClose">
        <div class="modal-content" @click.stop>
          <!-- Header -->
          <div class="modal-header">
            <h3 class="modal-title">续作任务提交</h3>
            <button class="close-btn" @click="handleClose">X</button>
          </div>

          <!-- Body -->
          <div class="modal-body">
            <div class="form-item">
              <label class="form-label">原作品预览</label>
              <div class="media-preview-wrapper">
                <video 
                  v-if="isVideo(formData.imageUrl)" 
                  :src="formData.imageUrl" 
                  controls 
                  class="preview-media"
                ></video>
                <img 
                  v-else-if="formData.imageUrl" 
                  :src="formData.imageUrl" 
                  alt="Reference" 
                  class="preview-media" 
                />
                <div v-else class="no-media">无预览内容</div>
              </div>
            </div>

            <div class="form-item">
              <label class="form-label">提示词 <span class="required">*</span></label>
              <textarea 
                v-model="formData.prompt" 
                class="custom-textarea" 
                rows="4" 
                placeholder="请输入新的提示词..."
              ></textarea>
            </div>
            
            <div class="form-item">
              <label class="form-label">
                时长 
                <span class="required">*</span>
                <span class="points-info" v-if="pointsCost > 0">（消耗 {{ pointsCost }} 积分）</span>
              </label>
              <div class="duration-options">
                <div 
                  v-for="opt in durationOptions" 
                  :key="opt.value"
                  class="duration-option"
                  :class="{ selected: formData.duration === opt.value }"
                  @click="selectDuration(opt.value)"
                >
                  {{ opt.label }}
                </div>
              </div>
            </div>

            <div class="form-item" v-if="supportsHighQuality">
              <div class="switch-wrapper">
                <label class="form-label mb-0">高清模式 (1080P)</label>
                <label class="switch">
                  <input type="checkbox" v-model="formData.highQuality">
                  <span class="slider"></span>
                </label>
              </div>
            </div>
          </div>

          <!-- Footer -->
          <div class="modal-footer">
            <button class="cancel-btn" @click="handleClose">取消</button>
            <button class="submit-btn" @click="handleSubmit" :disabled="loading">
              {{ loading ? '提交中...' : '确认续作' }}
            </button>
          </div>
        </div>
      </div>
    </transition>
  </Teleport>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import { submitAITask, getAIModels } from '../api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  initialData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'submit-success'])

const loading = ref(false)

const availableModels = ref([])
const currentTaskType = ref('image_to_video')

const formData = ref({
  modelName: '', // 初始为空，等待加载
  prompt: '',
  imageUrl: '',
  sourceTaskNo: '',
  aspectRatio: '16:9',
  duration: 10,
  highQuality: false
})

// 模拟积分计算逻辑，实际应从模型列表获取
const pointsCost = computed(() => {
  const exactModelName = getExactModelName()
  const found = availableModels.value.find(m => m.modelName === exactModelName)
  return found ? found.pointsCost : 30 // 默认 30，如果找到则使用实际值
})

const durationOptions = [
  { value: 10, label: '10秒' },
  { value: 15, label: '15秒' }
]

const supportsHighQuality = computed(() => {
  // 支持高清模式的判断：不是 sora2-pro 即可 (Sora2_img_video 或 Sora2_text_video)
  return !formData.value.modelName.toLowerCase().includes('sora2-pro')
})

const isVideo = (url) => {
  if (!url) return false
  const ext = url.split('.').pop().toLowerCase()
  return ['mp4', 'mov', 'webm', 'avi'].includes(ext) || url.includes('video')
}

const fetchModels = async () => {
  try {
    const response = await getAIModels({
      taskType: currentTaskType.value,
      provider: 'suchuang',
      enabledOnly: true
    })
    if (response.code === 200) {
      availableModels.value = response.data || []
    }
  } catch (error) {
    console.error('续作弹窗获取模型失败:', error)
  }
}

watch(() => props.initialData, (newVal) => {
  if (newVal) {
    // 根据原任务模型名称判断任务类型
    const isTextModel = newVal.modelName && newVal.modelName.includes('text')
    currentTaskType.value = isTextModel ? 'text_to_video' : 'image_to_video'
    const baseModelName = isTextModel ? 'Sora2_text_video' : 'Sora2_img_video'

    formData.value = {
      modelName: baseModelName, 
      prompt: newVal.prompt || '',
      imageUrl: newVal.referenceImageUrl || '', 
      sourceTaskNo: newVal.sourceTaskNo || '',
      aspectRatio: newVal.aspectRatio || '16:9',
      duration: 10,
      highQuality: false
    }
    // 加载模型列表以确保能匹配到正确的模型名称
    fetchModels()
  }
}, { immediate: true })

const selectDuration = (duration) => {
  formData.value.duration = duration
}

const handleClose = () => {
  emit('update:visible', false)
}

const handleSubmit = async () => {
  if (!formData.value.prompt.trim()) {
    ElMessage.warning('请输入提示词')
    return
  }

  loading.value = true
  try {
    // 获取精确匹配的模型名称
    const exactModelName = getExactModelName()
    
    const taskData = {
      modelName: exactModelName, // 使用精确匹配后的模型名称
      prompt: formData.value.prompt,
      imageUrl: formData.value.imageUrl,
      aspectRatio: formData.value.aspectRatio,
      sourceTaskNo: formData.value.sourceTaskNo,
      imageToVideo: currentTaskType.value === 'image_to_video',
      duration: formData.value.duration,
      size: formData.value.highQuality ? 'large' : 'small'
    }
    
    console.log('提交续作任务:', taskData)
    const response = await submitAITask(taskData)
    
    if (response.code === 200) {
      ElMessage.success('续作任务提交成功')
      emit('submit-success')
      handleClose()
    } else {
      throw new Error(response.message || '提交失败')
    }
  } catch (error) {
    console.error('续作提交错误:', error)
    ElMessage.error(error.message || '提交失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取准确的模型名称（包含参数后缀）
const getExactModelName = () => {
  if (availableModels.value.length === 0) return formData.value.modelName
  
  const targetAspectRatio = formData.value.aspectRatio === 'portrait' ? '9:16' : (formData.value.aspectRatio === 'landscape' ? '16:9' : formData.value.aspectRatio)
  const targetDuration = formData.value.duration.toString()
  const targetSize = formData.value.highQuality ? 'large' : 'small'
  
  // 在 availableModels 中查找匹配配置的模型
  const found = availableModels.value.find(m => {
    const config = m.extendedConfig || {}
    const name = m.modelName || ''
    
    // 排除 Sora2Pro
    if (name.toLowerCase().includes('sora2pro')) return false
    
    // 匹配参数
    return config.aspectRatio === targetAspectRatio &&
           config.duration === targetDuration &&
           config.size === targetSize
  })
  
  if (found) {
    console.log('续作匹配到具体模型:', found.modelName)
    return found.modelName
  }
  
  console.warn('续作未找到精确匹配的模型，将使用基础名称:', formData.value.modelName)
  return formData.value.modelName
}

// Directive for clicking outside
const vClickOutside = {
  mounted(el, binding) {
    el.clickOutsideEvent = (event) => {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value()
      }
    }
    document.addEventListener('click', el.clickOutsideEvent)
  },
  unmounted(el) {
    document.removeEventListener('click', el.clickOutsideEvent)
  }
}
</script>

<style scoped>
.continuation-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  backdrop-filter: blur(5px);
}

.modal-content {
  width: 500px;
  background: #1F1F1F;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
  overflow: hidden;
  animation: modalFadeIn 0.3s ease;
}

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

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  margin: 0;
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  cursor: pointer;
  font-size: 18px;
  padding: 4px;
  transition: color 0.3s;
}

.close-btn:hover { color: #fff; }

.modal-body {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.required { color: #ff4d4f; margin-left: 4px; }

.media-preview-wrapper {
  width: 100%;
  height: 200px;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-media {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.no-media {
  color: rgba(255, 255, 255, 0.3);
  font-size: 14px;
}

.custom-select {
  position: relative;
  width: 100%;
}

/* Duration Options */
.duration-options {
  display: flex;
  gap: 12px;
}

.duration-option {
  flex: 1;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 10px;
  text-align: center;
  color: rgba(255, 255, 255, 0.6);
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.duration-option:hover {
  background: rgba(255, 255, 255, 0.1);
}

.duration-option.selected {
  background: rgba(26, 195, 255, 0.15);
  border-color: #1AC3FF;
  color: #1AC3FF;
}

/* Switch */
.switch-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 0;
}

.mb-0 { margin-bottom: 0; }

.switch {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.2);
  transition: .4s;
  border-radius: 24px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #1AC3FF;
}

input:checked + .slider:before {
  transform: translateX(20px);
}

.points-info {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
  margin-left: 8px;
  font-weight: normal;
}

.select-trigger {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 10px 12px;
  color: #fff;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.arrow {
  width: 16px;
  height: 16px;
  transition: transform 0.3s;
}
.arrow.rotated { transform: rotate(180deg); }

.select-options {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background: #2a2a2a;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  margin-top: 4px;
  z-index: 10;
  overflow: hidden;
}

.select-option {
  padding: 10px 12px;
  color: rgba(255, 255, 255, 0.8);
  cursor: pointer;
  transition: background 0.2s;
}

.select-option:hover { background: rgba(255, 255, 255, 0.1); }
.select-option.selected { color: #1AC3FF; background: rgba(26, 195, 255, 0.1); }

.custom-textarea {
  width: 100%;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 12px;
  color: #fff;
  font-size: 14px;
  resize: none;
}

.custom-textarea:focus {
  outline: none;
  border-color: #1AC3FF;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn {
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  padding: 8px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn:hover { border-color: #fff; }

.submit-btn {
  background: linear-gradient(90deg, #1AC3FF 0%, #0085FF 100%);
  border: none;
  color: #fff;
  padding: 8px 24px;
  border-radius: 6px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.submit-btn:hover:not(:disabled) { opacity: 0.9; }
</style>
