<template>
  <div class="simulation-input-generator">
    <el-card class="input-card">
      <template #header>
        <div class="card-header">
          <span>仿真输入生成器</span>
        </div>
      </template>
      
      <el-form :model="form" label-width="120px">
        <el-form-item label="生成方式">
          <el-radio-group v-model="form.method" @change="handleMethodChange">
            <el-radio label="openai">通过OpenAI生成</el-radio>
            <el-radio label="template">使用预设模板</el-radio>
            <el-radio label="manual">手动输入</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- OpenAI生成选项 -->
        <div v-if="form.method === 'openai'">
          <el-form-item label="描述提示">
            <el-input
              v-model="form.prompt"
              type="textarea"
              :rows="4"
              placeholder="描述你想要的输入数据，例如：'一张包含猫和狗的照片' 或 '包含年龄、姓名、邮箱的用户数据'"
            />
          </el-form-item>
          
          <el-form-item label="数据类型">
            <el-select v-model="form.dataType" placeholder="请选择数据类型">
              <el-option label="文本" value="text" />
              <el-option label="结构化数据" value="structured" />
              <el-option label="图像描述" value="image" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="loading" 
              @click="generateWithOpenAI"
              :disabled="!form.prompt"
            >
              生成仿真数据
            </el-button>
          </el-form-item>
        </div>
        
        <!-- 预设模板选项 -->
        <div v-if="form.method === 'template'">
          <el-form-item label="选择模板">
            <el-select v-model="form.selectedTemplate" placeholder="请选择模板" @change="loadTemplateData">
              <el-option
                v-for="template in templates"
                :key="template.id"
                :label="template.name"
                :value="template.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="模板预览">
            <pre class="template-preview">{{ templatePreview }}</pre>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              @click="useTemplate"
              :disabled="!form.selectedTemplate"
            >
              使用此模板
            </el-button>
          </el-form-item>
        </div>
        
        <!-- 手动输入选项 -->
        <div v-if="form.method === 'manual'">
          <el-form-item label="输入类型">
            <el-radio-group v-model="form.manualType">
              <el-radio label="json">JSON数据</el-radio>
              <el-radio label="text">纯文本</el-radio>
              <el-radio label="file">文件上传</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="输入数据" v-if="form.manualType !== 'file'">
            <el-input
              v-if="form.manualType === 'text'"
              v-model="form.manualData"
              type="textarea"
              :rows="6"
              placeholder="请输入文本数据"
            />
            <json-editor
              v-else-if="form.manualType === 'json'"
              v-model="form.jsonData"
              :height="200"
            />
          </el-form-item>
          
          <el-form-item label="上传文件" v-if="form.manualType === 'file'">
            <el-upload
              class="upload-demo"
              drag
              :action="uploadUrl"
              :on-success="handleFileUploadSuccess"
              :on-error="handleFileUploadError"
              :headers="authHeaders"
              multiple
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或<em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      
      <!-- 生成结果预览 -->
      <div v-if="generatedData" class="result-section">
        <h3>生成的数据预览</h3>
        <div class="result-preview">
          <json-editor
            v-if="isJsonData(generatedData)"
            :value="generatedData"
            :height="200"
            :readonly="true"
          />
          <pre v-else-if="typeof generatedData === 'string'" class="text-result">
            {{ generatedData }}
          </pre>
          <div v-else class="other-result">
            {{ JSON.stringify(generatedData, null, 2) }}
          </div>
        </div>
        
        <div class="result-actions">
          <el-button @click="copyToClipboard">复制到剪贴板</el-button>
          <el-button type="primary" @click="emitGeneratedData">使用此数据</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import JsonEditor from './common/JsonEditor.vue' // 假设我们有一个JSON编辑器组件
import { useAlgorithmStore } from '../stores/algorithm'

// 定义组件属性和事件
const emit = defineEmits(['data-generated'])

// 状态
const loading = ref(false)
const generatedData = ref<any>(null)
const templatePreview = ref('')

// 表单数据
const form = reactive({
  method: 'openai', // 'openai', 'template', 'manual'
  prompt: '',
  dataType: 'text',
  selectedTemplate: '',
  manualType: 'json',
  manualData: '',
  jsonData: {}
})

// 模拟模板数据
const templates = ref([
  {
    id: 'image-classification',
    name: '图像分类输入',
    description: '适用于图像分类算法的标准输入格式',
    data: {
      image_url: 'https://example.com/sample.jpg',
      preprocessing: {
        resize: [224, 224],
        normalize: [0.485, 0.456, 0.406, 0.229, 0.224, 0.225]
      }
    }
  },
  {
    id: 'text-classification',
    name: '文本分类输入',
    description: '适用于文本分类算法的标准输入格式',
    data: {
      text: '这是一个示例文本，用于文本分类任务',
      language: 'zh',
      max_length: 512
    }
  },
  {
    id: 'tabular-data',
    name: '表格数据输入',
    description: '适用于机器学习模型的表格数据输入',
    data: {
      features: ['age', 'income', 'education'],
      values: [25, 50000, 'bachelor'],
      target_column: 'prediction'
    }
  }
])

// 计算属性
const uploadUrl = computed(() => {
  // 返回文件上传的API端点
  return '/api/data/media/upload'
})

const authHeaders = computed(() => {
  // 返回认证头部
  const token = localStorage.getItem('token')
  return {
    Authorization: `Bearer ${token}`
  }
})

// 方法
const generateWithOpenAI = async () => {
  if (!form.prompt) {
    ElMessage.warning('请输入描述提示')
    return
  }
  
  loading.value = true
  try {
    const algorithmStore = useAlgorithmStore()
    const result = await algorithmStore.generateSimulationData(form.prompt, form.dataType)
    
    if (result) {
      generatedData.value = result.data
      ElMessage.success('仿真数据生成成功！')
    } else {
      ElMessage.error('生成仿真数据失败')
    }
  } catch (error) {
    console.error('Error generating simulation data:', error)
    ElMessage.error('生成仿真数据时发生错误')
  } finally {
    loading.value = false
  }
}

const loadTemplateData = (templateId: string) => {
  const template = templates.value.find(t => t.id === templateId)
  if (template) {
    templatePreview.value = JSON.stringify(template.data, null, 2)
  }
}

const useTemplate = () => {
  const template = templates.value.find(t => t.id === form.selectedTemplate)
  if (template) {
    generatedData.value = template.data
    ElMessage.success('模板数据已加载')
  }
}

const handleMethodChange = () => {
  // 重置相关字段
  if (form.method !== 'template') {
    form.selectedTemplate = ''
    templatePreview.value = ''
  }
  if (form.method !== 'manual') {
    form.manualData = ''
    form.jsonData = {}
  }
}

const isJsonData = (data: any) => {
  try {
    if (typeof data === 'object' && data !== null) {
      return true
    }
    JSON.parse(typeof data === 'string' ? data : JSON.stringify(data))
    return true
  } catch {
    return false
  }
}

const copyToClipboard = () => {
  if (!generatedData.value) return
  
  const textToCopy = typeof generatedData.value === 'string' 
    ? generatedData.value 
    : JSON.stringify(generatedData.value, null, 2)
  
  navigator.clipboard.writeText(textToCopy)
    .then(() => {
      ElMessage.success('已复制到剪贴板')
    })
    .catch(err => {
      console.error('Failed to copy: ', err)
      ElMessage.error('复制失败')
    })
}

const emitGeneratedData = () => {
  if (!generatedData.value) {
    ElMessage.warning('没有可使用的数据')
    return
  }
  
  emit('data-generated', generatedData.value)
  ElMessage.success('数据已传递给父组件')
}

const handleFileUploadSuccess = (response: any) => {
  console.log('File upload success:', response)
  generatedData.value = response
  ElMessage.success('文件上传成功')
}

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

// 初始化
onMounted(() => {
  // 如果有默认方法，可以在这里设置
})
</script>

<style scoped>
.simulation-input-generator {
  width: 100%;
}

.input-card {
  margin-bottom: 20px;
}

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

.template-preview {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
}

.result-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.result-preview {
  margin: 10px 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.text-result {
  padding: 10px;
  background-color: #f5f5f5;
  white-space: pre-wrap;
  word-break: break-all;
  min-height: 100px;
}

.other-result {
  padding: 10px;
  background-color: #f5f5f5;
  white-space: pre-wrap;
  word-break: break-all;
  min-height: 100px;
}

.result-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

:deep(.json-editor-container) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>
</template>
</file_path>