<template>
  <div class="algorithm-call-advanced">
    <!-- 算法信息 -->
    <el-card class="algorithm-info-card">
      <template #header>
        <div class="card-header">
          <h2>{{ algorithm?.name || 'N/A' }}</h2>
          <el-tag :type="getStatusType(algorithm?.status || '')">
            {{ algorithm?.status || 'N/A' }}
          </el-tag>
        </div>
      </template>
      
      <p class="algorithm-description">{{ algorithm?.description }}</p>
      
      <div class="algorithm-meta">
        <el-descriptions :column="2" size="small" border>
          <el-descriptions-item label="类型">{{ algorithm?.type || 'N/A' }}</el-descriptions-item>
          <el-descriptions-item label="版本数量">{{ algorithm?.versions?.length || 0 }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(algorithm?.created_at || '') }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(algorithm?.updated_at || '') }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
    
    <!-- 版本选择和参数配置 -->
    <el-card class="configuration-card">
      <template #header>
        <h3>配置选项</h3>
      </template>
      
      <el-form :model="config" label-width="120px">
        <el-form-item label="算法版本">
          <el-select 
            v-model="config.versionId" 
            placeholder="请选择算法版本"
            @change="onVersionChange"
            style="width: 100%"
          >
            <el-option
              v-for="version in algorithm?.versions || []"
              :key="version.id"
              :label="`${version.version}${version.is_default ? ' (默认)' : ''}`"
              :value="version.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="调用参数">
          <div class="params-container">
            <el-row :gutter="20">
              <el-col 
                v-for="(param, key) in currentVersion?.params || {}" 
                :key="key" 
                :span="12"
              >
                <el-form-item :label="key">
                  <component
                    :is="getParamInputComponent(param)"
                    v-model="config.params[key]"
                    v-bind="getParamInputProps(param)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 输入数据区域 -->
    <el-card class="input-data-card">
      <template #header>
        <div class="card-header">
          <h3>输入数据</h3>
          <el-button @click="showSimulator = true">
            <el-icon><MagicStick /></el-icon>
            启动仿真输入生成器
          </el-button>
        </div>
      </template>
      
      <el-tabs v-model="inputTab" type="card">
        <el-tab-pane label="文本输入" name="text">
          <el-input
            v-model="inputData.text"
            type="textarea"
            :rows="6"
            placeholder="请输入文本数据"
          />
        </el-tab-pane>
        
        <el-tab-pane label="文件上传" name="files">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action="/api/data/media/upload"
            :headers="authHeaders"
            :before-upload="beforeFileUpload"
            :on-success="onFileUploadSuccess"
            :on-error="onFileUploadError"
            multiple
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持图片、文档等文件类型
              </div>
            </template>
          </el-upload>
        </el-tab-pane>
        
        <el-tab-pane label="结构化数据" name="structured">
          <json-editor
            v-model="inputData.structured"
            :height="300"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 调用控制 -->
    <div class="call-controls">
      <el-button 
        type="primary" 
        size="large" 
        :loading="isCalling" 
        @click="callAlgorithm"
        :disabled="!canCall"
      >
        <el-icon><VideoPlay /></el-icon>
        执行算法
      </el-button>
      
      <el-button 
        size="large" 
        @click="clearResults"
      >
        <el-icon><Delete /></el-icon>
        清空结果
      </el-button>
    </div>
    
    <!-- 执行结果 -->
    <el-card v-if="result" class="result-card">
      <template #header>
        <div class="card-header">
          <h3>执行结果</h3>
          <el-tag :type="getResultStatusType(result.status)">
            {{ result.status }}
          </el-tag>
        </div>
      </template>
      
      <div class="result-content">
        <div class="result-metadata">
          <el-descriptions :column="3" size="small">
            <el-descriptions-item label="执行时间">
              {{ result.response_time ? `${result.response_time}s` : 'N/A' }}
            </el-descriptions-item>
            <el-descriptions-item label="执行时间">
              {{ formatDate(result.created_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="调用ID">
              {{ result.id }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div v-if="result.status === 'success'" class="success-result">
          <h4>输出数据</h4>
          <json-editor
            :value="result.output_data"
            :height="400"
            :readonly="true"
          />
        </div>
        
        <div v-else class="error-result">
          <el-alert
            :title="result.status"
            :description="result.error_message || '未知错误'"
            type="error"
            show-icon
          />
        </div>
      </div>
    </el-card>
    
    <!-- 仿真输入生成器对话框 -->
    <el-dialog
      v-model="showSimulator"
      title="仿真输入生成器"
      width="80%"
      top="5vh"
    >
      <simulation-input-generator @data-generated="onSimulatedDataGenerated" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAlgorithmStore } from '../../stores/algorithm'
import { useUserStore } from '../../stores/user'
import { ElMessage } from 'element-plus'
import { 
  MagicStick, 
  VideoPlay, 
  Delete 
} from '@element-plus/icons-vue'
import SimulationInputGenerator from '../SimulationInputGenerator.vue'
import JsonEditor from '../common/JsonEditor.vue'

// 类型定义
interface Algorithm {
  id: string
  name: string
  description: string
  type: string
  status: string
  versions: AlgorithmVersion[]
  created_at: string
  updated_at: string
}

interface AlgorithmVersion {
  id: string
  algorithm_id: string
  version: string
  url: string
  params: Record<string, any>
  input_schema: any
  output_schema: any
  is_default: boolean
  created_at: string
  updated_at: string
}

// 定义props和emit
interface Props {
  algorithmId?: string
}

const props = defineProps<Props>()

// 状态
const algorithmStore = useAlgorithmStore()
const userStore = useUserStore()
const route = useRoute()

const config = reactive<{versionId: string, params: Record<string, any>}>({
  versionId: '',
  params: {}
})

const inputData = reactive({
  text: '',
  structured: {},
  files: []
})

const result = ref<any>(null)
const isCalling = ref(false)
const showSimulator = ref(false)
const inputTab = ref('text')
const fileList = ref<any[]>([])

// 计算属性
const algorithm = computed<Algorithm | null>(() => algorithmStore.currentAlgorithm)
const currentVersion = computed(() => {
  return algorithm.value?.versions?.find(v => v.id === config.versionId)
})

const canCall = computed(() => {
  return config.versionId && 
         (inputData.text || Object.keys(inputData.structured).length > 0 || fileList.value.length > 0)
})

const authHeaders = computed(() => {
  return {
    Authorization: `Bearer ${localStorage.getItem('token')}`
  }
})

// 方法
const loadAlgorithm = async (id: string) => {
  try {
    await algorithmStore.fetchAlgorithmDetail(id)
    
    // 选择默认版本
    if (algorithm.value?.versions && algorithm.value.versions.length > 0) {
      const defaultVersion = algorithm.value.versions.find(v => v.is_default)
      config.versionId = defaultVersion?.id || algorithm.value.versions[0].id
      
      // 初始化参数
      onVersionChange()
    }
  } catch (error) {
    console.error('Failed to load algorithm:', error)
    ElMessage.error('加载算法信息失败')
  }
}

const onVersionChange = () => {
  if (currentVersion.value?.params) {
    // 初始化参数值
    Object.keys(currentVersion.value.params).forEach(key => {
      const param = currentVersion.value!.params[key]
      config.params[key] = param.default || getDefaultParamValue(param)
    })
  }
}

const getDefaultParamValue = (param: any) => {
  if (param.type === 'number') return param.default || 0
  if (param.type === 'boolean') return param.default || false
  if (param.options && param.options.length > 0) return param.options[0]
  return param.default || ''
}

const getParamInputComponent = (param: any) => {
  if (param.type === 'boolean') return 'el-switch'
  if (param.options && param.options.length > 0) return 'el-select'
  if (param.type === 'number') return 'el-input-number'
  return 'el-input'
}

const getParamInputProps = (param: any) => {
  if (param.type === 'boolean') return {}
  if (param.type === 'number') {
    return {
      min: param.min,
      max: param.max,
      step: param.step || 1
    }
  }
  if (param.options) {
    return {
      options: param.options.map((opt: any) => ({ label: opt, value: opt }))
    }
  }
  return {
    placeholder: param.description || `请输入${param.name || '参数'}`
  }
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'active': return 'success'
    case 'inactive': return 'info'
    case 'deprecated': return 'warning'
    default: return 'info'
  }
}

const getResultStatusType = (status: string) => {
  switch (status) {
    case 'success': return 'success'
    case 'failed': return 'error'
    case 'running': return 'warning'
    default: return 'info'
  }
}

const formatDate = (dateString: string) => {
  if (!dateString) return 'N/A'
  return new Date(dateString).toLocaleString()
}

const callAlgorithm = async () => {
  if (!canCall.value) {
    ElMessage.warning('请填写必要参数和输入数据')
    return
  }
  
  isCalling.value = true
  
  try {
    // 准备输入数据
    let preparedInputData: any = {}
    
    if (inputData.text) {
      preparedInputData.text = inputData.text
    }
    
    if (Object.keys(inputData.structured).length > 0) {
      preparedInputData.structured = inputData.structured
    }
    
    if (fileList.value.length > 0) {
      preparedInputData.files = fileList.value.map(file => ({
        name: file.name,
        url: file.url,
        size: file.size
      }))
    }
    
    // 调用算法
    const callResult = await algorithmStore.callAlgorithm({
      algorithm_id: algorithm.value!.id,
      version_id: config.versionId,
      input_data: preparedInputData,
      params: config.params
    })
    
    if (callResult) {
      result.value = algorithmStore.callResult
      ElMessage.success('算法执行成功！')
    } else {
      ElMessage.error('算法执行失败')
    }
  } catch (error) {
    console.error('Algorithm call error:', error)
    ElMessage.error('算法执行过程中发生错误')
  } finally {
    isCalling.value = false
  }
}

const clearResults = () => {
  result.value = null
  ElMessage.info('结果已清空')
}

const beforeFileUpload = (file: File) => {
  // 文件类型和大小验证
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'text/plain']
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('不支持的文件类型')
    return false
  }
  
  if (file.size > 10 * 1024 * 1024) { // 10MB
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  
  return true
}

const onFileUploadSuccess = (response: any) => {
  ElMessage.success('文件上传成功')
}

const onFileUploadError = (error: any) => {
  console.error('File upload error:', error)
  ElMessage.error('文件上传失败')
}

const onSimulatedDataGenerated = (data: any) => {
  // 将生成的数据应用到输入区域
  if (typeof data === 'string') {
    inputTab.value = 'text'
    inputData.text = data
  } else if (typeof data === 'object') {
    inputTab.value = 'structured'
    inputData.structured = data
  }
  
  showSimulator.value = false
  ElMessage.success('仿真数据已应用')
}

// 监听props变化
watch(() => props.algorithmId, (newId) => {
  if (newId) {
    loadAlgorithm(newId)
  }
})

// 初始化
onMounted(() => {
  if (props.algorithmId) {
    loadAlgorithm(props.algorithmId)
  } else if (route.params.id) {
    loadAlgorithm(route.params.id as string)
  }
})
</script>

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

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

.configuration-card,
.input-data-card,
.result-card {
  margin-bottom: 20px;
}

.params-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.call-controls {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin: 30px 0;
}

.result-content {
  padding: 15px 0;
}

.result-metadata {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.success-result,
.error-result {
  margin-top: 15px;
}

.success-result :deep(.json-editor) {
  border: 1px solid #e1f3d8;
  border-radius: 4px;
}

.error-result {
  padding: 15px;
  background-color: #fef0f0;
  border-radius: 4px;
}

:deep(.el-descriptions__body) {
  background-color: #fafafa;
}
</style>
</template>
</file_path>