<template>
  <MainLayout>
    <div class="node-templates-container">
      <el-card>
      <template #header>
        <div class="card-header">
          <span>节点模板管理</span>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建模板
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="filters">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索模板名称、描述或提示词"
          clearable
          style="width: 300px; margin-right: 10px"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="selectedCategory"
          placeholder="分类"
          clearable
          style="width: 150px; margin-right: 10px"
          @change="handleSearch"
        >
          <el-option label="文本生成" value="text_generation" />
          <el-option label="数据分析" value="data_analysis" />
          <el-option label="代码生成" value="code_generation" />
          <el-option label="翻译" value="translation" />
          <el-option label="摘要" value="summarization" />
          <el-option label="问答" value="qa" />
          <el-option label="其他" value="other" />
        </el-select>
        <el-select
          v-model="filterPublic"
          placeholder="可见性"
          clearable
          style="width: 120px"
          @change="handleSearch"
        >
          <el-option label="我的模板" :value="false" />
          <el-option label="公开模板" :value="true" />
        </el-select>
      </div>

      <!-- 模板列表 -->
      <el-table :data="templates" v-loading="loading" style="margin-top: 20px">
        <el-table-column prop="name" label="模板名称" width="200" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getCategoryLabel(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="tags" label="标签" width="150">
          <template #default="{ row }">
            <el-tag
              v-for="tag in (row.tags || [])"
              :key="tag"
              size="small"
              style="margin-right: 5px"
            >
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="use_count" label="使用次数" width="100" align="center" />
        <el-table-column prop="is_public" label="可见性" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_public ? 'success' : 'info'" size="small">
              {{ row.is_public ? '公开' : '私有' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleUse(row)"
            >
              使用
            </el-button>
            <el-button
              v-if="row.user_id === currentUser?.id"
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.user_id === currentUser?.id"
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" label-width="120px" ref="formRef">
        <el-form-item label="模板名称" prop="name" :rules="[{ required: true, message: '请输入模板名称' }]">
          <el-input v-model="formData.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="文本生成" value="text_generation" />
            <el-option label="数据分析" value="data_analysis" />
            <el-option label="代码生成" value="code_generation" />
            <el-option label="翻译" value="translation" />
            <el-option label="摘要" value="summarization" />
            <el-option label="问答" value="qa" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="formData.tags"
            multiple
            filterable
            allow-create
            placeholder="输入标签后按回车添加"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="提示词模板" prop="prompt" :rules="[{ required: true, message: '请输入提示词模板' }]">
          <el-input
            v-model="formData.prompt"
            type="textarea"
            :rows="8"
            placeholder="请输入提示词模板，支持变量占位符，如 {{variable}}"
          />
          <div style="margin-top: 5px; color: #909399; font-size: 12px">
            提示：使用 {{变量名}} 格式定义变量，例如 {{useCase}}、{{templateType}}
          </div>
        </el-form-item>
        <el-form-item label="变量定义" prop="variables">
          <div style="width: 100%">
            <div v-for="(variable, index) in formData.variables" :key="index" style="margin-bottom: 15px; padding: 15px; border: 1px solid #dcdfe6; border-radius: 4px; background: #f5f7fa">
              <el-row :gutter="10">
                <el-col :span="6">
                  <el-form-item :label="'变量名'" style="margin-bottom: 0">
                    <el-input
                      v-model="variable.name"
                      placeholder="变量名"
                      @blur="validateVariableName(index)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item :label="'类型'" style="margin-bottom: 0">
                    <el-select v-model="variable.type" placeholder="类型" style="width: 100%">
                      <el-option label="text" value="text" />
                      <el-option label="number" value="number" />
                      <el-option label="boolean" value="boolean" />
                      <el-option label="select" value="select" />
                      <el-option label="date" value="date" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-form-item :label="'必填'" style="margin-bottom: 0">
                    <el-switch v-model="variable.required" />
                  </el-form-item>
                </el-col>
                <el-col :span="9">
                  <el-form-item :label="'描述'" style="margin-bottom: 0">
                    <el-input
                      v-model="variable.description"
                      placeholder="变量描述"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-button
                    type="danger"
                    :icon="Delete"
                    circle
                    size="small"
                    @click="removeVariable(index)"
                    style="margin-top: 28px"
                  />
                </el-col>
              </el-row>
            </div>
            <el-button
              type="primary"
              :icon="Plus"
              size="small"
              @click="addVariable"
              style="width: 100%"
            >
              添加变量
            </el-button>
            <div style="margin-top: 10px; color: #909399; font-size: 12px">
              提示：变量名需要在提示词模板中使用 {{变量名}} 格式引用
            </div>
          </div>
        </el-form-item>
        <el-form-item label="默认配置">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="提供商" prop="provider">
                <el-select v-model="formData.provider" style="width: 100%">
                  <el-option label="DeepSeek" value="deepseek" />
                  <el-option label="OpenAI" value="openai" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模型" prop="model">
                <el-input v-model="formData.model" placeholder="模型名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Temperature" prop="temperature">
                <el-input-number
                  v-model="formData.temperature"
                  :min="0"
                  :max="2"
                  :step="0.1"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Max Tokens" prop="max_tokens">
                <el-input-number
                  v-model="formData.max_tokens"
                  :min="1"
                  :max="10000"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="可见性" prop="is_public">
          <el-switch
            v-model="formData.is_public"
            active-text="公开"
            inactive-text="私有"
          />
          <div style="margin-top: 5px; color: #909399; font-size: 12px">
            公开的模板可以被其他用户使用
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Delete } from '@element-plus/icons-vue'
import api from '@/api'
import { useUserStore } from '@/stores/user'
import MainLayout from '@/components/MainLayout.vue'

const userStore = useUserStore()
const currentUser = computed(() => userStore.user)

const loading = ref(false)
const templates = ref<any[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const searchKeyword = ref('')
const selectedCategory = ref('')
const filterPublic = ref<boolean | null>(null)

const dialogVisible = ref(false)
const dialogTitle = ref('创建模板')
const formRef = ref()
const formData = ref({
  name: '',
  description: '',
  category: '',
  tags: [] as string[],
  prompt: '',
  variables: [] as Array<{
    name: string
    type: string
    required: boolean
    description: string
  }>,
  provider: 'deepseek',
  model: 'deepseek-chat',
  temperature: 0.7,
  max_tokens: 1500,
  is_public: false
})
const editingId = ref<string | null>(null)

// 获取分类标签
const getCategoryLabel = (category: string) => {
  const labels: Record<string, string> = {
    text_generation: '文本生成',
    data_analysis: '数据分析',
    code_generation: '代码生成',
    translation: '翻译',
    summarization: '摘要',
    qa: '问答',
    other: '其他'
  }
  return labels[category] || category
}

// 加载模板列表
const loadTemplates = async () => {
  loading.value = true
  try {
    const params: any = {
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value
    }
    if (searchKeyword.value) {
      params.search = searchKeyword.value
    }
    if (selectedCategory.value) {
      params.category = selectedCategory.value
    }
    if (filterPublic.value !== null) {
      params.is_public = filterPublic.value
    }
    
    const response = await api.get('/api/v1/node-templates', { params })
    templates.value = response.data
    // 注意：API可能没有返回total，这里需要根据实际情况调整
    total.value = response.data.length
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载模板列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadTemplates()
}

// 分页
const handleSizeChange = () => {
  loadTemplates()
}

const handlePageChange = () => {
  loadTemplates()
}

// 创建模板
const handleCreate = () => {
  editingId.value = null
  dialogTitle.value = '创建模板'
  formData.value = {
    name: '',
    description: '',
    category: '',
    tags: [],
    prompt: '',
    variables: [],
    provider: 'deepseek',
    model: 'deepseek-chat',
    temperature: 0.7,
    max_tokens: 1500,
    is_public: false
  }
  dialogVisible.value = true
}

// 编辑模板
const handleEdit = (row: any) => {
  editingId.value = row.id
  dialogTitle.value = '编辑模板'
  formData.value = {
    name: row.name,
    description: row.description || '',
    category: row.category || '',
    tags: row.tags || [],
    prompt: row.prompt,
    variables: row.variables ? JSON.parse(JSON.stringify(row.variables)) : [],
    provider: row.provider || 'deepseek',
    model: row.model || 'deepseek-chat',
    temperature: parseFloat(row.temperature) || 0.7,
    max_tokens: row.max_tokens || 1500,
    is_public: row.is_public || false
  }
  dialogVisible.value = true
}

// 添加变量
const addVariable = () => {
  formData.value.variables.push({
    name: '',
    type: 'text',
    required: true,
    description: ''
  })
}

// 删除变量
const removeVariable = (index: number) => {
  formData.value.variables.splice(index, 1)
}

// 验证变量名
const validateVariableName = (index: number) => {
  const variable = formData.value.variables[index]
  if (!variable.name) return
  
  // 检查变量名格式（只能包含字母、数字、下划线）
  if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(variable.name)) {
    ElMessage.warning('变量名只能包含字母、数字和下划线，且不能以数字开头')
    variable.name = ''
    return
  }
  
  // 检查重复
  const duplicates = formData.value.variables.filter((v, i) => 
    i !== index && v.name === variable.name
  )
  if (duplicates.length > 0) {
    ElMessage.warning('变量名不能重复')
    variable.name = ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (editingId.value) {
      // 更新
      await api.put(`/api/v1/node-templates/${editingId.value}`, formData.value)
      ElMessage.success('模板更新成功')
    } else {
      // 创建
      await api.post('/api/v1/node-templates', formData.value)
      ElMessage.success('模板创建成功')
    }
    
    dialogVisible.value = false
    loadTemplates()
  } catch (error: any) {
    if (error.response?.data?.detail) {
      ElMessage.error(error.response.data.detail)
    }
  }
}

// 使用模板
const handleUse = async (row: any) => {
  try {
    // 增加使用次数
    await api.post(`/api/v1/node-templates/${row.id}/use`)
    
    // 跳转到工作流设计器，并传递模板信息
    // 这里可以通过路由参数或事件总线传递模板信息
    ElMessage.success('模板已应用，请在节点配置中选择此模板')
    
    // 可以打开新窗口或导航到工作流设计器
    // router.push({ name: 'workflow', query: { templateId: row.id } })
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '使用模板失败')
  }
}

// 删除模板
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模板 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/api/v1/node-templates/${row.id}`)
    ElMessage.success('模板删除成功')
    loadTemplates()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.detail || '删除模板失败')
    }
  }
}

onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
.node-templates-container {
  padding: 20px;
}

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

.filters {
  display: flex;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
