<template>
  <div class="page-content">
    <div class="mb-5 flex items-start justify-between"><div><h2 class="text-xl font-semibold">Prompt 资产</h2><p class="text-g-500 mt-1 text-sm">模板版本只增不改，可切回任意历史版本；变量使用 &#123;&#123;name&#125;&#125; 占位</p></div><div><ElButton @click="categoryVisible=true">分类</ElButton><ElButton type="primary" @click="openCreate">新建 Prompt</ElButton></div></div>
    <ElTable v-loading="loading" :data="items" row-key="id"><ElTableColumn prop="name" label="名称" min-width="180"/><ElTableColumn prop="category_name" label="分类" width="120"/><ElTableColumn label="标签" min-width="160"><template #default="{row}"><ElTag v-for="tag in row.tags" :key="tag" class="mr-1">{{tag}}</ElTag></template></ElTableColumn><ElTableColumn label="当前版本" width="100"><template #default="{row}">v{{row.current_version||'-'}}</template></ElTableColumn><ElTableColumn label="状态" width="90"><template #default="{row}"><ElTag :type="row.enabled?'success':'info'">{{row.enabled?'启用':'停用'}}</ElTag></template></ElTableColumn><ElTableColumn label="操作" width="230" fixed="right"><template #default="{row}"><ElButton link type="primary" @click="openEdit(row)">编辑</ElButton><ElButton link type="primary" @click="openVersions(row)">版本</ElButton><ElButton link type="danger" @click="remove(row)">删除</ElButton></template></ElTableColumn></ElTable>
    <ElDialog v-model="visible" :title="editing?'编辑 Prompt':'新建 Prompt'" width="760px"><ElForm label-width="100px"><div class="grid grid-cols-2 gap-x-4"><ElFormItem label="名称"><ElInput v-model="form.name"/></ElFormItem><ElFormItem label="分类"><ElSelect v-model="form.category_id" clearable class="w-full"><ElOption v-for="c in categories" :key="c.id" :label="c.name" :value="c.id"/></ElSelect></ElFormItem></div><ElFormItem label="描述"><ElInput v-model="form.description" type="textarea"/></ElFormItem><ElFormItem label="标签"><ElSelect v-model="form.tags" multiple allow-create filterable class="w-full"/></ElFormItem><ElFormItem label="部门范围"><ElSelect v-model="form.department_ids" multiple allow-create filterable class="w-full" placeholder="留空表示全部部门；填写部门 UUID"/></ElFormItem><ElFormItem label="状态"><ElSwitch v-model="form.enabled"/></ElFormItem><template v-if="!editing"><ElFormItem label="正文"><ElInput v-model="form.content" type="textarea" :rows="8"/></ElFormItem><ElFormItem label="变量定义"><ElInput v-model="variablesJSON" type="textarea" :rows="4" placeholder='[{"name":"question","required":true}]'/></ElFormItem><ElFormItem label="变更说明"><ElInput v-model="form.change_note"/></ElFormItem></template></ElForm><template #footer><ElButton @click="visible=false">取消</ElButton><ElButton type="primary" :loading="saving" @click="save">保存</ElButton></template></ElDialog>
    <ElDialog v-model="versionsVisible" :title="`${selected?.name||''} · 版本`" width="820px"><ElForm label-width="90px" class="mb-4"><ElFormItem label="新正文"><ElInput v-model="newVersion.content" type="textarea" :rows="6"/></ElFormItem><ElFormItem label="变量 JSON"><ElInput v-model="newVersionVariables" type="textarea" :rows="3"/></ElFormItem><ElFormItem label="说明"><ElInput v-model="newVersion.change_note"/></ElFormItem><ElFormItem><ElCheckbox v-model="newVersion.activate">创建后立即生效</ElCheckbox><ElButton class="ml-3" type="primary" @click="addVersion">创建版本</ElButton></ElFormItem></ElForm><ElTable :data="versions"><ElTableColumn prop="version" label="版本" width="80"/><ElTableColumn prop="change_note" label="变更说明"/><ElTableColumn prop="created_at" label="创建时间" width="190"/><ElTableColumn label="操作" width="100"><template #default="{row}"><ElButton v-if="row.version!==selected?.current_version" link type="primary" @click="activate(row.version)">设为当前</ElButton><ElTag v-else type="success">当前</ElTag></template></ElTableColumn></ElTable></ElDialog>
    <ElDialog v-model="categoryVisible" title="Prompt 分类" width="560px"><div class="mb-3 flex gap-2"><ElInput v-model="newCategory" placeholder="新分类名称"/><ElButton type="primary" @click="addCategory">添加</ElButton></div><ElTable :data="categories"><ElTableColumn prop="name" label="分类"/><ElTableColumn prop="template_count" label="模板数" width="90"/><ElTableColumn label="操作" width="80"><template #default="{row}"><ElButton link type="danger" @click="removeCategory(row)">删除</ElButton></template></ElTableColumn></ElTable></ElDialog>
  </div>
</template>
<script setup lang="ts">
  import { PromptInput,PromptTemplate,PromptVariable,PromptVersion,activatePromptVersion,createPrompt,createPromptCategory,createPromptVersion,deletePrompt,deletePromptCategory,fetchPromptCategories,fetchPromptVersions,fetchPrompts,updatePrompt } from '@/api/workbench';import{ElMessage,ElMessageBox}from'element-plus'
  const loading=ref(false),saving=ref(false),visible=ref(false),versionsVisible=ref(false),categoryVisible=ref(false),editing=ref(''),newCategory=ref('');const items=ref<PromptTemplate[]>([]),categories=ref<any[]>([]),versions=ref<PromptVersion[]>([]),selected=ref<PromptTemplate>();const blank=():PromptInput=>({name:'',description:'',category_id:null,tags:[],department_ids:[],enabled:true,content:'',variables:[],change_note:'初始版本'});const form=reactive<PromptInput>(blank()),variablesJSON=ref('[]');const newVersion=reactive({content:'',change_note:'',activate:true}),newVersionVariables=ref('[]')
  async function load(){loading.value=true;try{[items.value,categories.value]=await Promise.all([fetchPrompts(),fetchPromptCategories()])}finally{loading.value=false}}function openCreate(){editing.value='';Object.assign(form,blank());variablesJSON.value='[]';visible.value=true}function openEdit(row:PromptTemplate){editing.value=row.id;Object.assign(form,{name:row.name,description:row.description,category_id:row.category_id||null,tags:[...row.tags],department_ids:[...row.department_ids],enabled:row.enabled,content:'',variables:[],change_note:''});visible.value=true}
  async function save(){try{form.variables=JSON.parse(variablesJSON.value) as PromptVariable[]}catch{ElMessage.error('变量 JSON 无效');return};saving.value=true;try{editing.value?await updatePrompt(editing.value,form):await createPrompt(form);visible.value=false;await load();ElMessage.success('已保存')}finally{saving.value=false}}async function remove(row:PromptTemplate){await ElMessageBox.confirm(`删除“${row.name}”及全部版本？`,'确认',{type:'warning'});await deletePrompt(row.id);await load()}
  async function openVersions(row:PromptTemplate){selected.value=row;versions.value=await fetchPromptVersions(row.id);newVersion.content=row.current?.content||'';newVersion.change_note='';newVersion.activate=true;newVersionVariables.value=JSON.stringify(row.current?.variables||[],null,2);versionsVisible.value=true}async function addVersion(){if(!selected.value)return;let variables:PromptVariable[];try{variables=JSON.parse(newVersionVariables.value)}catch{ElMessage.error('变量 JSON 无效');return}await createPromptVersion(selected.value.id,{...newVersion,variables});await load();const current=items.value.find(i=>i.id===selected.value?.id);if(current)await openVersions(current)}async function activate(version:number){if(!selected.value)return;await activatePromptVersion(selected.value.id,version);await load();const current=items.value.find(i=>i.id===selected.value?.id);if(current)await openVersions(current)}
  async function addCategory(){if(!newCategory.value.trim())return;await createPromptCategory({name:newCategory.value,description:''});newCategory.value='';await load()}async function removeCategory(row:any){await deletePromptCategory(row.id);await load()}onMounted(load)
</script>
