<template>
	<el-dialog
		v-model="visible"
		v-loading="loadingConfig"
		element-loading-text="获取配置中..."
		title="选择智能体"
		width="640px"
		append-to-body
		@close="handleClose"
	>
		<div class="agent-picker">
			<el-input v-model="keyword" clearable placeholder="搜索智能体" @keyup.enter="handleSearch">
				<template #append>
					<el-button @click="handleSearch">搜索</el-button>
				</template>
			</el-input>
			<el-scrollbar class="agent-picker__list">
				<div v-loading="loading" class="agent-list">
					<el-empty v-if="!agentOptions.length && !loading" description="暂无智能体" />
					<div
						v-for="item in agentOptions"
						:key="item.id"
						class="agent-option"
						:class="{ 'agent-option--active': selectedAgentId === item.id }"
						@click="handleSelectAgent(item)"
					>
						<div class="agent-option__left">
							<div class="agent-option__avatar">{{ getAgentAvatar(item.avatar) }}</div>
							<div class="agent-option__main">
								<div class="agent-option__name">{{ item.name || '未命名智能体' }}</div>
								<div class="agent-option__desc">{{ item.description || '暂无描述' }}</div>
							</div>
						</div>
						<el-tag size="small" effect="plain">{{ formatModeLabel(item.mode) }}</el-tag>
					</div>
				</div>
			</el-scrollbar>
			<el-pagination
				:page-size="pageSize"
				:total="totalCount"
				:current-page="currentPage"
				@current-change="handlePageChange"
				class="agent-pagination"
			/>
		</div>
		<template #footer>
			<el-button @click="handleClose">关闭</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { agentApplication } from '@repo/api-service'
import { ElMessage } from 'element-plus'

type AgentOption = NonNullable<
	Awaited<ReturnType<typeof agentApplication.postAiAgentPageList>>['result']
>['model'][number]

interface Props {
	modelValue: boolean
}

interface Emits {
	(e: 'update:modelValue', value: boolean): void
	(e: 'select', agent: AgentOption, config: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(props.modelValue)
const loading = ref(false)
const loadingConfig = ref(false)
const keyword = ref('')
const agentOptions = ref<AgentOption[]>([])
const selectedAgentId = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalCount = ref(0)

const formatModeLabel = (mode?: string) => {
	if (mode === 'quick-answer') return '快速问答'
	if (mode === 'smart-reasoning') return '智能推理'
	return mode || '未知模式'
}

const getAgentAvatar = (avatar?: string) => avatar?.trim() || '🤖'

const fetchAgentOptions = async (page = 1) => {
	loading.value = true
	try {
		const res = await agentApplication.postAiAgentPageList({
			keyword: keyword.value.trim(),
			mode: '',
			type: '',
			pageIndex: page,
			pageSize: pageSize.value
		})
		if (res?.isSuccess && res.result) {
			agentOptions.value = res.result.model || []
			totalCount.value = res.result.totalCount || 0
			currentPage.value = page
		}
	} finally {
		loading.value = false
	}
}

const handleSearch = () => {
	fetchAgentOptions(1)
}

const handlePageChange = (page: number) => {
	fetchAgentOptions(page)
}

const handleSelectAgent = async (item: AgentOption) => {
	selectedAgentId.value = item.id || ''
	try {
		loadingConfig.value = true
		// 获取选择agent的配置
		const res = await agentApplication.postAiAgentInfo({ id: item.id! })
		if (res.isSuccess && res.result) {
			emit('select', item, res.result.config)
			ElMessage.success('设置成功')
			handleClose()
		} else {
			ElMessage.error('获取配置失败')
		}
	} finally {
		loadingConfig.value = false
	}
}

const handleClose = () => {
	visible.value = false
	emit('update:modelValue', false)
}

watch(
	() => props.modelValue,
	(val) => {
		visible.value = val
		if (val && !agentOptions.value.length) {
			fetchAgentOptions(1)
		}
	}
)

watch(visible, (val) => {
	emit('update:modelValue', val)
})
</script>

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

.agent-picker__list {
	height: 360px;
}

.agent-list {
	min-height: 220px;
}

.agent-option {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 12px;
	padding: 12px;
	border: 1px solid var(--border-light);
	border-radius: 8px;
	cursor: pointer;
}

.agent-option + .agent-option {
	margin-top: 8px;
}

.agent-option:hover,
.agent-option--active {
	border-color: var(--el-color-primary);
	background: var(--el-color-primary-light-9);
}

.agent-option__left {
	display: flex;
	align-items: center;
	gap: 10px;
	min-width: 0;
}

.agent-option__avatar {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	width: 32px;
	height: 32px;
	flex-shrink: 0;
	font-size: 20px;
	line-height: 1;
	border-radius: 50%;
	background: var(--bg-container);
}

.agent-option__main {
	min-width: 0;
}

.agent-option__name {
	font-size: 14px;
	font-weight: 700;
	color: var(--text-primary);
}

.agent-option__desc {
	margin-top: 4px;
	font-size: 12px;
	color: var(--text-tertiary);
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.agent-pagination {
	margin-top: 12px;
	justify-content: center;
}
</style>
