<template>
	<div class="panel">
		<div class="toolbar">
			<div class="toolbar-left">
				<el-input v-model="keyword" clearable placeholder="搜索提示词名称 / 描述" class="search-input"
					@keyup.enter="loadList(1)">
					<template #prefix>
						<el-icon>
							<Search />
						</el-icon>
					</template>
				</el-input>
				<el-select v-model="type" clearable placeholder="类型" style="width: 160px" :options="typeList"
					@change="loadList(1)"></el-select>
				<el-button @click="loadList(1)">查询</el-button>
				<el-button @click="handleReset">重置</el-button>
			</div>
			<div class="toolbar-right">
				<el-button type="primary" @click="openCreate">
					<el-icon>
						<Plus />
					</el-icon>
					新建提示词
				</el-button>
			</div>
		</div>

		<div v-loading="loading" class="card-grid">
			<el-empty v-if="!visibleList.length && !loading" description="暂无提示词" class="empty" />
			<div v-for="item in visibleList" :key="item.id" class="resource-card">
				<div class="resource-card__top">
					<div>
						<div class="resource-card__title flex items-center gap-4px">
							<el-tag v-if="item.is_builtin" type="success" effect="light">内置</el-tag>{{ item.name }}
						</div>

						<div class="resource-card__desc">{{ item.description || '暂无描述' }}</div>
					</div>
					<el-dropdown :hide-on-click="false">
						<span class="cursor-pointer">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</span>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item>
									<el-button link type="primary" @click="openDetail(item)">详情</el-button>
								</el-dropdown-item>
								<el-dropdown-item>
									<el-button link type="primary" @click="openEdit(item)">编辑</el-button>
								</el-dropdown-item>
								<el-dropdown-item>
									<el-button link type="danger" @click="removeItem(item.id)">删除</el-button>
								</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</div>
				<div class="resource-card__meta">
					<span>类型：{{ formatType(item.type) }}</span>
				</div>
				<div class="resource-card__content">{{ shortText(item.content) }}</div>
			</div>
		</div>

		<div v-if="pagination.totalCount > 0" class="pagination">
			<el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize" background
				layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]" :total="pagination.totalCount"
				@current-change="handlePageChange" @size-change="handleSizeChange" />
		</div>

		<el-drawer v-model="drawerVisible" :title="currentId ? '编辑提示词' : '新建提示词'" direction="rtl" size="760px">
			<el-form ref="formRef" :model="form" :rules="rules" label-position="top">
				<el-form-item label="名称" prop="name">
					<el-input v-model="form.name" />
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input v-model="form.description" type="textarea" :rows="2" />
				</el-form-item>
				<el-form-item label="内容" prop="content">
					<el-input v-model="form.content" type="textarea" :rows="8" />
				</el-form-item>
				<el-form-item label="用户提示词" prop="user">
					<el-input v-model="form.user" type="textarea" :rows="4" />
				</el-form-item>
				<div class="grid-2">
					<el-form-item label="类型" prop="type">
						<el-select v-model="form.type" style="width: 100%">
							<el-option label="系统提示词" value="system-prompt" />
							<el-option label="agent 系统提示词" value="agent-system-prompt" />
							<el-option label="改写提示词" value="rewrite" />
							<el-option label="回退提示词" value="fallback" />
							<el-option label="上下文模板" value="context-template" />
						</el-select>
					</el-form-item>
					<el-form-item label="是否默认" prop="is_default">
						<el-switch v-model="form.is_default" />
					</el-form-item>
				</div>
				<div class="grid-2">
					<el-form-item label="包含知识库" prop="has_knowledge_base">
						<el-switch v-model="form.has_knowledge_base" />
					</el-form-item>
					<el-form-item label="包含网络搜索" prop="has_web_search">
						<el-switch v-model="form.has_web_search" />
					</el-form-item>
				</div>
			</el-form>
			<template #footer>
				<div class="drawer-footer">
					<el-button @click="drawerVisible = false">取消</el-button>
					<el-button type="primary" :loading="submitLoading" @click="handleSubmit">保存</el-button>
				</div>
			</template>
		</el-drawer>

		<el-drawer v-model="detailVisible" title="提示词详情" width="760px">
			<el-descriptions v-if="detailItem" :column="1" direction="vertical">
				<el-descriptions-item label="名称">{{ detailItem.name }}</el-descriptions-item>
				<el-descriptions-item label="类型">{{ formatType(detailItem.type) }}</el-descriptions-item>
				<el-descriptions-item label="描述">{{
					detailItem.description || '-'
				}}</el-descriptions-item>
				<el-descriptions-item label="内容">
					<div class="w-full p-12rpx">
						<Markdown :content="detailItem.content" />
					</div>
				</el-descriptions-item>
			</el-descriptions>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, MoreFilled } from '@element-plus/icons-vue'
import { resource } from '@repo/api-service'
import { Markdown } from '@repo/ui'

type PromptPageResponse = Awaited<ReturnType<typeof resource.postPromptTemplatePageList>>
type PromptPageResult = NonNullable<PromptPageResponse['result']>
type PromptItem = PromptPageResult['model'][number]

const keyword = ref('')
const type = ref('')
const loading = ref(false)
const submitLoading = ref(false)
const drawerVisible = ref(false)
const detailVisible = ref(false)
const detailItem = ref<PromptItem | null>(null)
const currentId = ref('')
const formRef = ref()

const pagination = reactive({
	pageIndex: 1,
	pageSize: 20,
	totalCount: 0,
	totalPages: 0
})

const list = ref<PromptItem[]>([])

const form = reactive({
	name: '',
	description: '',
	content: '',
	user: '',
	type: 'system-prompt',
	is_default: false,
	has_knowledge_base: false,
	has_web_search: false
})

const rules = {
	name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
	content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
	type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

const visibleList = computed(() => list.value)

const typeMap: Record<string, string> = {
	'system-prompt': '系统提示词',
	'agent-system-prompt': 'Agent 系统提示词',
	rewrite: '改写提示词',
	'fall-back': '回退提示词',
	'context-template': '上下文模板',
	'generate-session-title': '生成会话标题',
	'generate-summary': '生成概要',
	'keywords-extraction': '关键词提取'
}

const typeList = Object.keys(typeMap).map((type) => ({ label: typeMap[type], value: type }))

function formatType(type?: string) {
	return typeMap[type || ''] || type || '-'
}

function shortText(text?: string) {
	if (!text) return '-'
	return text.length > 120 ? `${text.slice(0, 120)}...` : text
}

function resetForm() {
	currentId.value = ''
	form.name = ''
	form.description = ''
	form.content = ''
	form.user = ''
	form.type = 'system-prompt'
	form.is_default = false
	form.has_knowledge_base = false
	form.has_web_search = false
}

async function loadList(pageIndex = 1) {
	loading.value = true
	try {
		const res = await resource.postPromptTemplatePageList({
			keyword: keyword.value,
			type: type.value,
			pageIndex,
			pageSize: pagination.pageSize
		})
		if (res.isSuccess && res.result) {
			list.value = (res.result.model || []) as PromptItem[]
			pagination.pageIndex = res.result.currentPage || pageIndex
			pagination.totalCount = res.result.totalCount || 0
			pagination.totalPages = res.result.totalPages || 0
			pagination.pageSize = res.result.pageSize || pagination.pageSize
		}
	} finally {
		loading.value = false
	}
}

function handlePageChange(page: number) {
	pagination.pageIndex = page
	loadList(page)
}

function handleSizeChange(size: number) {
	pagination.pageSize = size
	loadList(1)
}

function handleReset() {
	keyword.value = ''
	loadList(1)
}

function openCreate() {
	resetForm()
	drawerVisible.value = true
}

function openEdit(item: PromptItem) {
	resetForm()
	currentId.value = item.id
	form.name = item.name || ''
	form.description = item.description || ''
	form.content = item.content || ''
	form.user = item.user || ''
	form.type = item.type || 'system-prompt'
	form.is_default = !!item.is_default
	form.has_knowledge_base = !!item.has_knowledge_base
	form.has_web_search = !!item.has_web_search
	drawerVisible.value = true
}

function openDetail(item: PromptItem) {
	detailItem.value = item
	detailVisible.value = true
}

async function handleSubmit() {
	await formRef.value?.validate(async (valid: boolean) => {
		if (!valid) return
		submitLoading.value = true
		try {
			const payload = {
				name: form.name,
				description: form.description,
				content: form.content,
				user: form.user,
				type: form.type,
				is_default: form.is_default,
				has_knowledge_base: form.has_knowledge_base,
				has_web_search: form.has_web_search
			}
			if (currentId.value) {
				await resource.postPromptTemplateUpdate({ id: currentId.value, ...(payload as any) })
				ElMessage.success('更新成功')
			} else {
				await resource.postPromptTemplateCreate(payload as any)
				ElMessage.success('创建成功')
			}
			drawerVisible.value = false
			loadList(pagination.pageIndex)
		} catch {
			ElMessage.error('保存失败')
		} finally {
			submitLoading.value = false
		}
	})
}

async function removeItem(id: string) {
	try {
		await ElMessageBox.confirm('确定删除该提示词吗？', '提示', { type: 'warning' })
		await resource.postPromptTemplateOpenApiDelete({ id })
		ElMessage.success('删除成功')
		loadList(pagination.pageIndex)
	} catch {
		// ignore
	}
}

onMounted(() => {
	loadList(1)
})
</script>

<style scoped lang="less">
.panel {
	display: flex;
	flex-direction: column;
	gap: 16px;
}

.toolbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 12px;
	flex-wrap: wrap;
}

.toolbar-left,
.toolbar-right {
	display: flex;
	align-items: center;
	gap: 10px;
	flex-wrap: wrap;
}

.search-input {
	width: 280px;
}

.card-grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
	gap: 16px;
	min-height: 200px;
}

.resource-card {
	padding: 16px;
	border-radius: 18px;
	border: 1px solid #e5e7eb;
	background: #fff;
	box-shadow: 0 12px 24px rgba(15, 23, 42, 0.05);
}

.resource-card__top {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	gap: 10px;
}

.resource-card__title {
	font-size: 18px;
	font-weight: 700;
	color: #111827;
}

.resource-card__desc {
	margin-top: 6px;
	color: #6b7280;
	font-size: 13px;
}

.resource-card__meta {
	display: flex;
	flex-wrap: wrap;
	gap: 8px 12px;
	margin-top: 12px;
	font-size: 12px;
	color: #6b7280;
}

.resource-card__content {
	margin-top: 12px;
	padding: 12px;
	border-radius: 12px;
	background: #f8fafc;
	color: #334155;
	font-size: 13px;
	line-height: 1.6;
	white-space: pre-wrap;
}

.resource-card__actions {
	display: flex;
	justify-content: flex-end;
	gap: 8px;
	margin-top: 12px;
}

.pagination {
	display: flex;
	justify-content: flex-end;
}

.grid-2 {
	display: grid;
	grid-template-columns: repeat(2, minmax(0, 1fr));
	gap: 12px;
}

.drawer-footer {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
}

.empty {
	padding: 24px 0;
	grid-column: span 4;
}

@media (max-width: 768px) {

	.toolbar,
	.grid-2 {
		grid-template-columns: 1fr;
	}

	.search-input {
		width: 100%;
	}
}
</style>
