<template>
	<div class="knowledge-knowledge-edit-container layout-pd">
		<el-card shadow="never" style="padding: 0 50px">
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="120px" scroll-to-error>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="温馨提示">
							<span class="color-danger">
								发布知识前请仔细阅读 <el-link type="primary" @click="showStandard">【知识编写规范】</el-link>，以免知识无法通过审核，浪费您的时间！
							</span>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="知识分类" prop="knowledgeTypeId" :rules="[{ required: true, message: '请选择知识分类', trigger: 'change' }]">
							<el-cascader
								:options="state.typeData"
								filterable
								:props="{ checkStrictly: true, value: 'id', label: 'name', emitPath: false, children: 'children' }"
								placeholder="请选择上知识分类"
								clearable
								class="w100"
								v-model="state.ruleForm.knowledgeTypeId"
								ref="cascadeRef"
								@change="getKnowledgeList"
							>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="热点分类" prop="hotspotId" :rules="[{ required: true, message: '请选择热点分类', trigger: 'change' }]">
							<el-tree-select
								class="w100"
								v-model="state.ruleForm.hotspotId"
								filterable
								placeholder="请选择热点分类"
								:props="HotspotProps"
								lazy
								:load="load"
								node-key="id"
								check-strictly
								:render-after-expand="false"
								@node-click="hotSpotChange"
								ref="hotspotRef"
								:default-expanded-keys="state.hotspotExternal"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="标题" prop="title" :rules="[{ required: true, message: '请填写标题', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.title" placeholder=" 输入标题，不超过30个字" max-length="30" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="摘要" prop="summary" :rules="[{ required: false, message: '请填写摘要', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.summary" placeholder="输入摘要，不超过200个字" max-length="200" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="正文" prop="content" :rules="[{ required: true, message: '请输入正文内容', trigger: 'blur' }]">
							<editor v-model:get-html="state.ruleForm.content" :disable="state.disable" placeholder="请输入正文内容" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="关键词" prop="keywords" :rules="[{ required: false, message: '请填写关键词要', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.keywords" placeholder="请输入关键词，多个关键词用英文“,”分开" max-length="200" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="是否公开" prop="isPublic" :rules="[{ required: false, message: '请选择是否公开', trigger: 'change' }]">
							<el-radio-group v-model="state.ruleForm.isPublic">
								<el-radio :label="true">是</el-radio>
								<el-radio :label="false">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="关联知识" prop="knowledges" :rules="[{ required: false, message: '请选择关联知识', trigger: 'change' }]">
							<template #label>
								<div style="height: 34px; display: flex; align-items: center">
									关联知识
									<el-tooltip placement="top-start">
										<SvgIcon name="ele-QuestionFilled" size="18px" class="ml3" />
										<template #content> 关联其它相似或业务相关的知识，方便话务员可以查询其他相似的知识 </template>
									</el-tooltip>
								</div>
							</template>
							<el-select-v2
								v-model="state.ruleForm.knowledges"
								filterable
								clearable
								:options="state.knowledgeOptions"
								placeholder="请选择关联知识"
								class="w100"
								multiple
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="失效时间" prop="expiredTime" :rules="[{ required: false, message: '请选择失效时间', trigger: 'change' }]">
							<template #label>
								<div style="height: 34px; display: flex; align-items: center">
									失效时间
									<el-tooltip placement="top-start">
										<SvgIcon name="ele-QuestionFilled" size="18px" class="ml3" />
										<template #content> 不设置则代表永久有效；到达预设失效时间，知识将自动下架 </template>
									</el-tooltip>
								</div>
							</template>
							<el-date-picker
								v-model="state.ruleForm.expiredTime"
								type="datetime"
								placeholder="请选择失效时间"
								class="w100"
								value-format="YYYY-MM-DD[T]HH:mm:ss"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件" prop="additions" :rules="[{ required: false, message: '请选择附件', trigger: 'change' }]">
							<annex-list name="知识附件" :businessId="state.knowledgeId" classify="知识上传"/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item>
							<el-button type="primary" @click="onSubmitReview(ruleFormRef)" :loading="state.loading">提交审核</el-button>
							<el-button class="default-button" @click="onPreview" :loading="state.loading">预览 </el-button>
							<el-button @click="onSaveOnly(ruleFormRef)" class="default-button" :loading="state.loading">{{ saveText }}</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<!-- 编写规范 -->
		<knowledge-standard ref="KnowledgeStandardRef" />
		<!-- 流程组件 -->
		<knowledge-process ref="KnowledgeProcessRef" @knowledgeProcessSuccess="knowledgeProcessSuccess" />
	</div>
</template>

<script setup lang="ts" name="knowledgeEdit">
import { reactive, ref, defineAsyncComponent, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import mittBus from '/@/utils/mitt';
import { useRoute, useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { Local } from '/@/utils/storage';
import other from '/@/utils/other';
import { throttle } from '/@/utils/tools';
import {commonEnum} from '/@/utils/constants';
import { treeList } from '/@/api/knowledge/type';
import { KnowledgeDetail, KnowledgeAdd, KnowledgeGetKnowledge, KnowledgeUpdate } from '/@/api/knowledge';
import { hotSpotType } from '/@/api/business/order';

// 引入组件
const Editor = defineAsyncComponent(() => import('/@/components/Editor/index.vue'));  // 富文本编辑器
const KnowledgeProcess = defineAsyncComponent(() => import('/@/views/knowledge/component/Knowledge-process.vue'));  // 流程组件
const KnowledgeStandard = defineAsyncComponent(() => import('/@/views/knowledge/knowledge/component/Knowledge-standard-info.vue')); // 编写规范
const AnnexList = defineAsyncComponent(() => import('/@/components/AnnexList/index.vue'));  // 附件组件

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		isPublic: true, // 是否公开
    keywords: '', // 关键字
		knowledgeTypeId: '',// 知识分类
		hotspotId: '', // 热点分类
		knowledges: [], // 关联知识
	},
	typeData: [], // 知识分类
	loading: false,
	hotspotExternal: [],
	knowledgeOptions: [], //关联知识
	knowledgeId: '', // 当前id
});
const ruleFormRef = ref<any>(); // 表单ref
// 热点分类远程搜索
const HotspotProps = {
	label: 'hotSpotFullName',
	children: 'children',
	isLeaf: 'isLeaf',
};
// 热点分类懒加载
const load = async (node: any, resolve: any) => {
	if (node.isLeaf) return resolve([]);
	const res: any = await hotSpotType({ id: node.data.id ? node.data.id : '' });
	resolve(res.result);
};
// 选择热点分类
const hotSpotChange = (val: any, e: any) => {
	state.hotspotExternal = [];
	state.external = [];
	state.hotspotExternal = getParentId(e, state.external);
	state.ruleForm.hotspotSpliceName = val.hotSpotFullName;
	state.ruleForm.hotspotName = val.hotSpotFullName;
	state.ruleForm.hotspot = val.hotSpotName;
};
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.data.parentId) {
		arr.push(val.data.parentId);
		getParentId(val.parent, arr);
	}
	return arr;
};
// 展示编写规范
const KnowledgeStandardRef = ref<RefType>();
const showStandard = () => {
	KnowledgeStandardRef.value.openDialog();
};
const cascadeRef = ref<RefType>();
// 获取选择name值
const getKnowledgeList = () => {
	let currentNode = cascadeRef.value.getCheckedNodes();
	state.ruleForm.parentName = currentNode[0]?.label ?? '';
	state.ruleForm.knowledgeTypeName = currentNode[0]?.text ?? '';
};
// 提交审核
const KnowledgeProcessRef = ref<RefType>(); // 流程组件
const handleOperation = async (submitObj: any, operation: Function) => {
	await operation(submitObj).then((res: any) => {
		const id = res.result || submitObj.id;
		KnowledgeProcessRef.value.openDialog({ id, title: '创建知识', commonEnum: commonEnum.KnowledgeLocution, processType: 'addStart' });
	});
};
const route = useRoute(); // 获取路由
const router = useRouter(); // 路由跳转
const onSubmitReview = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
		const submitObj = other.deepClone(state.ruleForm);
		if (route.params.id) {
			// 更新
			submitObj.id = route.params.id;
			const operation = route.params.isDraft ? KnowledgeUpdate : KnowledgeAdd;
			handleOperation(submitObj, operation);
		} else {
			if (state.knowledgeId) {
				// 更新
				submitObj.id = state.knowledgeId;
				handleOperation(submitObj, KnowledgeUpdate);
			} else {
				//知识流程提交
				handleOperation(submitObj, KnowledgeAdd);
			}
		}
	});
};
// 流程提交成功
const knowledgeProcessSuccess = () => {
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'knowledge');
	router.push({
		path: '/knowledge',
	});
};
// 预览
const stores = useUserInfo(); // 用户信息
const { userInfos } = storeToRefs(stores);  // 用户信息
const onPreview = () => {
	state.ruleForm.creatorName = userInfos.value?.name ?? '';
	state.ruleForm.creationTime = new Date();
	Local.set('previewForm', state.ruleForm);
	router.push({
		name: 'knowledgePreview',
		params: {
			tagsViewName: '知识预览',
		},
	});
};
// 保存到草稿箱
const handleSuccess = () => {
	ElMessage.success('操作成功');
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'knowledge');
	mittBus.emit('clearCache', 'knowledgeDraft');
	router.push({
		path: '/knowledge/draft',
	});
};
const onSaveOnly = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
		const submitObj = other.deepClone(state.ruleForm);
		if (route.params.id) {
			// 更新
			submitObj.id = route.params.id;
			if (route.params.isDraft) {
				// 如果从草稿进来 // 更新
				KnowledgeUpdate(submitObj).then(handleSuccess);
			} else {
				//如果是直接从知识库编辑 新增
				KnowledgeAdd(submitObj).then(handleSuccess);
			}
		} else {
			if (state.knowledgeId) {
				// 更新
				submitObj.id = state.knowledgeId;
				KnowledgeUpdate(submitObj).then(handleSuccess);
			} else {
				// 新增
				KnowledgeAdd(submitObj).then(handleSuccess);
			}
		}
	});
}, 300);
// 知识分类
const getKnowledgeType = async () => {
	state.loading = true;
	try {
		const res: any = await Promise.all([treeList({ IsEnable: true }), KnowledgeGetKnowledge()]);
		state.typeData = res[0].result ?? [];
		state.knowledgeOptions = res[1].result ?? [];
		state.knowledgeOptions = state.knowledgeOptions.map((v: any) => ({
			label: v.title,
			value: v.id,
			...v,
		}));
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
const saveText = ref('保存为草稿');
onMounted(async () => {
	await getKnowledgeType();
	if (route.params.id) {
		const res: any = await KnowledgeDetail(route.params.id); //知识详情
		if (route.params.isDraft) {
			saveText.value = '保存';
		}
		state.ruleForm = res.result ?? {};
		if (res.result.hotspotExternal) {
			//热点分类默认展开
			state.hotspotExternal = state.ruleForm.hotspotExternal.split(',');
		}
		state.ruleForm.knowledges = state.ruleForm.knowledges ?? [];
	}
});
</script>
