<template>
  <div class="algorithm-call-container">
    <!-- 页面标题 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item><router-link to="/">首页</router-link></el-breadcrumb-item>
      <el-breadcrumb-item><router-link to="/algorithms">算法列表</router-link></el-breadcrumb-item>
      <el-breadcrumb-item><router-link :to="`/algorithm/${algorithmStore.currentAlgorithm?.id}`">{{ algorithmStore.currentAlgorithm?.name }}</router-link></el-breadcrumb-item>
      <el-breadcrumb-item>算法调用</el-breadcrumb-item>
    </el-breadcrumb>
    
    <el-loading v-if="algorithmStore.loading" :fullscreen="true" text="加载中..." />
    
    <template v-else-if="algorithmStore.currentAlgorithm">
      <!-- 算法信息 -->
      <el-card class="algorithm-info-card">
        <h1>{{ algorithmStore.currentAlgorithm.name }}</h1>
        <p class="algorithm-description">{{ algorithmStore.currentAlgorithm.description }}</p>
      </el-card>
      
      <!-- 版本选择 -->
      <el-card class="version-select-card">
        <template #header>
          <h2>版本选择</h2>
        </template>
        <el-form-item label="选择版本">
          <el-select v-model="selectedVersionId" placeholder="选择算法版本" @change="handleVersionChange">
            <el-option 
              v-for="version in algorithmStore.currentAlgorithm.versions" 
              :key="version.id" 
              :label="version.version + (version.is_default ? ' (默认)' : '')" 
              :value="version.id" 
            />
          </el-select>
        </el-form-item>
      </el-card>
      
      <!-- 输入数据 -->
      <el-card class="input-card">
        <template #header>
          <div class="card-header">
            <h2>输入数据</h2>
            <el-button type="primary" @click="showOpenAIDialog = true">
              <el-icon><chat-dot-round /></el-icon>
              使用OpenAI生成
            </el-button>
          </div>
        </template>
        
        <div class="input-section">
          <!-- 文本输入 -->
          <el-form-item label="文本输入" v-if="inputType === 'text'">
            <el-input
              v-model="inputData.text"
              type="textarea"
              :rows="5"
              placeholder="请输入文本数据"
            />
          </el-form-item>
          
          <!-- 图片输入 -->
          <el-form-item label="图片上传" v-if="inputType === 'image'">
            <el-upload
              class="image-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleImageUpload"
              :show-file-list="false"
              accept="image/*"
            >
              <el-button size="large">
                <el-icon><upload /></el-icon>
                选择图片
              </el-button>
            </el-upload>
            <div v-if="inputData.image" class="image-preview">
              <img :src="inputData.image" alt="预览" />
              <el-button type="danger" size="small" @click="inputData.image = ''">删除</el-button>
            </div>
          </el-form-item>
          
          <!-- 视频输入 -->
          <el-form-item label="视频上传" v-if="inputType === 'video'">
            <el-upload
              class="video-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleVideoUpload"
              :show-file-list="false"
              accept="video/*"
            >
              <el-button size="large">
                <el-icon><upload /></el-icon>
                选择视频
              </el-button>
            </el-upload>
            <div v-if="inputData.video" class="video-preview">
              <video :src="inputData.video" controls width="400"></video>
              <el-button type="danger" size="small" @click="inputData.video = ''">删除</el-button>
            </div>
          </el-form-item>
          
          <!-- PLY文件输入 -->
          <el-form-item label="PLY文件上传" v-if="inputType === 'ply'">
            <el-upload
              class="ply-upload"
              action="#"
              :auto-upload="false"
              :on-change="handlePlyUpload"
              :show-file-list="false"
              accept=".ply"
            >
              <el-button size="large">
                <el-icon><upload /></el-icon>
                选择PLY文件
              </el-button>
            </el-upload>
            <div v-if="inputData.ply" class="ply-preview">
              <el-tag type="success">{{ getPlyFileName(inputData.ply) }}</el-tag>
              <el-button type="danger" size="small" @click="inputData.ply = ''">删除</el-button>
            </div>
          </el-form-item>
          
          <!-- 结构化数据输入 -->
          <el-form-item label="结构化数据" v-if="inputType === 'structured'">
            <el-input
              v-model="structuredInput"
              type="textarea"
              :rows="5"
              placeholder="请输入JSON格式的结构化数据"
            />
          </el-form-item>
          
          <!-- 输入类型选择 -->
          <el-form-item label="输入类型">
            <el-radio-group v-model="inputType" @change="handleInputTypeChange">
              <el-radio label="text">文本</el-radio>
              <el-radio label="image">图片</el-radio>
              <el-radio label="video">视频</el-radio>
              <el-radio label="ply">PLY文件</el-radio>
              <el-radio label="structured">结构化数据</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-card>
      
      <!-- 参数配置 -->
      <el-card class="params-card" v-if="currentVersion?.params">
        <template #header>
          <h2>参数配置</h2>
        </template>
        
        <el-form :model="algorithmParams" label-width="120px">
          <el-form-item 
            v-for="(paramConfig, paramName) in currentVersion.params" 
            :key="paramName"
            :label="paramName"
          >
            <!-- 数值参数 -->
            <el-input-number
              v-if="paramConfig.type === 'number'"
              v-model="algorithmParams[paramName]"
              :min="paramConfig.min"
              :max="paramConfig.max"
              :step="paramConfig.step || 0.1"
            />
            
            <!-- 字符串参数 -->
            <el-input
              v-else-if="paramConfig.type === 'string'"
              v-model="algorithmParams[paramName]"
              :placeholder="paramConfig.placeholder"
            />
            
            <!-- 布尔参数 -->
            <el-switch
              v-else-if="paramConfig.type === 'boolean'"
              v-model="algorithmParams[paramName]"
            />
            
            <!-- 下拉选择参数 -->
            <el-select
              v-else-if="paramConfig.options"
              v-model="algorithmParams[paramName]"
              placeholder="选择选项"
            >
              <el-option
                v-for="option in paramConfig.options"
                :key="option"
                :label="option"
                :value="option"
              />
            </el-select>
            
            <!-- 默认输入 -->
            <el-input
              v-else
              v-model="algorithmParams[paramName]"
              :placeholder="paramConfig.placeholder"
            />
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 调用按钮 -->
      <div class="call-section">
        <el-button 
          type="primary" 
          size="large" 
          :loading="calling" 
          @click="handleCallAlgorithm"
          :disabled="!selectedVersionId || !isInputValid"
        >
          调用算法
        </el-button>
      </div>
      
      <!-- 调用结果 -->
      <el-card v-if="algorithmStore.callResult" class="result-card">
        <template #header>
          <h2>调用结果</h2>
        </template>
        
        <div class="result-section">
          <div class="result-meta">
            <span class="meta-item">
              <el-icon><timer /></el-icon>
              响应时间: {{ algorithmStore.callResult.response_time }} 秒
            </span>
            <span class="meta-item">
              <el-icon><check /></el-icon>
              状态: {{ algorithmStore.callResult.status }}
            </span>
          </div>
          
          <div v-if="algorithmStore.callResult.status === 'success'" class="success-result">
            <pre>{{ JSON.stringify(algorithmStore.callResult.output_data, null, 2) }}</pre>
          </div>
          
          <div v-else class="error-result">
            <el-alert
              :title="algorithmStore.callResult.status"
              :description="algorithmStore.callResult.error_message"
              type="error"
              show-icon
            />
          </div>
        </div>
      </el-card>
    </template>
    
    <div v-else class="error-state">
      <el-icon class="error-icon"><warning /></el-icon>
      <p>获取算法信息失败</p>
      <router-link to="/algorithms" class="back-btn">
        <el-button type="primary">返回算法列表</el-button>
      </router-link>
    </div>
    
    <!-- OpenAI对话框 -->
    <el-dialog
      v-model="showOpenAIDialog"
      title="使用OpenAI生成输入数据"
      width="50%"
    >
      <el-form :model="openAIForm">
        <el-form-item label="描述">
          <el-input
            v-model="openAIForm.prompt"
            type="textarea"
            :rows="4"
            placeholder="请描述您需要的输入数据"
          />
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select v-model="openAIForm.dataType" placeholder="选择数据类型">
            <el-option label="文本" value="text" />
            <el-option label="结构化数据" value="structured" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showOpenAIDialog = false">取消</el-button>
          <el-button type="primary" @click="generateDataWithOpenAI" :loading="generatingData">生成</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAlgorithmStore } from '../stores/algorithm'
import { ChatDotRound, Upload, Warning, Timer, Check } from '@element-plus/icons-vue'

// 获取路由和存储
const route = useRoute()
const algorithmStore = useAlgorithmStore()

// 状态管理
const selectedVersionId = ref('')
const inputType = ref('text')
const inputData = ref({ text: '', image: '', video: '', ply: '', structured: {} })
const algorithmParams = ref({})
const calling = ref(false)
const showOpenAIDialog = ref(false)
const generatingData = ref(false)
const structuredInput = ref('')

// OpenAI表单
const openAIForm = ref({
  prompt: '',
  dataType: 'text'
})

// 计算当前选中的版本
const currentVersion = computed(() => {
  if (!algorithmStore.currentAlgorithm || !selectedVersionId.value) return null
  return algorithmStore.currentAlgorithm.versions.find(v => v.id === selectedVersionId.value)
})

// 检查输入是否有效
const isInputValid = computed(() => {
  if (inputType.value === 'text') {
    return inputData.value.text.trim() !== ''
  } else if (inputType.value === 'image') {
    return inputData.value.image !== ''
  } else if (inputType.value === 'video') {
    return inputData.value.video !== ''
  } else if (inputType.value === 'ply') {
    return inputData.value.ply !== ''
  } else if (inputType.value === 'structured') {
    try {
      JSON.parse(structuredInput.value)
      return true
    } catch {
      return false
    }
  }
  return false
})

// 处理版本变更
const handleVersionChange = () => {
  // 重置参数
  if (currentVersion.value?.params) {
    const params = {}
    for (const [key, config] of Object.entries(currentVersion.value.params)) {
      params[key] = config.default || ''
    }
    algorithmParams.value = params
  }
}

// 处理输入类型变更
const handleInputTypeChange = () => {
  // 重置输入数据
  inputData.value = { text: '', image: '', video: '', ply: '', structured: {} }
  structuredInput.value = ''
}

// 处理图片上传
const handleImageUpload = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    inputData.value.image = e.target?.result as string
  }
  reader.readAsDataURL(file.raw)
}

// 处理视频上传
const handleVideoUpload = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    inputData.value.video = e.target?.result as string
  }
  reader.readAsDataURL(file.raw)
}

// 处理PLY文件上传
const handlePlyUpload = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    inputData.value.ply = e.target?.result as string
  }
  reader.readAsDataURL(file.raw)
}

// 从data URL中提取PLY文件名
const getPlyFileName = (dataUrl: string) => {
  // 这里简单返回文件名，实际应用中可以从data URL或文件对象中提取更多信息
  return 'PLY文件'
}

// 处理算法调用
const handleCallAlgorithm = async () => {
  if (!selectedVersionId.value || !algorithmStore.currentAlgorithm) return
  
  calling.value = true
  
  // 准备输入数据
  let finalInputData: any = {}
  if (inputType.value === 'text') {
    finalInputData.text = inputData.value.text
  } else if (inputType.value === 'image') {
    finalInputData.image = inputData.value.image
  } else if (inputType.value === 'video') {
    finalInputData.video = inputData.value.video
  } else if (inputType.value === 'ply') {
    finalInputData.ply = inputData.value.ply
  } else if (inputType.value === 'structured') {
    try {
      finalInputData.structured = JSON.parse(structuredInput.value)
    } catch {
      finalInputData.structured = {}
    }
  }
  
  // 调用算法
  await algorithmStore.callAlgorithm({
    algorithm_id: algorithmStore.currentAlgorithm.id,
    version_id: selectedVersionId.value,
    input_data: finalInputData,
    params: algorithmParams.value
  })
  
  calling.value = false
}

// 使用OpenAI生成数据
const generateDataWithOpenAI = async () => {
  if (!openAIForm.value.prompt) return
  
  generatingData.value = true
  
  // 调用OpenAI生成数据
  const result = await algorithmStore.generateSimulationData(openAIForm.value.prompt, openAIForm.value.dataType)
  
  if (result) {
    if (openAIForm.value.dataType === 'text') {
      inputType.value = 'text'
      inputData.value.text = result.data
    } else if (openAIForm.value.dataType === 'structured') {
      inputType.value = 'structured'
      structuredInput.value = JSON.stringify(result.data, null, 2)
    }
  }
  
  generatingData.value = false
  showOpenAIDialog.value = false
}

// 加载算法详情
onMounted(async () => {
  const algorithmId = route.params.id as string
  const versionId = route.query.version_id as string
  
  if (algorithmId) {
    await algorithmStore.fetchAlgorithmDetail(algorithmId)
    
    // 如果指定了版本，选择该版本
    if (versionId) {
      selectedVersionId.value = versionId
    } else if (algorithmStore.currentAlgorithm?.versions.length > 0) {
      // 否则选择默认版本或第一个版本
      const defaultVersion = algorithmStore.currentAlgorithm.versions.find(v => v.is_default)
      selectedVersionId.value = defaultVersion?.id || algorithmStore.currentAlgorithm.versions[0].id
    }
    
    // 初始化参数
    handleVersionChange()
  }
})
</script>

<style scoped>
.algorithm-call-container {
  max-width: 1200px;
  margin: 0 auto;
}

.breadcrumb {
  margin-bottom: 20px;
}

.algorithm-info-card {
  margin-bottom: 20px;
}

.algorithm-info-card h1 {
  font-size: 24px;
  margin-bottom: 10px;
  color: #333;
}

.algorithm-description {
  color: #606266;
  line-height: 1.6;
}

.version-select-card,
.input-card,
.params-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  font-size: 18px;
  margin: 0;
  color: #333;
}

.input-section {
  margin-top: 10px;
}

.image-upload {
  margin-bottom: 20px;
}

.image-preview {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.image-preview img {
  max-width: 300px;
  max-height: 200px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.video-preview {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.video-preview video {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 10px;
}

.video-preview .el-button {
  align-self: flex-start;
}

.ply-upload {
  margin-bottom: 20px;
}

.ply-preview {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.ply-preview .el-tag {
  margin-right: 10px;
}

.call-section {
  margin: 30px 0;
  text-align: center;
}

.result-card {
  margin-top: 30px;
}

.result-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.success-result pre {
  background-color: #f0f9eb;
  padding: 20px;
  border-radius: 4px;
  border: 1px solid #e1f3d8;
  color: #67c23a;
  overflow-x: auto;
}

.error-result {
  margin-top: 20px;
}

.error-state {
  text-align: center;
  padding: 60px 0;
  color: #909399;
}

.error-icon {
  font-size: 64px;
  margin-bottom: 20px;
  color: #F56C6C;
}

.error-state p {
  font-size: 18px;
  margin-bottom: 30px;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .result-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .image-preview {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .image-preview img {
    max-width: 100%;
  }
}
</style>
