<template>
	<el-dialog v-model="visible" :title="t('pages.chat.addKbTitle')" width="600px">
		<el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
			<el-form-item :label="t('pages.chat.knowledgeBase')" prop="knowledge_base_id">
				<el-select
					v-model="formData.knowledge_base_id"
					:options="knowledgeOptions"
					:placeholder="t('pages.chat.selectKnowledgeBase')"
					filterable
					remote
					:remote-method="getKbOptions"
				/>
			</el-form-item>
			<el-form-item :label="t('pages.chat.title')" prop="title">
				<el-input v-model="formData.title"></el-input>
			</el-form-item>
			<el-form-item :label="t('pages.chat.content')" prop="content">
				<el-input v-model="formData.content" :rows="10" type="textarea"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="handleClose">{{ t('common.cancel') }}</el-button>
			<el-button type="primary" :loading="loading" @click="handleSubmit">{{
				t('common.save')
			}}</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { knowledge } from '@repo/api-service'
import type { FormInstance } from 'element-plus'
import { useI18n } from '@/composables/useI18n'

const { t } = useI18n()

const visible = ref(false)
const formRef = ref<FormInstance>()
const knowledgeOptions = ref<{ label: string; value: string }[]>([])
const kbLoading = ref(false)
const loading = ref(false)
const formData = ref({
	knowledge_base_id: '',
	title: '',
	content: '',
	publish: true
})

const rules = {
	knowledge_base_id: [
		{ required: true, message: t('pages.chat.selectKnowledgeBase'), trigger: 'change' }
	],
	title: [{ required: true, message: t('pages.chat.titleRequired'), trigger: 'blur' }],
	content: [{ required: true, message: t('pages.chat.contentRequired'), trigger: 'blur' }]
}

const getKbOptions = async (keyword: string = '') => {
	try {
		const res = await knowledge.postAiKnowledgeBaseSelectList({
			keyword,
			type: 'document'
		})
		if (res.isSuccess)
			knowledgeOptions.value = (res.result || []).map((item) => ({
				label: item.name,
				value: item.id
			}))
	} finally {
		kbLoading.value = false
	}
}

const handleClose = () => {
	formRef.value?.resetFields()
	visible.value = false
}

const handleSubmit = async () => {
	const vilid = await formRef.value?.validate()

	if (vilid) {
		try {
			loading.value = true
			const res = await knowledge.postAiKnowledgeCreateWithManual({
				...formData.value
			})

			if (res.isSuccess) {
				ElMessage.success(t('pages.chat.addKbSuccess'))
				handleClose()
			}
		} finally {
			loading.value = false
		}
	}
}

defineExpose({
	open: (val: string) => {
		getKbOptions()
		visible.value = true
		formRef.value?.resetFields()

		formData.value.content = val
	}
})
</script>

<style scoped></style>
