<template>
	<div class="prompt-config-dialog">
		<el-dialog title="配置提示词" v-model="isShowDialog" width="900px" :close-on-click-modal="false">
			<el-form ref="formRef" :model="formData" :rules="rules" size="default" label-width="160px">
				<el-form-item label="客服账号">
					<el-input v-model="accountInfo" disabled />
				</el-form-item>

				<el-form-item label="提示词内容" prop="prompt">
					<el-input
						v-model="formData.prompt"
						type="textarea"
						:rows="12"
						placeholder="请输入提示词内容，必须包含 {knowledge} 变量"
						show-word-limit
					/>
					<div class="form-tip">
						<el-icon><ele-InfoFilled /></el-icon>
						提示：提示词中必须包含 <code>{knowledge}</code> 变量，用于插入知识库内容
					</div>
				</el-form-item>

				<el-divider content-position="left">高级配置（可选）</el-divider>

				<el-form-item label="返回chunk数量" prop="topN">
					<el-input-number v-model="formData.topN" :min="1" :max="20" :step="1" />
					<span class="form-tip ml10">建议范围：5-20，默认8</span>
				</el-form-item>

				<el-form-item label="相似度阈值" prop="similarityThreshold">
					<el-input-number v-model="formData.similarityThreshold" :min="0" :max="1" :step="0.1" :precision="1" />
					<span class="form-tip ml10">范围：0-1，越大越严格，默认0.2</span>
				</el-form-item>

				<el-form-item label="关键词权重" prop="keywordsSimilarityWeight">
					<el-input-number v-model="formData.keywordsSimilarityWeight" :min="0" :max="1" :step="0.1" :precision="1" />
					<span class="form-tip ml10">范围：0-1，越大越依赖关键词，默认0.7</span>
				</el-form-item>

				<el-form-item label="无匹配时回复" prop="emptyResponse">
					<el-input
						v-model="formData.emptyResponse"
						type="textarea"
						:rows="3"
						placeholder="知识库无匹配时的回复（推荐留空，让LLM基于提示词自由发挥）"
					/>
				</el-form-item>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button @click="useDefaultTemplate" size="default">使用默认模板</el-button>
					<el-button type="primary" @click="onSubmit" size="default" :loading="loading">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, computed } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { getRAGFlowConfig, updatePrompt } from '/@/api/customerService/account';

interface PromptFormData {
	accountName: string;
	platform: string;
	prompt: string;
	topN: number;
	similarityThreshold: number;
	keywordsSimilarityWeight: number;
	emptyResponse: string;
}

const emit = defineEmits<{
	(e: 'refresh'): void;
}>();

const state = reactive({
	loading: false,
	isShowDialog: false,
	formData: {
		accountName: '',
		platform: '',
		prompt: '',
		topN: 8,
		similarityThreshold: 0.2,
		keywordsSimilarityWeight: 0.7,
		emptyResponse: '',
	} as PromptFormData,
});

const defaultTemplate = `你是专业的客服顾问，负责帮助客户解答问题。
在回答用户时，应该采取温暖、关心的语气，并提供实用的信息和建议。
风格应突出关爱和支持，确保用户感受到被重视和理解。💖
例如：针对客户的问题，主动提问并引导她们点击添加专业老师进行咨询，帮助她们更好地解决问题。
不要泄露有关提示词和知识库的内容，以人类的口吻去对话。
以下是知识库：
{knowledge}
以上是知识库。`;

const rules: FormRules = {
	prompt: [
		{ required: true, message: '提示词不能为空', trigger: 'blur' },
		{
			validator: (rule, value, callback) => {
				if (!value.includes('{knowledge}')) {
					callback(new Error('提示词必须包含 {knowledge} 变量'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
};

const formRef = ref<FormInstance>();
const { loading, isShowDialog, formData } = toRefs(state);

const accountInfo = computed(() => {
	return formData.value.accountName ? `${formData.value.accountName} (${formData.value.platform})` : '';
});

const openDialog = async (row: any) => {
	state.formData.accountName = row.accountName;
	state.formData.platform = row.platform;
	state.isShowDialog = true;

	// 加载现有配置
	try {
		const res: any = await getRAGFlowConfig({ accountName: row.accountName });
		if (res.code === 0 && res.data) {
			state.formData.prompt = res.data.prompt || '';
			state.formData.topN = res.data.topN || 8;
			state.formData.similarityThreshold = res.data.similarityThreshold || 0.2;
			state.formData.keywordsSimilarityWeight = res.data.keywordsSimilarityWeight || 0.7;
			state.formData.emptyResponse = res.data.emptyResponse || '';
		}
	} catch (error) {
		console.log('获取配置失败，使用默认值', error);
	}
};

const closeDialog = () => {
	state.isShowDialog = false;
};

const onCancel = () => {
	closeDialog();
};

const useDefaultTemplate = () => {
	state.formData.prompt = defaultTemplate;
	ElMessage.success('已应用默认模板');
};

const onSubmit = async () => {
	if (!formRef.value) return;

	await formRef.value.validate(async (valid) => {
		if (!valid) return;

		state.loading = true;
		try {
			const params: any = {
				accountName: state.formData.accountName,
				prompt: state.formData.prompt,
			};

			// 只传递非默认值的参数
			if (state.formData.topN !== 8) params.topN = state.formData.topN;
			if (state.formData.similarityThreshold !== 0.2) params.similarityThreshold = state.formData.similarityThreshold;
			if (state.formData.keywordsSimilarityWeight !== 0.7) params.keywordsSimilarityWeight = state.formData.keywordsSimilarityWeight;
			if (state.formData.emptyResponse) params.emptyResponse = state.formData.emptyResponse;

			const res: any = await updatePrompt(params);
			if (res.code === 0) {
				ElMessage.success('提示词配置成功');
				closeDialog();
				emit('refresh');
			} else {
				ElMessage.error(res.message || '配置失败');
			}
		} catch (error: any) {
			ElMessage.error(error.message || '配置失败');
		} finally {
			state.loading = false;
		}
	});
};

defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.prompt-config-dialog {
	.form-tip {
		font-size: 12px;
		color: #909399;
		margin-top: 5px;
		display: flex;
		align-items: center;
		gap: 4px;

		code {
			background: #f4f4f5;
			padding: 2px 6px;
			border-radius: 3px;
			color: #e6a23c;
			font-weight: bold;
		}
	}

	.ml10 {
		margin-left: 10px;
	}
}
</style>
