<template>
	<el-dialog title="新增热词" v-model="state.dialogVisible" width="500px" draggable @close="close">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="90px">
			<el-form-item label="热词名称" prop="keyWord" :rules="[{ required: true, message: '请填写热词名称', trigger: 'blur' }]">
				<el-input v-model="state.ruleForm.keyWord" placeholder="请填写热词名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="类型" prop="type">
				<el-select v-model="state.ruleForm.type" placeholder="请选择类型" clearable>
					<el-option v-for="items in props.typeOptions" :key="items.key" :label="items.value" :value="items.key" />
				</el-select>
			</el-form-item>
			<el-form-item label="排序" prop="sort" :rules="[{ required: true, message: '请填写排序', trigger: 'blur' }]">
				<el-input-number v-model="state.ruleForm.sort" controls-position="right" placeholder="请填写排序" class="w100" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确 定 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { addKnowledgeHotWords } from '@/api/knowledge/hotWords';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

const props = defineProps({
	typeOptions:{
		type: Array,
		default: () => []
	}
})
// 定义变量内容
const ruleFormRef = ref<FormInstance>();
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		keyWord: '', // 热词名称
		sort: 1, // 排序
		type:null
	},
	loading: false, // 确定按钮loading
});
// 打开弹窗
const openDialog = async () => {
	state.dialogVisible = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 新增
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		addKnowledgeHotWords(state.ruleForm)
			.then(() => {
				emit('updateList');
				closeDialog(); // 关闭弹窗
				ElMessage.success('操作成功');
				state.loading = false;
			})
			.catch(() => {
				emit('updateList');
				state.loading = false;
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
