<template>
	<div class="document-manage">
		<div class="action-bar">
			<div class="action-bar__left">
				<el-input
					v-model="keyword"
					clearable
					placeholder="搜索知识标题"
					style="width: 240px"
					@keyup.enter="fetchKnowledgeList"
				/>
				<el-input
					v-model="fileType"
					clearable
					placeholder="文件类型，如 pdf/md"
					style="width: 180px"
					@keyup.enter="fetchKnowledgeList"
				/>
				<el-button @click="fetchKnowledgeList">
					<el-icon>
						<Refresh />
					</el-icon>
					刷新
				</el-button>
			</div>
			<div class="action-bar__right">
				<el-button @click="openFileDrawer">
					<el-icon>
						<Upload />
					</el-icon>
					上传文件
				</el-button>
				<el-button type="primary" @click="openManualDrawer">
					<el-icon>
						<Plus />
					</el-icon>
					自定义
				</el-button>
			</div>
		</div>

		<el-card>
			<template #header>
				<div class="card-header">
					<span>知识列表</span>
				</div>
			</template>

			<el-table
				v-if="knowledgeList.length || loading"
				:data="knowledgeList"
				v-loading="loading"
				border
			>
				<el-table-column prop="title" label="标题" min-width="220" />
				<el-table-column prop="type" label="类型" width="100">
					<template #default="{ row }">
						<el-tag v-if="row.type === 'file'">文件上传</el-tag>
						<el-tag v-if="row.type === 'manual'">自定义</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="file_name" label="文件名" min-width="180" />
				<el-table-column prop="file_type" label="文件类型" width="100" />
				<el-table-column prop="source" label="来源" width="110" />
				<el-table-column prop="parse_status" label="解析状态" width="120">
					<template #default="{ row }">
						<el-tag :type="getStatusTagType(row.parse_status)">
							{{ row.parse_status ? stateMap[row.parse_status] : '-' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="summary_status" label="摘要状态" width="120">
					<template #default="{ row }">
						<el-tag :type="getStatusTagType(row.summary_status)">
							{{ row.parse_status ? stateMap[row.summary_status] : '-' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="错误信息" min-width="180">
					<template #default="{ row }">
						<span class="truncate-text">{{ row.error_message || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="updateTime" label="更新时间" width="180" />
				<el-table-column label="操作" width="220" fixed="right">
					<template #default="{ row }">
						<el-button
							v-if="row.file_type === 'manual'"
							link
							type="primary"
							@click="openEditDrawer(row)"
						>
							编辑
						</el-button>
						<el-button link type="warning" @click="reparseKnowledge(row.id)">重新解析</el-button>
						<el-button link type="danger" @click="removeKnowledge(row.id)">删除</el-button>
					</template>
				</el-table-column>
				<template #empty>暂无知识内容</template>
			</el-table>
			<el-empty v-else description="暂无知识内容" class="page-empty" />
		</el-card>

		<el-drawer v-model="manualDrawerVisible" title="新建知识" direction="rtl" size="640px">
			<el-form ref="manualFormRef" :model="manualForm" :rules="manualRules" label-position="top">
				<el-form-item label="标题" prop="title">
					<el-input v-model="manualForm.title" placeholder="请输入标题" />
				</el-form-item>
				<el-form-item label="知识内容" prop="content">
					<el-input v-model="manualForm.content" type="textarea" placeholder="请输入知识正文" />
				</el-form-item>
				<el-form-item label="发布">
					<el-switch v-model="manualForm.publish" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="drawer-footer">
					<el-button @click="manualDrawerVisible = false">取消</el-button>
					<el-button type="primary" :loading="submitLoading" @click="submitManualKnowledge">
						提交
					</el-button>
				</div>
			</template>
		</el-drawer>

		<el-drawer v-model="fileDrawerVisible" title="导入文件知识" direction="rtl" size="640px">
			<el-form :model="fileForm" label-position="top">
				<el-form-item label="上传文件">
					<FileUploadInput
						v-model="uploadFile"
						:multiple="false"
						:file-types="['document', 'image', 'audio']"
						:allow-link-input="false"
						tip="支持文档、图片、音频格式，上传后会按知识内容处理。"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item>
					<div class="metadata-config">
						<div class="metadata-config__top">
							<span>元数据(可选)</span>
							<el-button type="primary" link @click="addMetadataItem">
								<el-icon> <Plus /> </el-icon>添加元数据
							</el-button>
						</div>
						<div class="metadata-config__desc">
							导入文件知识时附加的元数据，常用于业务分类、标签标记、来源标识等场景
						</div>
						<div class="metadata-config__rows">
							<div
								v-for="(item, index) in fileForm.metadata"
								:key="`metadata-${index}`"
								class="metadata-config__row"
							>
								<el-input v-model="item.key" placeholder="元数据名称" />
								<el-input v-model="item.value" placeholder="元数据值" />
								<el-button
									link
									type="danger"
									:disabled="fileForm.metadata.length === 1"
									@click="removeMetadataItem(index)"
								>
									删除
								</el-button>
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="启用多模型解析">
					<el-switch v-model="fileForm.enable_multi_model" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="drawer-footer">
					<el-button @click="fileDrawerVisible = false">取消</el-button>
					<el-button type="primary" :loading="submitLoading" @click="submitFileKnowledge">
						提交
					</el-button>
				</div>
			</template>
		</el-drawer>

		<el-drawer v-model="editDrawerVisible" title="编辑知识" direction="rtl" size="560px">
			<el-form
				ref="editFormRef"
				v-loading="editDrawerLoading"
				:model="editForm"
				:rules="editRules"
				label-position="top"
			>
				<el-form-item label="标题" prop="title">
					<el-input v-model="editForm.title" />
				</el-form-item>
				<el-form-item label="描述(点击编辑，支持Markdown语法)">
					<!-- <markdown v-if="!isEdit" :content="editForm.description" @click="isEdit = true" /> -->
					<el-input
						v-model="editForm.description"
						type="textarea"
						:rows="5"
						@blur="isEdit = false"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="drawer-footer">
					<el-button @click="editDrawerVisible = false">取消</el-button>
					<el-button type="primary" :loading="submitLoading" @click="submitEditKnowledge">
						保存
					</el-button>
				</div>
			</template>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Upload } from '@element-plus/icons-vue'
import { knowledge } from '@repo/api-service'
import FileUploadInput from '@/features/fileUpload/FileUploadInput.vue'
// import { Markdown } from '@repo/ui'
import type { WorkflowUploadFile } from '@/features/fileUpload/shared'
import type {
	FileKnowledgeForm,
	KnowledgeEditForm,
	KnowledgeItem,
	ManualKnowledgeForm,
	KnowledgeBaseItem,
	MetadataEntry
} from './types'

const props = defineProps<{ currentBase: KnowledgeBaseItem }>()

const loading = ref(false)
const submitLoading = ref(false)
const keyword = ref('')
const fileType = ref('')
const knowledgeList = ref<KnowledgeItem[]>([])
const isEdit = ref(false)

const manualDrawerVisible = ref(false)
const fileDrawerVisible = ref(false)
const editDrawerLoading = ref(false)
const editDrawerVisible = ref(false)
const uploadFile = ref<WorkflowUploadFile | null>(null)

const manualFormRef = ref()
const editFormRef = ref()

const manualForm = reactive<ManualKnowledgeForm>({
	title: '',
	content: '',
	publish: true
})

function createDefaultMetadata(): MetadataEntry[] {
	return [{ key: '', value: '' }]
}

const fileForm = reactive<FileKnowledgeForm>({
	enable_multi_model: false,
	metadata: createDefaultMetadata()
})

const editForm = reactive<KnowledgeEditForm>({
	id: '',
	title: '',
	description: ''
})

const manualRules = {
	title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
	content: [{ required: true, message: '请输入知识内容', trigger: 'blur' }]
}

const editRules = {
	title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
}

function getStatusTagType(status?: string) {
	if (!status) return 'info'
	const normalized = status.toLowerCase()
	if (['done', 'success', 'completed', 'finished'].includes(normalized)) return 'success'
	if (['failed', 'error'].includes(normalized)) return 'danger'
	if (['parsing', 'running', 'processing'].includes(normalized)) return 'warning'
	return 'info'
}

const stateMap = {
	done: '完成',
	completed: '完成',
	failed: '失败',
	finished: '结束',
	parsing: '解析中',
	error: '错误',
	running: '运行中',
	processing: '处理中'
}

async function fetchKnowledgeList() {
	if (!props.currentBase.id) return
	loading.value = true
	try {
		const res = await knowledge.postKnowledgePageList({
			knowledge_base_id: props.currentBase.id,
			title: keyword.value,
			file_type: fileType.value,
			pageIndex: 1,
			pageSize: 20
		})
		if (res?.isSuccess) {
			knowledgeList.value = (res.result?.model || []) as KnowledgeItem[]
		}
	} finally {
		loading.value = false
	}
}

function resetManualForm() {
	Object.assign(manualForm, {
		title: '',
		content: '',
		publish: true
	})
}

function resetFileForm() {
	Object.assign(fileForm, {
		enable_multi_model: false,
		metadata: createDefaultMetadata()
	})
	uploadFile.value = null
}

function addMetadataItem() {
	fileForm.metadata.push({ key: '', value: '' })
}

function removeMetadataItem(index: number) {
	if (fileForm.metadata.length <= 1) return
	fileForm.metadata.splice(index, 1)
}

function openManualDrawer() {
	resetManualForm()
	manualDrawerVisible.value = true
}

function openFileDrawer() {
	resetFileForm()
	fileDrawerVisible.value = true
}

async function openEditDrawer(row: KnowledgeItem) {
	// 获取详情
	try {
		editDrawerLoading.value = true
		const res = await knowledge.postKnowledgeInfo({
			id: row.id!
		})
		if (res.isSuccess) {
			editForm.description = res.result.description || row.description || ''
			editForm.title = res.result.title || row.title || ''
			editForm.id = row.id || ''
		}
	} finally {
		editDrawerLoading.value = false
	}
	editDrawerVisible.value = true
}

async function submitManualKnowledge() {
	const valid = await formValidate(manualFormRef.value)
	if (!valid) return

	submitLoading.value = true
	try {
		await knowledge.postKnowledgeCreateWithManual({
			knowledge_base_id: props.currentBase.id,
			title: manualForm.title,
			content: manualForm.content,
			publish: manualForm.publish
		})
		ElMessage.success('知识已创建')
		manualDrawerVisible.value = false
		await fetchKnowledgeList()
	} catch {
		ElMessage.error('创建失败')
	} finally {
		submitLoading.value = false
	}
}

function buildMetadataPayload() {
	return fileForm.metadata.reduce<Record<string, string>>((result, item) => {
		const key = item.key.trim()
		if (!key) return result
		result[key] = item.value
		return result
	}, {})
}

async function submitFileKnowledge() {
	const fileId = uploadFile.value?.path || ''
	if (!fileId) {
		ElMessage.warning('请先上传文件')
		return
	}

	submitLoading.value = true
	try {
		const res = await knowledge.postKnowledgeCreateWithFile({
			knowledge_base_id: props.currentBase.id,
			fileId,
			metadata: buildMetadataPayload(),
			enable_multi_model: fileForm.enable_multi_model
		})
		if (!res?.isSuccess) {
			ElMessage.error((res as any)?.error || '导入失败')
		} else {
			ElMessage.success('文件知识已导入')
			fileDrawerVisible.value = false
			await fetchKnowledgeList()
		}
	} catch {
		ElMessage.error('导入失败')
	} finally {
		submitLoading.value = false
	}
}

async function submitEditKnowledge() {
	const valid = await formValidate(editFormRef.value)
	if (!valid) return

	submitLoading.value = true
	try {
		await knowledge.postKnowledgeUpdate({
			id: editForm.id,
			title: editForm.title,
			description: editForm.description
		})
		ElMessage.success('知识已更新')
		editDrawerVisible.value = false
		await fetchKnowledgeList()
	} catch {
		ElMessage.error('更新失败')
	} finally {
		submitLoading.value = false
	}
}

async function reparseKnowledge(id?: string) {
	if (!id) return
	await knowledge.postKnowledgeReparse({ id })
	ElMessage.success('已触发重新解析')
	await fetchKnowledgeList()
}

async function removeKnowledge(id?: string) {
	if (!id) return
	const confirmed = await ElMessageBox.confirm('确定删除该知识吗？删除后不可恢复。', '删除确认', {
		type: 'warning'
	})
		.then(() => true)
		.catch(() => false)
	if (!confirmed) return

	await knowledge.postKnowledgeOpenApiDelete({ id })
	ElMessage.success('知识已删除')
	await fetchKnowledgeList()
}

async function formValidate(formInstance: any) {
	return formInstance
		?.validate()
		.then(() => true)
		.catch(() => false)
}

watch(
	() => props.currentBase.id,
	() => {
		keyword.value = ''
		fileType.value = ''
		knowledgeList.value = []
		if (props.currentBase.id) {
			void fetchKnowledgeList()
		}
	},
	{ immediate: true }
)
</script>

<style scoped lang="less">
.page-empty {
	min-height: calc(100vh - 360px);
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>

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

.action-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 16px;
	flex-wrap: wrap;
}

.action-bar__left,
.action-bar__right {
	display: flex;
	align-items: center;
	gap: 12px;
	flex-wrap: wrap;
}

.card-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 12px;
	font-weight: 600;
}

.card-header__meta {
	font-size: 12px;
	color: #6b7280;
}

.truncate-text {
	display: inline-block;
	max-width: 240px;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
}

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

.metadata-config {
	width: 100%;
}

.metadata-config__top {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.metadata-config__desc {
	color: #909399;
	font-size: 12px;
	margin: 4px 0 10px;
}

.metadata-config__rows {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.metadata-config__row {
	display: flex;
	gap: 8px;
	align-items: center;
}
</style>
