<template>
	<XMarkdown v-bind="xMarkdownProps" :custom-attrs="markdownCustomAttrs">
		<!-- 知识引用 -->
		<template #kb="{ doc }">
			<span class="kb-reference">
				<el-icon class="kb-reference__icon"><Document /></el-icon>
				<span class="kb-reference__doc">{{ doc }}</span>
			</span>
		</template>
		<!-- UI信息卡片 -->
		<template #ai-ui-card="{ children, key, ...attrs }">
			<AiUiCard
				:attrs="attrs"
				:data="aiUiChildStrMap?.[key]"
				@submit="(val) => emit('card-submit', val)"
			/>
		</template>
		<!-- 图片预览 -->
		<template #img="{ ...props }">
			<el-image
				:key="props.key"
				:src="props.src"
				:preview-src-list="[props.src]"
				style="max-width: 80%"
				:style="props?.style"
			/>
		</template>
		<slot></slot>
	</XMarkdown>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue'
import { XMarkdown } from 'vue-element-plus-x'
import { Document } from '@element-plus/icons-vue'
import AiUiCard from './AiUiCard.vue'

import type { MarkdownProps } from 'vue-element-plus-x/types/XMarkdownCore/shared'

defineOptions({
	name: 'SMarkdown'
})

const props = defineProps<MarkdownProps>()
const emit = defineEmits<{
	(e: 'card-submit', payload: string): void
}>()
//
const aiUiChildStrMap = ref<Record<string, string>>()

const KB_SELF_CLOSING_TAG_RE = /<kb\b([^>]*)\/>/gi

const normalizeMarkdownContent = (content?: string) => {
	let text = `${content || ''}`

	// kb 自闭合标签补全
	text = text.replace(KB_SELF_CLOSING_TAG_RE, '<kb$1></kb>')

	// 提取 <ai-ui-card>xxx</ai-ui-card> 中间的 inner text 并剥离
	const AI_UI_CARD_RE = /<ai-ui-card([^>]*)>([\s\S]*?)<\/ai-ui-card>/gi
	const newMap: Record<string, string> = {}
	let cardIdx = 0
	text = text.replace(AI_UI_CARD_RE, (_match, attrs, inner) => {
		newMap[`ai-ui-card-${cardIdx}`] = inner
		cardIdx++
		return `<ai-ui-card${attrs}></ai-ui-card>`
	})
	aiUiChildStrMap.value = newMap
	// ai-ui-card: 流式输出时，不完整的标签先隐藏，待闭合标签完整后才渲染
	text = stripIncompleteAiCard(text)

	return text
}

function stripIncompleteAiCard(text: string): string {
	const openIdx = text.lastIndexOf('<ai-ui-card')
	if (openIdx === -1) return text

	const closeIdx = text.lastIndexOf('</ai-ui-card>')
	// 闭合标签在开标签之后 → 标签已完整，保留原文
	if (closeIdx > openIdx) return text

	// 标签未闭合（流式输出中）→ 去掉从开标签到末尾的部分
	return text.slice(0, openIdx)
}

const getMarkdownContent = computed(() => {
	return normalizeMarkdownContent(props.markdown)
})

const xMarkdownProps = computed(() => ({
	...props,
	markdown: getMarkdownContent.value
}))

const markdownCustomAttrs = {
	kb: (_node: any, attrs: Record<string, any>) => ({
		class: 'kb-reference-node',
		'data-doc': attrs.doc || '',
		'data-chunk-id': attrs.chunk_id || ''
	})
}
</script>

<style scoped lang="less">
.kb-reference {
	display: inline-flex;
	align-items: center;
	max-width: min(100%, 360px);
	height: 24px;
	margin: 0 3px;
	padding: 0 8px;
	border: 1px solid var(--el-color-primary-light-7);
	border-radius: 6px;
	background: var(--el-color-primary-light-9);
	color: var(--el-color-primary);
	font-size: 12px;
	line-height: 1;
	cursor: default;
	vertical-align: middle;
}

.kb-reference__icon {
	margin-right: 4px;
	font-size: 14px;
	flex-shrink: 0;
}

.kb-reference__doc {
	min-width: 0;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

/* -------- ai-ui-card styles -------- */
.ai-ui-card {
	display: block;
}

:deep(.ui-card) {
	margin: 12px 0;
	padding: 16px;
	border: 1px solid var(--el-border-color-light);
	border-radius: 12px;
	background: var(--el-bg-color);
	max-width: 400px;
	font-size: 14px;
	line-height: 1.5;
	color: var(--el-text-color-primary);
}

:deep(.ui-card__header) {
	display: flex;
	align-items: center;
	gap: 12px;
	margin-bottom: 14px;
}

:deep(.ui-card__icon) {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 36px;
	height: 36px;
	border-radius: 10px;
	background: var(--el-color-primary-light-9);
	color: var(--el-color-primary);
	font-size: 18px;
	flex-shrink: 0;
}

:deep(.ui-card__header-text) {
	min-width: 0;
	flex: 1;
}

:deep(.ui-card__title) {
	font-size: 15px;
	font-weight: 600;
	color: var(--el-text-color-primary);
	line-height: 1.3;
}

:deep(.ui-card__desc) {
	margin-top: 2px;
	font-size: 12px;
	color: var(--el-text-color-secondary);
	line-height: 1.4;
}

:deep(.ui-card__field) {
	margin-bottom: 12px;
}

:deep(.ui-card__label) {
	display: block;
	margin-bottom: 4px;
	font-size: 13px;
	font-weight: 500;
	color: var(--el-text-color-regular);
}

:deep(.ui-card__input-wrap) {
	width: 100%;
}

:deep(.ui-card__input) {
	display: block;
	width: 100%;
	height: 36px;
	padding: 0 12px;
	border: 1px solid var(--el-border-color);
	border-radius: 8px;
	background: var(--el-fill-color-blank);
	color: var(--el-text-color-primary);
	font-size: 14px;
	line-height: 36px;
	outline: none;
	transition: border-color 0.2s;
	box-sizing: border-box;

	&:focus {
		border-color: var(--el-color-primary);
		box-shadow: 0 0 0 2px var(--el-color-primary-light-8);
	}

	&::placeholder {
		color: var(--el-text-color-placeholder);
	}
}

:deep(.ui-card__actions) {
	display: flex;
	gap: 8px;
	margin-top: 14px;
}

:deep(.ui-card__btn) {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	height: 34px;
	padding: 0 16px;
	border: 1px solid var(--el-border-color);
	border-radius: 8px;
	background: var(--el-bg-color);
	color: var(--el-text-color-regular);
	font-size: 13px;
	cursor: pointer;
	transition: all 0.2s;
	line-height: 1;

	&:hover {
		border-color: var(--el-color-primary-light-3);
		color: var(--el-color-primary);
		background: var(--el-color-primary-light-9);
	}
}

:deep(.ui-card__btn--primary) {
	background: var(--el-color-primary);
	border-color: var(--el-color-primary);
	color: #fff;

	&:hover {
		background: var(--el-color-primary-light-3);
		border-color: var(--el-color-primary-light-3);
		color: #fff;
	}
}

:deep(.ui-card__data) {
	margin: 8px 0;
	padding: 10px 12px;
	border-radius: 8px;
	background: var(--el-fill-color);
	font-size: 12px;
	line-height: 1.6;
	white-space: pre-wrap;
	word-break: break-all;
	color: var(--el-text-color-regular);
	overflow: auto;
}

:deep(.ui-card__success) {
	display: flex;
	align-items: center;
	gap: 6px;
	padding: 10px 0 0;
	color: var(--el-color-success);
	font-size: 14px;
	font-weight: 500;
}

:deep(.ui-card__success-icon) {
	font-size: 16px;
}
</style>
