<template>
  <div class="page-content">
    <div class="mb-5 flex items-center justify-between gap-4">
      <div>
        <h2 class="text-xl font-semibold">记忆管理</h2>
        <p class="text-g-500 mt-1 text-sm">沉淀个人经验与偏好,对话时按语义自动召回;可授权给其他用户</p>
      </div>
      <ElButton type="primary" @click="openCreate">添加记忆</ElButton>
    </div>

    <ElCard shadow="never" class="mb-4">
      <div class="flex gap-2">
        <ElInput v-model="recallQuery" placeholder="语义检索我的记忆(如:我常用的代码风格)" @keyup.enter="recall" />
        <ElButton type="primary" plain :loading="recalling" @click="recall">召回</ElButton>
      </div>
      <div v-if="recalled.length" class="mt-3 space-y-2">
        <div v-for="item in recalled" :key="item.id" class="rounded bg-g-50 p-3 text-sm">
          <div class="font-medium">{{ item.category }} · 重要度 {{ item.importance }}</div>
          <div class="text-g-600 mt-1">{{ item.content }}</div>
        </div>
      </div>
    </ElCard>

    <ElTable v-loading="loading" :data="entries" row-key="id">
      <ElTableColumn prop="category" label="分类" width="120" />
      <ElTableColumn prop="content" label="内容" min-width="300" show-overflow-tooltip />
      <ElTableColumn prop="importance" label="重要度" width="90" />
      <ElTableColumn label="授权给" width="160">
        <template #default="{ row }">{{ (row.shared_with || []).length ? row.shared_with.length + ' 人' : '—' }}</template>
      </ElTableColumn>
      <ElTableColumn prop="updated_at" label="更新时间" width="180" />
      <ElTableColumn label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <ElButton link type="primary" @click="openEdit(row)">编辑</ElButton>
          <ElButton link type="danger" @click="remove(row)">删除</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElDialog v-model="dialogVisible" :title="editingId ? '编辑记忆' : '添加记忆'" width="600px">
      <ElForm label-width="90px">
        <ElFormItem label="分类"><ElInput v-model="form.category" placeholder="如 工作偏好 / 代码风格 / 常用工具" /></ElFormItem>
        <ElFormItem label="内容" required>
          <ElInput v-model="form.content" type="textarea" :rows="4" maxlength="8000" show-word-limit placeholder="记忆内容,对话时按语义召回" />
        </ElFormItem>
        <ElFormItem label="重要度">
          <ElRate v-model="form.importance" :max="10" />
        </ElFormItem>
        <ElFormItem label="授权用户ID">
          <ElInput v-model="sharedText" placeholder="逗号分隔的用户 ID(授权后对方可召回你的这条记忆)" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" :loading="saving" @click="submit">保存</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import request from '@/utils/http'

  interface MemoryEntry {
    id: string
    category: string
    content: string
    importance: number
    shared_with: string[]
    updated_at: string
  }

  const entries = ref<MemoryEntry[]>([])
  const recalled = ref<MemoryEntry[]>([])
  const loading = ref(false)
  const recalling = ref(false)
  const saving = ref(false)
  const dialogVisible = ref(false)
  const editingId = ref('')
  const recallQuery = ref('')
  const sharedText = ref('')
  const form = reactive({ category: 'general', content: '', importance: 5 })

  async function load() {
    loading.value = true
    try {
      entries.value = await request.get<MemoryEntry[]>({ url: '/api/v1/portal/memories' })
    } finally {
      loading.value = false
    }
  }

  async function recall() {
    if (!recallQuery.value.trim()) return
    recalling.value = true
    try {
      recalled.value = await request.post<MemoryEntry[]>({ url: '/api/v1/portal/memories/recall', params: { query: recallQuery.value.trim(), limit: 5 } })
    } finally {
      recalling.value = false
    }
  }

  function openCreate() {
    editingId.value = ''
    Object.assign(form, { category: 'general', content: '', importance: 5 })
    sharedText.value = ''
    dialogVisible.value = true
  }

  function openEdit(row: MemoryEntry) {
    editingId.value = row.id
    Object.assign(form, { category: row.category, content: row.content, importance: row.importance })
    sharedText.value = (row.shared_with || []).join(',')
    dialogVisible.value = true
  }

  async function submit() {
    if (!form.content.trim()) {
      ElMessage.warning('请输入记忆内容')
      return
    }
    saving.value = true
    try {
      const shared = sharedText.value.split(',').map((v) => v.trim()).filter(Boolean)
      const payload = { ...form, shared_with: shared }
      if (editingId.value) {
        await request.put({ url: `/api/v1/portal/memories/${editingId.value}`, params: payload })
      } else {
        await request.post({ url: '/api/v1/portal/memories', params: payload })
      }
      ElMessage.success('已保存')
      dialogVisible.value = false
      await load()
    } finally {
      saving.value = false
    }
  }

  async function remove(row: MemoryEntry) {
    try {
      await ElMessageBox.confirm('确认删除这条记忆？', '删除记忆', { type: 'warning' })
    } catch {
      return
    }
    try {
      await request.del({ url: `/api/v1/portal/memories/${row.id}` })
      ElMessage.success('已删除')
      await load()
    } catch { /* 全局错误提示 */ }
  }

  onMounted(load)
</script>
