<template>
	<div class="knowledge-knowledge-add-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 style="color: var(--el-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: 'child' }"
								placeholder="请选择知识分类"
								clearable
								class="w100"
								v-model="state.ruleForm.knowledgeTypeId"
								ref="cascaderRef"
								@change="getselKnowledgeList"
							>
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.child.length }}) </span>
								</template>
							</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="hotsoptChange"
								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="applies" :rules="[{ required: false, message: '请选择关联知识申请', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.applies" value-key="id" clearable filterable placeholder="请选择关联知识申请" class="w100">
								<el-option v-for="item in state.knowledgeApplyOptions" :key="item.id" :label="item.content" :value="item.id" />
							</el-select>
						</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' }]">
							<el-select v-model="state.ruleForm.knowledges" multiple value-key="id" clearable filterable placeholder="请选择关联知识" class="w100">
								<el-option v-for="item in state.knowledgeOptions" :key="item.id" :label="item.title" :value="item.id" />
							</el-select>
						</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>
										<SvgIcon name="ele-QuestionFilled" size="18px" class="ml3" />
										<template #content> 不设置则代表永久有效；到达预设失效时间，知识将自动下架 </template>
									</el-tooltip>
								</div>
							</template>
							<el-date-picker
								v-model="state.ruleForm.expiredTime"
								type="date"
								placeholder="请选择失效时间"
								class="w100"
								value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
							/>
						</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' }]">
							<el-upload
								v-model:file-list="fileList"
								class="upload-demo w100"
								action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
								multiple
								:before-remove="beforeRemove"
								:on-exceed="handleExceed"
								ref="uploadListRef"
							>
								<el-button> <SvgIcon name="ele-Upload" /> 上传附件 </el-button>
								<template #file="{ file }">
									<div class="el-upload-list__item-info">
										<a class="el-upload-list__item-name">
											<SvgIcon class="mr5" :name="fileType(checkFile(file.name))" size="16px" />
											<span class="el-upload-list__item-file-name">{{ file.name }}</span>
										</a>
									</div>
									<SvgIcon name="ele-Close" class="el-icon--close" size="14px" title="删除文件" @click="handleRemove(file)" />
								</template>
							</el-upload>
						</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">保存到草稿箱</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<!-- 编写规范 -->
		<Standard ref="standardRef" />
		<!-- 流程组件 -->
		<Process ref="processRef" @onSubmitProcess="onSubmitProcess" />
		<!-- 预览 -->
		<Preview ref="previewRef" />
	</div>
</template>

<script setup lang="ts" name="knowledgeAdd">
import { reactive, ref, defineAsyncComponent, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps, UploadUserFile, 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 { hotspottype } from '/@/api/business/order';
import { checkFile, fileType, commonEeum } from '/@/utils/tools';
import { treelist } from '/@/api/knowledge/type';
import { KnowledgeGetknowledge, KnowledgeAddapply, KnowledgeAdd } from '/@/api/knowledge';
import { adddrafts } from '/@/api/knowledge/draft';

// 引入组件
const Editor = defineAsyncComponent(() => import('/@/components/Editor/index.vue'));
const Standard = defineAsyncComponent(() => import('/@/views/knowledge/knowledge/component/StandardInfo.vue'));
const Process = defineAsyncComponent(() => import('/@/views/knowledge/component/Process.vue'));
const Preview = defineAsyncComponent(() => import('/@/views/knowledge/component/Preview.vue'));

// 定义变量内容
const ruleFormRef = ref<any>();
const state = reactive<any>({
	isShowDialog: false,
	ruleForm: {
		isPublic: true,
	},
	typeData: [], // 知识分类
	loading: false,
	knowledgeOptions: [], //关联知识
	knowledgeApplyOptions: [], //关联知识申请
});
const route = useRoute();
const router = useRouter();
const processRef = ref();
const previewRef = ref();
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);
// 热点分类远程搜索
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 hotsoptChange = (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 standardRef = ref();
const showStandard = () => {
	standardRef.value.openDialog();
};
const cascaderRef = ref();
// 获取选择name值
const getselKnowledgeList = () => {
	let currentNode = cascaderRef.value.getCheckedNodes();
	state.ruleForm.parentName = currentNode[0]?.label ?? '';
	state.ruleForm.knowledgeTypeName = currentNode[0]?.text ?? '';
};
const uploadListRef = ref();
const fileList = ref<UploadUserFile[]>([]);
// 删除确认
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile) => {
	return ElMessageBox.confirm(`确定要删除 ${uploadFile.name} ?`).then(
		() => true,
		() => false
	);
};
// 删除文件
const handleRemove = (file: any) => {
	uploadListRef.value.handleRemove(file);
};

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
	ElMessage.warning(`The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length} totally`);
};
// 提交审核
const onSubmitReview = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid) => {
		if (valid) {
			state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
			KnowledgeAdd(state.ruleForm).then((res: any) => {
				processRef.value.openDialog({ id: res.result, title: '创建知识', commonEeum: commonEeum.Seat, processType: 'addStart' });
			});
		}
	});
};
// 流程提交成功
const onSubmitProcess = () => {
	router.push({
		path: '/knowledge',
	});
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
};
// 预览
const onPreview = () => {
	state.ruleForm.creatorName = userInfos.value?.name ?? '';
	state.ruleForm.creationTime = new Date();
	previewRef.value.openDialog(state.ruleForm,true); //编辑预览
};
// 保存到草稿箱
const onSaveOnly = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid) => {
		if (valid) {
			state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
			adddrafts(state.ruleForm).then(() => {
				ElMessage.success('操作成功');
				router.push({
					path: '/knowledge/knowledge/draft',
				});
				// 关闭当前 tagsView
				mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
			});
		}
	});
};
// 知识分类
const getKnowledgeType = async () => {
	state.loading = true;
	try {
		const res: any = await Promise.all([
			treelist({IsEnable:1}),
			KnowledgeGetknowledge({ PageIndex: 1, PageSize: 99 }),
			KnowledgeAddapply({ PageIndex: 1, PageSize: 99 }),
		]);
		state.typeData = res[0].result ?? [];
		state.knowledgeOptions = res[1].result?.items ?? [];
		state.knowledgeApplyOptions = res[2].result?.items ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
onMounted(() => {
	getKnowledgeType();
});
</script>
<style scoped lang="scss">
.upload-demo {
	:deep(.el-upload-list) {
		display: flex;
		flex-wrap: wrap;
		.el-upload-list__item {
			width: calc(25% - 10px);
			border: var(--el-border);
			margin-right: 10px;
		}
	}
}
</style>
