<template>
	<div class="memory-page">
		<div class="page-header">
			<span class="title">记忆管理</span>
		</div>
		<div class="page-body">
			<!-- 左侧统计面板 -->
			<div class="stats-sidebar">
				<div
					class="stat-card"
					:class="{ active: !filterAgent }"
					@click="filterAgent = ''"
				>
					<div class="stat-name">全部</div>
					<div class="stat-count">{{ totalCount }} 条</div>
				</div>
				<div
					v-for="item in statsData"
					:key="item.agentName"
					class="stat-card"
					:class="{ active: filterAgent === item.agentName }"
					@click="filterAgent = item.agentName"
				>
					<div class="stat-name">{{ agentLabelMap[item.agentName] || item.agentName }}</div>
					<el-tag size="small" :type="item.backend === 'mysql' ? '' : 'success'">
						{{ item.backend === 'mysql' ? 'MySQL' : 'SQLite' }}
					</el-tag>
					<div class="stat-count">{{ item.count }} 条</div>
				</div>
			</div>

			<!-- 右侧主内容 -->
			<div class="main-content">
				<!-- 筛选栏 -->
				<div class="filter-bar">
					<el-select v-model="filterAgent" placeholder="Agent" clearable style="width: 160px">
						<el-option
							v-for="s in statsData"
							:key="s.agentName"
							:label="agentLabelMap[s.agentName] || s.agentName"
							:value="s.agentName"
						/>
					</el-select>
					<el-select v-model="filterType" placeholder="类型" clearable style="width: 140px">
						<el-option
							v-for="t in typeList"
							:key="t.key"
							:label="t.name"
							:value="t.key"
						/>
					</el-select>
					<el-input
						v-model="filterKeyword"
						placeholder="关键词搜索"
						clearable
						style="width: 200px"
						@keyup.enter="loadMemoryList"
					/>
					<el-button type="primary" @click="loadMemoryList">搜索</el-button>
					<div class="filter-actions">
						<el-button type="primary" @click="openAddDialog">+ 新增记忆</el-button>
						<el-button @click="typeDialogVisible = true">类型管理</el-button>
					</div>
				</div>

				<!-- 记忆表格 -->
				<el-table :data="memoryList" border stripe style="width: 100%">
					<el-table-column prop="id" label="ID" width="70" />
					<el-table-column prop="name" label="标题" min-width="140" show-overflow-tooltip />
					<el-table-column prop="type" label="类型" width="110">
						<template #default="{ row }">
							<el-tag :type="typeTagColor(row.type)" size="small">
								{{ typeNameMap[row.type] || row.type }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="Agent" width="160" show-overflow-tooltip>
						<template #default="{ row }">
							{{ agentLabelMap[row.agentName] || row.agentName }}
						</template>
					</el-table-column>
					<el-table-column prop="_backend" label="存储后端" width="100">
						<template #default="{ row }">
							<el-tag :type="row._backend === 'mysql' ? '' : 'success'" size="small">
								{{ row._backend === 'mysql' ? 'MySQL' : 'SQLite' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="description" label="描述" min-width="160" show-overflow-tooltip />
					<el-table-column prop="updatedAt" label="更新时间" width="170" />
					<el-table-column label="操作" width="140" fixed="right">
						<template #default="{ row }">
							<el-button type="primary" link size="small" @click="openEditDialog(row)">编辑</el-button>
							<el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<div class="pagination-wrap">
					<el-pagination
						v-model:current-page="pagination.page"
						v-model:page-size="pagination.size"
						:total="pagination.total"
						:page-sizes="[10, 20, 50]"
						layout="total, sizes, prev, pager, next"
						@size-change="loadMemoryList"
						@current-change="loadMemoryList"
					/>
				</div>
			</div>
		</div>

		<!-- 新增/编辑记忆弹窗 -->
		<el-dialog
			v-model="memoryDialogVisible"
			:title="isEdit ? '编辑记忆' : '新增记忆'"
			width="600px"
			destroy-on-close
		>
			<el-form ref="memoryFormRef" :model="memoryForm" :rules="memoryRules" label-width="100px">
				<el-form-item label="Agent" prop="agentName">
					<el-select
						v-model="memoryForm.agentName"
						placeholder="选择 Agent"
						:disabled="isEdit"
						style="width: 100%"
					>
						<el-option
							v-for="a in agentList"
							:key="a.name"
							:label="a.label || a.name"
							:value="a.name"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="类型" prop="type">
					<el-select v-model="memoryForm.type" placeholder="选择类型" style="width: 100%">
						<el-option
							v-for="t in typeList"
							:key="t.key"
							:label="t.name"
							:value="t.key"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="标题" prop="name">
					<el-input v-model="memoryForm.name" placeholder="记忆标题" />
				</el-form-item>
				<el-form-item label="内容" prop="content">
					<el-input v-model="memoryForm.content" type="textarea" :rows="4" placeholder="记忆内容" />
				</el-form-item>
				<el-form-item label="描述">
					<el-input v-model="memoryForm.description" placeholder="简要描述" />
				</el-form-item>
				<el-form-item label="元数据">
					<el-input
						v-model="memoryForm.metadataStr"
						type="textarea"
						:rows="3"
						placeholder='JSON 格式，如 {"key": "value"}'
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="memoryDialogVisible = false">取消</el-button>
				<el-button type="primary" :loading="saving" @click="handleSaveMemory">保存</el-button>
			</template>
		</el-dialog>
		<!-- 类型管理弹窗 -->
		<el-dialog v-model="typeDialogVisible" title="类型管理" width="680px" destroy-on-close>
			<el-table :data="typeList" border size="small" style="width: 100%">
				<el-table-column prop="key" label="Key" width="120" />
				<el-table-column prop="name" label="名称" width="120" />
				<el-table-column prop="description" label="描述" />
				<el-table-column prop="isSystem" label="系统" width="70">
					<template #default="{ row }">
						<el-icon v-if="row.isSystem"><Lock /></el-icon>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="80">
					<template #default="{ row }">
						<el-button
							type="danger"
							link
							size="small"
							:disabled="row.isSystem"
							@click="handleDeleteType(row)"
						>删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<div class="type-add-form">
				<el-form :inline="true" :model="typeForm" size="small">
					<el-form-item label="Key">
						<el-input v-model="typeForm.key" placeholder="类型标识" style="width: 100px" />
					</el-form-item>
					<el-form-item label="名称">
						<el-input v-model="typeForm.name" placeholder="类型名称" style="width: 100px" />
					</el-form-item>
					<el-form-item label="描述">
						<el-input v-model="typeForm.description" placeholder="描述" style="width: 140px" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleAddType">添加</el-button>
					</el-form-item>
				</el-form>
			</div>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { Lock } from '@element-plus/icons-vue';
import { useCool } from '/@/cool';

const { service } = useCool();

// --- 状态 ---
const statsData = ref<any[]>([]);
const agentList = ref<any[]>([]);
const typeList = ref<any[]>([]);
const memoryList = ref<any[]>([]);
const filterAgent = ref('');
const filterType = ref('');
const filterKeyword = ref('');
const pagination = reactive({ page: 1, size: 20, total: 0 });

const memoryDialogVisible = ref(false);
const typeDialogVisible = ref(false);
const isEdit = ref(false);
const saving = ref(false);
const memoryFormRef = ref<FormInstance>();
const memoryForm = reactive({
	id: undefined as number | undefined,
	agentName: '',
	type: '',
	name: '',
	content: '',
	description: '',
	metadataStr: '',
	updatedAt: ''
});
const memoryRules = {
	agentName: [{ required: true, message: '请选择 Agent', trigger: 'change' }],
	name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
	content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
};
const typeForm = reactive({ key: '', name: '', description: '' });

const totalCount = computed(() => statsData.value.reduce((s, i) => s + (i.count || 0), 0));
const typeNameMap = computed(() => {
	const m: Record<string, string> = {};
	typeList.value.forEach((t: any) => { m[t.key] = t.name; });
	return m;
});
const agentLabelMap = computed(() => {
	const m: Record<string, string> = {};
	agentList.value.forEach((a: any) => { m[a.name] = a.label || a.name; });
	return m;
});

// --- 类型标签颜色 ---
function typeTagColor(type: string) {
	const map: Record<string, string> = { user: '', project: 'success', feedback: 'warning', reference: 'info' };
	return map[type] ?? 'info';
}

// --- 数据加载 ---
async function loadStats() {
	try {
		const res = await service.request({ url: '/admin/netaclaw/memory/stats' });
		statsData.value = res || [];
	} catch { statsData.value = []; }
}

async function loadAgents() {
	try {
		const res = await service.request({ url: '/admin/netaclaw/agent/page', method: 'POST', data: { page: 1, size: 200 } });
		agentList.value = res?.list || [];
	} catch { agentList.value = []; }
}

async function loadTypes() {
	try {
		const res = await service.netaclaw.memory_type.list();
		typeList.value = res || [];
	} catch { typeList.value = []; }
}
async function loadMemoryList() {
	try {
		const data: any = { page: pagination.page, size: pagination.size };
		if (filterAgent.value) data.agentName = filterAgent.value;
		if (filterType.value) data.type = filterType.value;
		if (filterKeyword.value) data.keyWord = filterKeyword.value;
		const res = await service.request({ url: '/admin/netaclaw/memory/page', method: 'POST', data });
		memoryList.value = res?.list || [];
		pagination.total = res?.pagination?.total || 0;
	} catch {
		memoryList.value = [];
	}
}

watch(filterAgent, () => { pagination.page = 1; loadMemoryList(); });

// --- 新增/编辑记忆 ---
function openAddDialog() {
	isEdit.value = false;
	Object.assign(memoryForm, { id: undefined, agentName: '', type: '', name: '', content: '', description: '', metadataStr: '', updatedAt: '' });
	memoryDialogVisible.value = true;
}

function openEditDialog(row: any) {
	isEdit.value = true;
	Object.assign(memoryForm, {
		id: row.id,
		agentName: row.agentName,
		type: row.type || '',
		name: row.name || '',
		content: row.content || '',
		description: row.description || '',
		metadataStr: row.metadata ? JSON.stringify(row.metadata, null, 2) : '',
		updatedAt: row.updatedAt || ''
	});
	memoryDialogVisible.value = true;
}

async function handleSaveMemory() {
	await memoryFormRef.value?.validate();
	let metadata: any = undefined;
	if (memoryForm.metadataStr.trim()) {
		try { metadata = JSON.parse(memoryForm.metadataStr); }
		catch { ElMessage.error('元数据 JSON 格式不正确'); return; }
	}
	saving.value = true;
	try {
		const payload: any = {
			agentName: memoryForm.agentName,
			type: memoryForm.type,
			name: memoryForm.name,
			content: memoryForm.content,
			description: memoryForm.description,
			metadata
		};
		if (isEdit.value) {
			payload.id = memoryForm.id;
			payload.updatedAt = memoryForm.updatedAt;
			await service.request({ url: '/admin/netaclaw/memory/update', method: 'POST', data: payload });
		} else {
			await service.request({ url: '/admin/netaclaw/memory/add', method: 'POST', data: payload });
		}
		ElMessage.success(isEdit.value ? '更新成功' : '新增成功');
		memoryDialogVisible.value = false;
		loadMemoryList();
		loadStats();
	} catch { /* error handled by interceptor */ }
	finally { saving.value = false; }
}

// --- 删除记忆 ---
async function handleDelete(row: any) {
	await ElMessageBox.confirm(`确定删除记忆「${row.name}」？`, '提示', { type: 'warning' });
	await service.request({ url: '/admin/netaclaw/memory/delete', method: 'POST', data: { agentName: row.agentName, ids: [row.id] } });
	ElMessage.success('删除成功');
	loadMemoryList();
	loadStats();
}

// --- 类型管理 ---
async function handleAddType() {
	if (!typeForm.key || !typeForm.name) { ElMessage.warning('Key 和名称必填'); return; }
	await service.netaclaw.memory_type.add({ key: typeForm.key, name: typeForm.name, description: typeForm.description });
	ElMessage.success('添加成功');
	typeForm.key = ''; typeForm.name = ''; typeForm.description = '';
	loadTypes();
}

async function handleDeleteType(row: any) {
	await ElMessageBox.confirm(`确定删除类型「${row.name}」？`, '提示', { type: 'warning' });
	await service.netaclaw.memory_type.delete({ ids: [row.id] });
	ElMessage.success('删除成功');
	loadTypes();
}

onMounted(() => { loadStats(); loadAgents(); loadTypes(); loadMemoryList(); });
</script>

<style lang="scss" scoped>
.memory-page {
	height: 100%;
	display: flex;
	flex-direction: column;
	padding: 16px;
	box-sizing: border-box;

	.page-header {
		margin-bottom: 16px;
		.title { font-size: 18px; font-weight: 600; }
	}

	.page-body {
		flex: 1;
		display: flex;
		gap: 16px;
		overflow: hidden;
	}

	.stats-sidebar {
		width: 240px;
		flex-shrink: 0;
		overflow-y: auto;
		display: flex;
		flex-direction: column;
		gap: 8px;

		.stat-card {
			padding: 12px;
			border: 1px solid #e4e7ed;
			border-radius: 8px;
			cursor: pointer;
			transition: all 0.2s;
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			gap: 6px;

			&:hover { border-color: #409eff; }
			&.active { border-color: #409eff; background: #ecf5ff; }

			.stat-name { font-weight: 500; flex: 1; }
			.stat-count { width: 100%; font-size: 12px; color: #909399; }
		}
	}

	.main-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;

		.filter-bar {
			display: flex;
			align-items: center;
			gap: 8px;
			margin-bottom: 12px;
			flex-wrap: wrap;

			.filter-actions { margin-left: auto; display: flex; gap: 8px; }
		}

		.el-table { flex: 1; overflow: auto; }

		.pagination-wrap {
			display: flex;
			justify-content: flex-end;
			padding-top: 12px;
		}
	}
}

.type-add-form {
	margin-top: 16px;
	padding-top: 12px;
	border-top: 1px solid #ebeef5;
}
</style>
