<template>
	<div class="document-manage">
		<div class="action-bar">
			<div class="action-bar__left">
				<el-input
					v-model="keyword"
					clearable
					:placeholder="t('pages.knowledge.document.searchPlaceholder')"
					style="width: 240px"
					@keyup.enter="fetchKnowledgeList"
					@blur="fetchKnowledgeList"
					@change="fetchKnowledgeList"
				/>
				<el-input
					v-model="fileType"
					clearable
					:placeholder="t('pages.knowledge.document.fileTypePlaceholder')"
					style="width: 180px"
					@keyup.enter="fetchKnowledgeList"
					@blur="fetchKnowledgeList"
					@change="fetchKnowledgeList"
				/>

				<el-button @click="fetchKnowledgeList">
					<el-icon>
						<Refresh />
					</el-icon>
					{{ t('pages.knowledge.document.refresh') }}
				</el-button>
			</div>
			<div class="action-bar__right">
				<el-button v-permission="{ buttonCode: 'upload_doc', menuCode: 'sys_ai_knowledge_base' }" @click="openFileDrawer">
					<el-icon>
						<Upload />
					</el-icon>
					{{ t('pages.knowledge.document.uploadFile') }}
				</el-button>
				<el-button v-permission="{ buttonCode: 'add_md', menuCode: 'sys_ai_knowledge_base' }" type="primary" @click="openManualDrawer">
					<el-icon>
						<Plus />
					</el-icon>
					{{ t('pages.knowledge.document.custom') }}
				</el-button>
			</div>
		</div>

		<el-card>
			<template #header>
				<div class="card-header">
					<span>{{ t('pages.knowledge.document.listTitle') }}</span>
				</div>
			</template>

			<el-table
				v-if="knowledgeList.length || loading"
				:data="knowledgeList"
				v-loading="loading"
				border
			>
				<el-table-column prop="title" :label="t('pages.knowledge.document.title')" min-width="220" />
				<el-table-column prop="type" :label="t('pages.knowledge.document.type')" width="100">
					<template #default="{ row }">
						<el-tag v-if="row.type === 'file'">{{ t('pages.knowledge.document.fileUpload') }}</el-tag>
						<el-tag v-if="row.type === 'manual'">{{ t('pages.knowledge.document.custom') }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="file_name" :label="t('pages.knowledge.document.fileName')" min-width="180" />
				<el-table-column prop="file_type" :label="t('pages.knowledge.document.fileType')" width="100" />
				<el-table-column prop="source" :label="t('pages.knowledge.document.source')" width="110" />
				<el-table-column prop="parse_status" :label="t('pages.knowledge.document.parseStatus')" 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="t('pages.knowledge.document.summaryStatus')" 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="t('pages.knowledge.document.errorMessage')" min-width="180">
					<template #default="{ row }">
						<span class="truncate-text">{{ row.error_message || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="creationTime" :label="t('pages.knowledge.document.creationTime')" width="180" />
				<el-table-column :label="t('pages.knowledge.document.actions')" width="220" fixed="right">
					<template #default="{ row }">
						<el-button
							v-permission="{ buttonCode: 'edit_doc', menuCode: 'sys_ai_knowledge_base' }"
							v-if="row.file_type === 'manual'"
							link
							type="primary"
							@click="openEditDrawer(row)"
						>
							{{ t('pages.knowledge.document.update') }}
						</el-button>
						<el-button v-permission="{ buttonCode: 'rebuild_index', menuCode: 'sys_ai_knowledge_base' }" link type="warning" @click="reparseKnowledge(row.id)">{{ t('pages.knowledge.document.reparse') }}</el-button>
						<el-button v-permission="{ buttonCode: 'del_doc', menuCode: 'sys_ai_knowledge_base' }" link type="danger" @click="removeKnowledge(row.id)">{{ t('common.delete') }}</el-button>
					</template>
				</el-table-column>
				<template #empty>{{ t('pages.knowledge.document.noContent') }}</template>
			</el-table>
			<el-empty v-else :description="t('pages.knowledge.document.noContent')" class="page-empty" />
		</el-card>
		<!-- 新建 -->
		<el-drawer v-model="manualDrawerVisible" :title="t('pages.knowledge.document.createTitle')" direction="rtl" size="640px">
			<el-form ref="manualFormRef" :model="manualForm" :rules="manualRules" label-position="top">
				<el-form-item :label="t('pages.knowledge.document.title')" prop="title">
					<el-input v-model="manualForm.title" :placeholder="t('pages.knowledge.document.titlePlaceholder')" />
				</el-form-item>
				<el-form-item :label="t('pages.knowledge.document.contentLabel')" prop="content">
					<el-input v-model="manualForm.content" type="textarea" :placeholder="t('pages.knowledge.document.contentPlaceholder')" />
				</el-form-item>
				<el-form-item :label="t('pages.knowledge.document.publish')">
					<el-switch v-model="manualForm.publish" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="drawer-footer">
					<el-button @click="manualDrawerVisible = false">{{ t('common.cancel') }}</el-button>
					<el-button type="primary" :loading="submitLoading" @click="submitManualKnowledge">
						{{ t('common.submit') }}
					</el-button>
				</div>
			</template>
		</el-drawer>
		<!-- 导入模版 -->
		<el-drawer v-model="fileDrawerVisible" :title="t('pages.knowledge.document.importTitle')" direction="rtl" size="640px">
			<el-form :model="fileForm" label-position="top">
				<el-form-item :label="t('pages.knowledge.document.uploadFile')">
					<FileUploadInput
						v-model="uploadFile"
						:multiple="false"
						:file-types="['document', 'image', 'audio']"
						:allow-link-input="false"
						:tip="t('pages.knowledge.document.uploadTip')"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item>
					<div class="metadata-config">
						<div class="metadata-config__top">
							<span>{{ t('pages.knowledge.document.metadataOptional') }}</span>
							<el-button type="primary" link @click="addMetadataItem">
								<el-icon> <Plus /> </el-icon>{{ t('pages.knowledge.document.addMetadata') }}
							</el-button>
						</div>
						<div class="metadata-config__desc">
							{{ t('pages.knowledge.document.metadataDesc') }}
						</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="t('pages.knowledge.document.metadataKeyPlaceholder')" />
								<el-input v-model="item.value" :placeholder="t('pages.knowledge.document.metadataValuePlaceholder')" />
								<el-button
									link
									type="danger"
									:disabled="fileForm.metadata.length === 1"
									@click="removeMetadataItem(index)"
								>
									{{ t('common.delete') }}
								</el-button>
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item :label="t('pages.knowledge.document.enableMultiModel')">
					<el-switch v-model="fileForm.enable_multi_model" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="drawer-footer">
					<el-button @click="fileDrawerVisible = false">{{ t('common.cancel') }}</el-button>
					<el-button type="primary" :loading="submitLoading" @click="submitFileKnowledge">
						{{ t('common.submit') }}
					</el-button>
				</div>
			</template>
		</el-drawer>
		<!-- 编辑 -->
		<el-drawer
			v-model="editDrawerVisible"
			:title="t('pages.knowledge.document.editTitle')"
			direction="rtl"
			size="560px"
			class="edit-knowledge-drawer"
		>
			<el-form
				ref="editFormRef"
				v-loading="editDrawerLoading"
				:model="editForm"
				:rules="editRules"
				label-position="top"
				class="edit-knowledge-form"
			>
				<el-form-item :label="t('pages.knowledge.document.title')" prop="title">
					<el-input v-model="editForm.title" />
				</el-form-item>
				<el-form-item :label="t('pages.knowledge.document.descriptionLabel')" class="edit-description-item">
					<!-- <markdown v-if="!isEdit" :content="editForm.description" @click="isEdit = true" /> -->
					<el-input
						v-model="editForm.description"
						type="textarea"
						class="edit-description-input"
						@blur="isEdit = false"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="drawer-footer">
					<el-button @click="editDrawerVisible = false">{{ t('common.cancel') }}</el-button>
					<el-button type="primary" :loading="submitLoading" @click="submitEditKnowledge">
						{{ t('common.save') }}
					</el-button>
				</div>
			</template>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { useI18n } from '@/composables/useI18n'
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 { t } = useI18n()

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: t('pages.knowledge.document.titleRequired'), trigger: 'blur' }],
	content: [{ required: true, message: t('pages.knowledge.document.contentRequired'), trigger: 'blur' }]
}

const editRules = {
	title: [{ required: true, message: t('pages.knowledge.document.titleRequired'), 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', 'pending'].includes(normalized)) return 'warning'
	return 'info'
}

const stateMap = computed(() => ({
	done: t('pages.knowledge.document.stateDone'),
	completed: t('pages.knowledge.document.stateDone'),
	failed: t('pages.knowledge.document.stateFailed'),
	finished: t('pages.knowledge.document.stateFinished'),
	parsing: t('pages.knowledge.document.stateParsing'),
	error: t('pages.knowledge.document.stateError'),
	running: t('pages.knowledge.document.stateRunning'),
	processing: t('pages.knowledge.document.stateProcessing'),
	pending: t('pages.knowledge.document.stateProcessing'),
	finalizing: t('pages.knowledge.document.stateFinalizing'),
	none: t('pages.knowledge.document.stateNone')
}))

async function fetchKnowledgeList() {
	if (!props.currentBase.id) return
	loading.value = true
	try {
		const res = await knowledge.postAiKnowledgePageList({
			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.postAiKnowledgeInfo({
			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.postAiKnowledgeCreateWithManual({
			knowledge_base_id: props.currentBase.id,
			title: manualForm.title,
			content: manualForm.content,
			publish: manualForm.publish
		})
		ElMessage.success(t('pages.knowledge.document.createSuccess'))
		manualDrawerVisible.value = false
		await fetchKnowledgeList()
	} catch {
		ElMessage.error(t('pages.knowledge.document.createFailed'))
	} 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(t('pages.knowledge.document.uploadFileFirst'))
		return
	}

	submitLoading.value = true
	try {
		const res = await knowledge.postAiKnowledgeCreateWithFile({
			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 || t('pages.knowledge.document.importFailed'))
		} else {
			ElMessage.success(t('pages.knowledge.document.importSuccess'))
			fileDrawerVisible.value = false
			await fetchKnowledgeList()
		}
	} catch {
		ElMessage.error(t('pages.knowledge.document.importFailed'))
	} finally {
		submitLoading.value = false
	}
}

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

	submitLoading.value = true
	try {
		await knowledge.postAiKnowledgeUpdate({
			id: editForm.id,
			title: editForm.title,
			description: editForm.description
		})
		ElMessage.success(t('pages.knowledge.document.updateSuccess'))
		editDrawerVisible.value = false
		await fetchKnowledgeList()
	} catch {
		ElMessage.error(t('pages.knowledge.document.updateFailed'))
	} finally {
		submitLoading.value = false
	}
}

async function reparseKnowledge(id?: string) {
	if (!id) return
	await knowledge.postAiKnowledgeReparse({ id })
	ElMessage.success(t('pages.knowledge.document.reparseSuccess'))
	await fetchKnowledgeList()
}

async function removeKnowledge(id?: string) {
	if (!id) return
	const confirmed = await ElMessageBox.confirm(t('pages.knowledge.document.confirmDelete'), t('pages.knowledge.document.deleteTitle'), {
		type: 'warning'
	})
		.then(() => true)
		.catch(() => false)
	if (!confirmed) return

	await knowledge.postAiKnowledgeOpenApiDelete({ id })
	ElMessage.success(t('pages.knowledge.document.deleteSuccess'))
	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;

	.el-button + .el-button {
		margin-left: 0;
	}
}

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

.card-header__meta {
	font-size: 12px;
	color: var(--text-tertiary);
}

.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;
}

:global(.edit-knowledge-drawer) {
	display: flex;
	flex-direction: column;
}

:global(.edit-knowledge-drawer .el-drawer__header),
:global(.edit-knowledge-drawer .el-drawer__footer) {
	flex: 0 0 auto;
}

:global(.edit-knowledge-drawer .el-drawer__body) {
	flex: 1;
	display: flex;
	flex-direction: column;
	min-height: 0;
	padding-bottom: 12px;
	overflow: hidden;
}

.edit-knowledge-form {
	flex: 1;
	display: flex;
	flex-direction: column;
	min-height: 0;
}

.edit-knowledge-form :deep(.el-form-item:last-child) {
	flex: 1;
	min-height: 0;
	margin-bottom: 0;
}

.edit-description-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	min-height: 0;
	margin-bottom: 0;
}

.edit-description-item :deep(.el-form-item__content) {
	flex: 1;
	min-height: 0;
	display: flex;
}

.edit-description-input {
	flex: 1;
	height: 100%;
	min-height: 0;
}

.edit-description-input :deep(.el-textarea__inner) {
	height: 100%;
	min-height: 100%;
	resize: none;
}

.metadata-config {
	width: 100%;
}

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

.metadata-config__desc {
	color: var(--text-tertiary);
	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>
