<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" v-if="state.info.knowledgeTypeText">知识分类：{{ state.info.knowledgeTypeText }}</span>
					<span class="mr10" v-if="state.info.source">知识来源：{{ state.info.source }}</span>
					<span class="mr10">是否公开：{{ state.info.isPublic ? '是' : '否' }}</span>
					<template v-if="haveId">
						<span class="mr10">已阅：{{ state.info.pageView }}</span>
						<el-button
							link
							class="flex-center-align"
							type="info"
							@click="onCollect(state.info?.collect?.collect)"
							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
						>
						<el-dropdown v-auth="'knowledge:index:export:detail'" @command="onExportDetail" class="ml12">
							<el-button type="info" :loading="state.loading" link> 导出详情<SvgIcon name="ele-ArrowDown" class="ml3" /> </el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item :command="item.key" v-for="item in exportType" :key="item.key">{{ item.value }}</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</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="haveId">
					<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" />

		<!-- 收藏 -->
		<el-dialog v-model="state.collectDialogVisible" draggable title="收藏知识" width="30%" @close="collectFormClose" append-to-body destroy-on-close>
			<el-form :model="state.collectForm" label-width="80px" ref="collectFormRef" @submit.native.prevent>
				<el-form-item label="收藏分组" prop="KnowledgeCollectGroupId" :rules="[{ required: true, message: '请选择收藏分组', trigger: 'change' }]">
					<el-row class="w100" :gutter="10">
						<el-col :span="20">
							<el-select-v2
								v-model="state.collectForm.KnowledgeCollectGroupId"
								:options="collectGroupOptions"
								placeholder="请选择收藏分组"
								filterable
								:props="{
									label: 'name',
									value: 'id',
								}"
								clearable
								:height="500"
							/>
						</el-col>
						<el-col :span="4">
							<el-button link type="primary" @click="addCollectGroup"> <SvgIcon name="ele-Plus" size="18px" />添加分组 </el-button>
						</el-col>
					</el-row>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.collectDialogVisible = false" class="default-button" :loading="state.loading">取 消</el-button>
					<el-button type="primary" @click="collectConfirm(collectFormRef)" :loading="state.loading">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<collect-group-add ref="collectGroupAddRef" @update="getCollectGroupOptions" />
	</div>
</template>

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

// 引入组件
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 CollectGroupAdd = defineAsyncComponent(() => import('@/views/knowledge/collect/components/Collect-group-add.vue')); // 收藏分组新增

// 定义变量内容
const state = reactive<any>({
	info: {
		knowledgeTypeName: '', // 类别
		hotspotName: '', // 热点
		keywords: '', // 关键词
		isPublic: false, // 是否公开
		creatorName: '', // 创建人
		creationTime: '', // 创建时间
		summary: '', // 摘要
		content: '', // 内容
		collect: false, // 收藏
		score: 0, // 评分
	},
	collectDialogVisible: false,
	collectForm: {
		KnowledgeCollectGroupId: null,
	},
	groupDialogVisible: false,
});
const loading = ref<Boolean>(false); // 加载状态
// 查询知识详情
const route = useRoute(); //  获取路由参数
// 新增分组
const collectGroupAddRef = ref<RefType>();
const addCollectGroup = async () => {
	collectGroupAddRef.value.openDialog();
};
// 获取收藏分组列表
const collectGroupOptions = ref<Array<any>>([]);
const getCollectGroupOptions = () => {
	getCollectList({ PageSize: 999, PageIndex: 1 }).then((res: any) => {
		collectGroupOptions.value = res.result?.items ?? [];
	});
};
// 收藏

const onCollect = (isCollect: boolean | any) => {
	if (!isCollect) {
		// 收藏
		getCollectGroupOptions();
		state.collectDialogVisible = true;
	} else {
		// 取消收藏
		ElMessageBox.confirm(`您确定要取消收藏，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				state.loading = true;
				knowledgeCollect({ knowledgeId: state.info.id, collect: !state.info?.collect?.collect })
					.then(() => {
						ElMessage.success('已取消收藏');
						mittBus.emit('clearCache', 'knowledgeCollect');
						getInfo();
						state.loading = false;
					})
					.catch(() => {
						state.loading = false;
					});
			})
			.catch(() => {});
	}
};
// 评分
const onRate = () => {
	knowledgeScore({ knowledgeId: state.info.id, score: state.info.score })
		.then(() => {
			ElMessage.success('操作成功');
			getInfo();
		})
		.catch(() => {
			getInfo();
		});
};
// 知识纠错
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) => {
	router.push({
		name: 'knowledgePreview',
		params: {
			id: row.id,
			tagsViewName: '知识查看',
		},
	});
};
// 查询详情
const getInfo = async () => {
	loading.value = true;
	if (route.params.id && route.params.id !== '0') {
		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',
	});
};
const collectFormRef = ref<RefType>();
const collectFormClose = () => {
	collectFormRef.value?.resetFields();
	collectFormRef.value?.clearValidate();
};
// 确认选择收藏分组
const collectConfirm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		knowledgeCollect({
			knowledgeId: state.info.id,
			collect: !state.info?.collect?.collect,
			knowledgeCollectGroupId: state.collectForm.KnowledgeCollectGroupId,
		})
			.then(() => {
				ElMessage.success('操作成功');
				mittBus.emit('clearCache', 'knowledgeCollect');
				getInfo();
				state.collectDialogVisible = false;
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 获取所有组织结构 和基础数据
const exportType = ref<EmptyArrayType>([]);
const getOrgListApi = async () => {
	state.loading = true;
	try {
		const { result } = await baseData();
		exportType.value = result.fileType ?? []; // 导出文件类型
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
// 详情导出
const onExportDetail = (command: string | number | object) => {
	state.loading = true;
	knowledgeDetailExport({ ids: [state.info.id], fileType: command })
		.then((res) => {
			downloadFileByStream(res);
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
const haveId = computed(()=>{
	return route.params.id && route.params.id !== '0';
})
onMounted(() => {
	getOrgListApi();
	getInfo();
});
onBeforeUnmount(() => {
	Local.remove('previewForm'); // 删除本地缓存
});
</script>
<style lang="scss" scoped>
.knowledge-preview-container {
	.relevance {
		margin-bottom: 5px;
		&:last-child {
			margin-bottom: 0;
		}
	}
}
</style>
