<template>
  <div class="algorithm-versions-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="versions-card">
        <template #header>
          <div class="card-header">
            <h2>版本列表</h2>
            <el-button type="primary" @click="showAddVersionDialog = true">
              <el-icon><plus /></el-icon>
              添加版本
            </el-button>
          </div>
        </template>
        
        <el-table :data="algorithmStore.currentAlgorithm.versions" style="width: 100%">
          <el-table-column prop="version" label="版本号" width="120" />
          <el-table-column prop="url" label="API地址" />
          <el-table-column prop="is_default" label="默认版本" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.is_default" type="success">是</el-tag>
              <el-tag v-else type="info">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="380">
            <template #default="scope">
              <el-button size="small" @click="editVersion(scope.row)">编辑</el-button>
              <el-button size="small" type="primary" @click="executeCode(scope.row)">执行代码</el-button>
              <el-button size="small" type="success" @click="runAlgorithm(scope.row)">执行算法</el-button>
              <el-button size="small" type="danger" @click="deleteVersion(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </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>
    
    <!-- 添加版本对话框 -->
    <el-dialog
      v-model="showAddVersionDialog"
      title="添加版本"
      width="70%"
    >
      <el-form :model="versionForm" :rules="versionRules" ref="versionFormRef">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="versionForm.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="API地址" prop="url">
          <el-input v-model="versionForm.url" placeholder="请输入算法API地址" />
        </el-form-item>
        <el-form-item label="默认版本">
          <el-switch v-model="versionForm.is_default" />
        </el-form-item>
        <el-form-item label="参数配置">
          <el-input
            v-model="versionForm.params"
            type="textarea"
            :rows="3"
            placeholder="请输入JSON格式的参数配置"
          />
        </el-form-item>
        <el-form-item label="输入模式">
          <el-input
            v-model="versionForm.input_schema"
            type="textarea"
            :rows="3"
            placeholder="请输入JSON格式的输入模式"
          />
        </el-form-item>
        <el-form-item label="输出模式">
          <el-input
            v-model="versionForm.output_schema"
            type="textarea"
            :rows="3"
            placeholder="请输入JSON格式的输出模式"
          />
        </el-form-item>
        <el-form-item label="算法代码">
          <div ref="codeEditorContainer" style="height: 400px; width: 100%"></div>
        </el-form-item>
        <el-form-item label="模型名字">
          <el-input v-model="versionForm.model_name" placeholder="请输入API训练后的模型名字" />
        </el-form-item>
        <el-form-item label="模型文件">
          <el-upload
            class="model-file-uploader"
            action="/api/algorithms/upload-model"
            :headers="{ 'Authorization': `Bearer ${localStorage.getItem('token')}` }"
            :on-success="handleModelFileUpload"
            :on-error="handleModelFileUploadError"
            :file-list="modelFileList"
            :auto-upload="false"
            ref="modelFileUploadRef"
            accept=".pt,.pth,.h5,.hdf5,.onnx,.pb,.tflite,.joblib,.pkl,.zip,.tar.gz"
          >
            <el-button type="primary">
              <el-icon><upload /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持的文件类型：.pt, .pth, .h5, .hdf5, .onnx, .pb, .tflite, .joblib, .pkl, .zip, .tar.gz
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="API用法">
          <el-input
            v-model="versionForm.api_doc"
            type="textarea"
            :rows="5"
            placeholder="请输入模型的API用法文档，包括input参数和返回内容类型"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddVersionDialog = false">取消</el-button>
          <el-button type="primary" @click="addVersion">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑版本对话框 -->
    <el-dialog
      v-model="showEditVersionDialog"
      title="编辑版本"
      width="70%"
    >
      <el-form :model="editVersionForm" :rules="versionRules" ref="editVersionFormRef">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="editVersionForm.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="API地址" prop="url">
          <el-input v-model="editVersionForm.url" placeholder="请输入算法API地址" />
        </el-form-item>
        <el-form-item label="默认版本">
          <el-switch v-model="editVersionForm.is_default" />
        </el-form-item>
        <el-form-item label="参数配置">
          <el-input
            v-model="editVersionForm.params"
            type="textarea"
            :rows="3"
            placeholder="请输入JSON格式的参数配置"
          />
        </el-form-item>
        <el-form-item label="输入模式">
          <el-input
            v-model="editVersionForm.input_schema"
            type="textarea"
            :rows="3"
            placeholder="请输入JSON格式的输入模式"
          />
        </el-form-item>
        <el-form-item label="输出模式">
          <el-input
            v-model="editVersionForm.output_schema"
            type="textarea"
            :rows="3"
            placeholder="请输入JSON格式的输出模式"
          />
        </el-form-item>
        <el-form-item label="算法代码">
          <div ref="editCodeEditorContainer" style="height: 400px; width: 100%"></div>
        </el-form-item>
        <el-form-item label="模型名字">
          <el-input v-model="editVersionForm.model_name" placeholder="请输入API训练后的模型名字" />
        </el-form-item>
        <el-form-item label="模型文件">
          <el-input v-model="editVersionForm.model_file" placeholder="请输入模型文件路径" />
        </el-form-item>
        <el-form-item label="API用法">
          <el-input
            v-model="editVersionForm.api_doc"
            type="textarea"
            :rows="5"
            placeholder="请输入模型的API用法文档，包括input参数和返回内容类型"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditVersionDialog = false">取消</el-button>
          <el-button type="primary" @click="updateVersion">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 代码执行结果对话框 -->
    <el-dialog
      v-model="showCodeExecutionDialog"
      title="代码执行结果"
      width="70%"
    >
      <div class="code-execution-result">
        <div v-if="codeExecutionLoading" class="loading-state">
          <el-icon class="loading-icon"><loading /></el-icon>
          <p>执行中...</p>
        </div>
        <div v-else>
          <el-form-item label="执行状态">
            <el-tag :type="codeExecutionResult.success ? 'success' : 'danger'">
              {{ codeExecutionResult.success ? '成功' : '失败' }}
            </el-tag>
          </el-form-item>
          <el-form-item label="执行输出">
            <el-input
              v-model="codeExecutionResult.output"
              type="textarea"
              :rows="10"
              readonly
              placeholder="执行输出"
            />
          </el-form-item>
          <el-form-item v-if="codeExecutionResult.error" label="错误信息">
            <el-input
              v-model="codeExecutionResult.error"
              type="textarea"
              :rows="5"
              readonly
              placeholder="错误信息"
            />
          </el-form-item>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCodeExecutionDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAlgorithmStore } from '../stores/algorithm'
import { Plus, Warning, Loading, Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as monaco from 'monaco-editor'

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

// 状态管理
const showAddVersionDialog = ref(false)
const showEditVersionDialog = ref(false)
const showCodeExecutionDialog = ref(false)
const versionFormRef = ref()
const editVersionFormRef = ref()
const codeEditorContainer = ref<HTMLElement>()
const editCodeEditorContainer = ref<HTMLElement>()
const codeEditor = ref<monaco.editor.IStandaloneCodeEditor>()
const editCodeEditor = ref<monaco.editor.IStandaloneCodeEditor>()
const currentVersionId = ref('')
const modelFileUploadRef = ref<any>(null)
const modelFileList = ref<any[]>([])
const versionForm = ref({
  version: '',
  url: '',
  is_default: false,
  params: '{}',
  input_schema: '{}',
  output_schema: '{}',
  code: '',
  model_name: '',
  model_file: '',
  api_doc: ''
})
const editVersionForm = ref({
  version: '',
  url: '',
  is_default: false,
  params: '{}',
  input_schema: '{}',
  output_schema: '{}',
  code: '',
  model_name: '',
  model_file: '',
  api_doc: ''
})
const codeExecutionLoading = ref(false)
const codeExecutionResult = ref({
  success: false,
  output: '',
  error: ''
})

// 表单验证规则
const versionRules = ref({
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入API地址', trigger: 'blur' }
  ]
})

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 添加版本
const addVersion = async () => {
  if (!versionFormRef.value) return
  
  // 从编辑器中获取代码内容
  if (codeEditor.value) {
    versionForm.value.code = codeEditor.value.getValue()
  }
  
  // 验证表单
  await versionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 解析JSON字段
      try {
        const params = JSON.parse(versionForm.value.params)
        const input_schema = JSON.parse(versionForm.value.input_schema)
        const output_schema = JSON.parse(versionForm.value.output_schema)
        
        // 这里应该调用后端API添加版本
        // 暂时模拟添加
        console.log('添加版本:', {
          ...versionForm.value,
          params,
          input_schema,
          output_schema
        })
        
        // 关闭对话框
        showAddVersionDialog.value = false
        
        // 重置表单
        versionForm.value = {
          version: '',
          url: '',
          is_default: false,
          params: '{}',
          input_schema: '{}',
          output_schema: '{}',
          code: '',
          model_name: '',
          model_file: '',
          api_doc: ''
        }
        
        // 重置编辑器内容
        if (codeEditor.value) {
          codeEditor.value.setValue('')
        }
        
        // 重新加载版本列表
        if (algorithmStore.currentAlgorithm) {
          await algorithmStore.fetchAlgorithmDetail(algorithmStore.currentAlgorithm.id)
        }
      } catch (error) {
        alert('JSON格式错误，请检查输入')
      }
    }
  })
}

// 初始化代码编辑器
const initCodeEditor = () => {
  if (codeEditorContainer.value && !codeEditor.value) {
    codeEditor.value = monaco.editor.create(codeEditorContainer.value, {
      value: versionForm.value.code,
      language: 'python',
      theme: 'vs-dark',
      automaticLayout: true,
      minimap: {
        enabled: true
      },
      scrollBeyondLastLine: false,
      renderIndentGuides: true,
      fontSize: 14,
      tabSize: 4
    })
  }
}

// 初始化编辑代码编辑器
const initEditCodeEditor = () => {
  if (editCodeEditorContainer.value && !editCodeEditor.value) {
    editCodeEditor.value = monaco.editor.create(editCodeEditorContainer.value, {
      value: editVersionForm.value.code,
      language: 'python',
      theme: 'vs-dark',
      automaticLayout: true,
      minimap: {
        enabled: true
      },
      scrollBeyondLastLine: false,
      renderIndentGuides: true,
      fontSize: 14,
      tabSize: 4
    })
  }
}

// 销毁代码编辑器
const destroyCodeEditor = () => {
  if (codeEditor.value) {
    codeEditor.value.dispose()
    codeEditor.value = undefined
  }
}

// 销毁编辑代码编辑器
const destroyEditCodeEditor = () => {
  if (editCodeEditor.value) {
    editCodeEditor.value.dispose()
    editCodeEditor.value = undefined
  }
}

// 监听添加对话框显示状态，初始化或更新编辑器
watch(showAddVersionDialog, (newVal) => {
  if (newVal) {
    // 对话框显示后，等待DOM更新，然后初始化编辑器
    setTimeout(() => {
      initCodeEditor()
    }, 100)
  }
})

// 监听编辑对话框显示状态，初始化或更新编辑器
watch(showEditVersionDialog, (newVal) => {
  if (newVal) {
    // 对话框显示后，等待DOM更新，然后初始化编辑器
    setTimeout(() => {
      initEditCodeEditor()
    }, 100)
  }
})

// 编辑版本
const editVersion = (version: any) => {
  // 填充编辑表单
  editVersionForm.value = {
    version: version.version,
    url: version.url,
    is_default: version.is_default,
    params: JSON.stringify(version.params || {}, null, 2),
    input_schema: JSON.stringify(version.input_schema || {}, null, 2),
    output_schema: JSON.stringify(version.output_schema || {}, null, 2),
    code: version.code || '',
    model_name: version.model_name || '',
    model_file: version.model_file || '',
    api_doc: version.api_doc || ''
  }
  
  // 保存当前版本ID
  currentVersionId.value = version.id
  
  // 显示编辑对话框
  showEditVersionDialog.value = true
}

// 更新版本
const updateVersion = async () => {
  if (!editVersionFormRef.value) return
  
  // 从编辑器中获取代码内容
  if (editCodeEditor.value) {
    editVersionForm.value.code = editCodeEditor.value.getValue()
  }
  
  // 验证表单
  await editVersionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 解析JSON字段
      try {
        const params = JSON.parse(editVersionForm.value.params)
        const input_schema = JSON.parse(editVersionForm.value.input_schema)
        const output_schema = JSON.parse(editVersionForm.value.output_schema)
        
        // 这里应该调用后端API更新版本
        // 暂时模拟更新
        console.log('更新版本:', {
          id: currentVersionId.value,
          ...editVersionForm.value,
          params,
          input_schema,
          output_schema
        })
        
        // 关闭对话框
        showEditVersionDialog.value = false
        
        // 重新加载版本列表
        if (algorithmStore.currentAlgorithm) {
          await algorithmStore.fetchAlgorithmDetail(algorithmStore.currentAlgorithm.id)
        }
      } catch (error) {
        alert('JSON格式错误，请检查输入')
      }
    }
  })
}

// 执行代码
const executeCode = async (version: any) => {
  // 显示执行结果对话框
  showCodeExecutionDialog.value = true
  codeExecutionLoading.value = true
  codeExecutionResult.value = {
    success: false,
    output: '',
    error: ''
  }
  
  try {
    // 检查代码是否为空
    if (!version.code) {
      codeExecutionResult.value = {
        success: false,
        output: '',
        error: '代码为空，无法执行'
      }
      return
    }
    
    // 调用后端API执行代码
        const response = await fetch('/api/algorithms/execute-code', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({ code: version.code })
    })
    
    // 处理响应
    if (response.ok) {
      const result = await response.json()
      codeExecutionResult.value = result
    } else {
      const error = await response.json()
      codeExecutionResult.value = {
        success: false,
        output: '',
        error: error.detail || '执行请求失败'
      }
    }
  } catch (error) {
    codeExecutionResult.value = {
      success: false,
      output: '',
      error: `执行错误: ${error}`
    }
  } finally {
    codeExecutionLoading.value = false
  }
}

// 删除版本
const deleteVersion = (versionId: string) => {
  // 这里应该调用后端API删除版本，暂时打印
  console.log('删除版本:', versionId)
}

// 处理模型文件上传成功
const handleModelFileUpload = (response: any, uploadFile: any) => {
  if (response.success) {
    versionForm.value.model_file = response.file_path
    modelFileList.value = [{ name: uploadFile.name, url: response.file_path }]
    ElMessage.success('模型文件上传成功')
  } else {
    ElMessage.error('模型文件上传失败: ' + response.message)
  }
}

// 处理模型文件上传失败
const handleModelFileUploadError = (error: any) => {
  ElMessage.error('模型文件上传失败: ' + error.message)
}

// 手动触发模型文件上传
const uploadModelFile = () => {
  if (modelFileUploadRef.value) {
    modelFileUploadRef.value.submit()
  }
}

// 执行算法
const runAlgorithm = async (version: any) => {
  // 这里应该调用后端API执行算法
  // 暂时模拟执行
  ElMessage.info('执行算法: ' + version.version)
  console.log('执行算法:', version)
}

// 加载算法详情
onMounted(async () => {
  const algorithmId = route.params.id as string
  if (algorithmId) {
    await algorithmStore.fetchAlgorithmDetail(algorithmId)
  }
})

// 组件卸载时销毁编辑器
onUnmounted(() => {
  destroyCodeEditor()
  destroyEditCodeEditor()
})
</script>

<style scoped>
.algorithm-versions-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;
}

.versions-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;
}

.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;
  }
}

/* 代码执行结果样式 */
.code-execution-result {
  margin-top: 20px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
}

.loading-icon {
  font-size: 48px;
  margin-bottom: 20px;
  color: #409EFF;
}

.loading-state p {
  font-size: 16px;
  color: #606266;
}
</style>
