<template>
	<div class="knowledge-preview-container layout-pd">
		<el-card shadow="never">
			<el-row v-loading="loading">
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
					<h1 class="font18">{{ state.info.title }}</h1></el-col
				>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="color-info flex-center-align flex-warp">
					<span class="mr10">创建时间：{{ formatDate(state.info.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					<span class="mr10">创建人：{{ state.info.creatorName }}</span>
					<span class="mr10">创建部门：{{ state.info.creatorOrgName }}</span>
					<span class="mr10">更新时间：{{ formatDate(state.info.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					<span class="mr10">知识分类：{{ state.info.knowledgeType?.map(item=> item.value).join(',') }}</span>
					<template v-if="route.params.id">
						<span class="mr10">已阅：{{ state.info.pageView }}</span>
						<el-button link class="flex-center-align" type="info" @click="onCollect" v-auth="'knowledge:collect:collect'">
							<SvgIcon :name="state.info?.collect?.collect ? 'ele-StarFilled' : 'ele-Star'" class="mr4" size="18px" />{{
								state.info?.collect?.collect ? '取消收藏' : '收藏'
							}}
						</el-button>
						<el-button link class="flex-center-align" type="info" v-auth="'knowledge:collect:rate'">
							<el-rate v-model="state.info.score" allow-half @change="onRate" /> 评分</el-button
						>
						<el-button link class="flex-center-align" type="info" @click="onError"> <SvgIcon name="ele-EditPen" class="mr4" />知识纠错</el-button>
						<el-button link class="flex-center-align" type="info" @click="onQuestion">
							<SvgIcon name="ele-QuestionFilled" class="mr4" />知识提问</el-button
						>
					</template>
				</el-col>
				<el-divider />
				摘要
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt5"> {{ state.info.summary }}</el-col>
				<el-divider />
				正文
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt5 editor-content-view">
					<div v-html="state.info.content" class="lineHeight24"></div
				></el-col>
				<template v-if="state.info.knowledgeDtos && state.info.knowledgeDtos.length">
					<el-divider />
					关联知识
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt5">
						<div v-for="item in state.info.knowledgeDtos" @click="onPreview(item)" class="relevance">
							<el-link type="primary">{{ item.title }}</el-link>
						</div>
					</el-col>
				</template>
				<template v-if="route.params.id">
					<el-divider />
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt10">
						<el-form-item label="附件">
							<annex-list name="知识附件" v-model="state.info.files" readonly classify="知识附件" />
						</el-form-item>
					</el-col>
				</template>
			</el-row>
			<el-button
				type="primary"
				@click="onAudit"
				title="审批"
				v-if="[1, 2].includes(state.info.status) && state.info.isCanHandle"
				v-auth="'knowledge:index:audit'"
			>
				审批
			</el-button>
		</el-card>
		<!-- 知识纠错 -->
		<error-add ref="errorAddRef" />
		<!-- 知识提问 -->
		<question-add ref="questionRef" />
		<!-- 流程审批 -->
		<process-audit ref="processAuditRef" @orderProcessSuccess="closePage" />
	</div>
</template>

<script setup lang="ts" name="knowledgePreview">
import { reactive, onMounted, onBeforeUnmount, ref, defineAsyncComponent } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Local } from '@/utils/storage';
import { KnowledgeInfo, knowledgeCollect, knowledgeScore } from '@/api/knowledge';
import { formatDate } from '@/utils/formatTime';
import { ElMessage } from 'element-plus';
import mittBus from '@/utils/mitt';
import { transformFile } from '@/utils/tools';

// 引入组件
const ErrorAdd = defineAsyncComponent(() => import('@/views/knowledge/error/components/Error-add.vue')); // 知识纠错
const QuestionAdd = defineAsyncComponent(() => import('@/views/knowledge/question/components/Question-add.vue')); // 知识提问
const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件列表
const ProcessAudit = defineAsyncComponent(() => import('@/components/ProcessAudit/index.vue')); // 流程审批

// 定义变量内容
const state = reactive<any>({
	info: {
		knowledgeTypeName: '', // 类别
		hotspotName: '', // 热点
		keywords: '', // 关键词
		isPublic: false, // 是否公开
		creatorName: '', // 创建人
		creationTime: '', // 创建时间
		summary: '', // 摘要
		content: '', // 内容
		collect: false, // 收藏
		score: 0, // 评分
	},
});
const loading = ref<Boolean>(false); // 加载状态
// 查询知识详情
const route = useRoute(); //  获取路由参数
// 收藏
const onCollect = () => {
	knowledgeCollect({ knowledgeId: state.info.id, collect: !state.info?.collect?.collect })
		.then(() => {
			ElMessage.success('操作成功');
			getInfo();
		})
		.catch(() => {});
};
// 评分
const onRate = () => {
	knowledgeScore({ knowledgeId: state.info.id, score: state.info.score })
		.then(() => {
			ElMessage.success('操作成功');
			getInfo();
		})
		.catch(() => {});
};
// 知识纠错
const errorAddRef = ref<RefType>();
const onError = () => {
	errorAddRef.value?.openDialog(state.info);
};
// 知识提问
const questionRef = ref<RefType>();
const onQuestion = () => {
	questionRef.value?.openDialog(state.info);
};
// 预览
const router = useRouter();
const onPreview = (row: any) => {
	if (!router.hasRoute('knowledgePreview')) {
		ElMessage.warning('未找到知识查看页面');
		return;
	}
	router.push({
		name: 'knowledgePreview',
		params: {
			id: row.id,
			tagsViewName: '知识查看',
		},
	});
};
// 查询详情
const getInfo = async () => {
	loading.value = true;
	if (route.params.id) {
		try {
			const { isAddPv } = route.params;
			let IsAddPv = isAddPv ? 'true' : false;
			const res: any = await KnowledgeInfo(route.params.id, { isAddPv: IsAddPv });
			state.info = res.result ?? {};
			state.info.files = transformFile(state.info.files);
			loading.value = false;
		} catch (error) {
			loading.value = false;
		}
	} else {
		state.info = Local.get('previewForm') ?? {};
		state.info.files = transformFile(state.info.files);
		loading.value = false;
	}
};
// 审批
const processAuditRef = ref<RefType>(); //审核记录ref
const onAudit = () => {
	const params = {
		id: state.info.workflowId,
		processType: '知识审批',
		orderDetail: state.info,
		extra: {
			dialogTitle: '知识审批',
			inputPlaceholder: '办理意见',
			annexName: '知识附件',
		},
	};
	processAuditRef.value.openDialog(params);
};
// 关闭当前页
const closePage = () => {
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'knowledgeManage');
	router.push({
		path: '/knowledge/index',
	});
};

onMounted(() => {
	getInfo();
});
onBeforeUnmount(() => {
	Local.remove('previewForm'); // 删除本地缓存
});
</script>
<style lang="scss" scoped>
.knowledge-preview-container {
	.relevance {
		margin-bottom: 5px;
		&:last-child {
			margin-bottom: 0;
		}
	}
}
</style>
