<template>
	<div class="knowledge-standard-container layout-pd">
		<el-card shadow="never">
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="80px">
				<el-form-item label="标题" prop="title" :rules="[{ required: true, message: '填写标题，不超过30个字', trigger: 'blur' }]">
					<el-input v-model="state.ruleForm.title" placeholder="填写标题，不超过30个字" clearable max-length="30"></el-input>
				</el-form-item>
				<el-form-item label="正文" prop="content" :rules="[{ required: true, message: '请填写正文内容', trigger: 'blur' }]">
					<editor v-model:get-html="state.ruleForm.content" :disable="state.disable" placeholder="请填写正文内容" height="500px" />
				</el-form-item>
				<el-form-item>
					<el-button class="default-button" @click="onPreview">预 览</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading" v-auth="'knowledge:standard:edit'"> 发 布</el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<el-drawer title="知识编写规范预览" v-model="state.dialogVisible" size="40%">
			<div>
				<h3 class="font18">{{ state.ruleForm.title }}</h3>
				<div v-html="state.ruleForm.content" class="mt20 lineHeight24"></div>
			</div>
		</el-drawer>
	</div>
</template>

<script setup lang="ts" name="knowledgeStandard">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import { useRoute } from 'vue-router';
import { standardInfo, standardUpdate } from '@/api/knowledge/standard';
import mittBus from '@/utils/mitt';

// 引入组件
const Editor = defineAsyncComponent(() => import('@/components/Editor/index.vue')); // 富文本编辑器

// 定义变量内容
const state = reactive<any>({
	ruleForm: {
		content: '', // 内容
		title: '', // 标题
	},
	disable: false, // 是否禁用
	loading: false, // 是否加载中
	dialogVisible: false, // 是否显示预览弹窗
});
// 新增
const route = useRoute(); // 路由
const ruleFormRef = ref<RefType>(); // 表单ref
const onSubmit = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		ElMessageBox.confirm(`是否要发布？`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(() => {
				standardUpdate(state.ruleForm).then(() => {
					ElMessage.success('发布成功');
					mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
				});
			})
			.catch(() => {});
	});
}, 500);
// 预览
const onPreview = () => {
	state.dialogVisible = true;
};
// 查询规范详情
const standardInfoFn = async () => {
	try {
		state.loading = true;
		const res: any = await standardInfo();
		state.ruleForm = res.result ?? {};
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
onMounted(() => {
	standardInfoFn();
});
</script>
