<template>
	<div class="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="12" :lg="12" :xl="8">
						<el-form-item label="知识归属" prop="attribution" :rules="[{ required: true, message: '请选择知识归属', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.attribution" placeholder="请选择知识归属" class="w100">
								<el-option label="中心知识库" value="中心知识库" />
								<el-option label="部门知识库" value="部门知识库" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
						<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="12" :lg="12" :xl="8">
						<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="12" :lg="12" :xl="8">
						<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="12" :lg="12" :xl="8">
						<el-form-item label="来源部门" prop="sourceOrganizeId" :rules="[{ required: true, message: '请选择来源部门', trigger: 'change' }]">
							<el-cascader
								:options="orgsOptions"
								filterable
								:props="{ value: 'id', label: 'name', emitPath: false, checkStrictly: true }"
								placeholder="请选择来源部门"
								class="w100"
								v-model="state.ruleForm.sourceOrganizeId"
								ref="orgRef"
								@change="selectOrg"
							>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
						<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, validator: validatePass, trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.title" placeholder="请输入知识标题" clearable @blur="isRepeat"></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="请输入知识摘要" 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="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
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="5"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="关键词" prop="keywordsName" :rules="[{ required: false, message: '请添加关键词', trigger: 'change' }]">
							<el-input v-model="state.ruleForm.keywordsName" readonly placeholder="请添加关键词" max-length="200" clearable>
                <template #append>
                  <el-button @click="addKeywords">添加</el-button>
                </template>
              </el-input>
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="知识库模板" prop="template" :rules="[{ required: false, message: '请选择知识库模板', trigger: 'change' }]">
              <el-select v-model="state.ruleForm.template" placeholder="请选择知识库模板" class="w100" @change="selectTemplate" clearable>
                <el-option :label="item.label" :value="item.value" v-for="item in templateList" :key="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="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="additions" :rules="[{ required: false, message: '请选择附件', trigger: 'change' }]">
							<annex-list name="知识附件" :businessId="state.ruleForm.id" 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" />
		<!-- 流程审批 -->
		<process-audit ref="processAuditRef" @orderProcessSuccess="knowledgeProcessSuccess" />
    <!-- 关键词 -->
    <knowledge-keywords ref="knowledgeKeywordsRef" @selectKeyword="selectKeyword"/>
	</div>
</template>

<script setup lang="ts" name="knowledgeEdit">
import {defineAsyncComponent, onMounted, reactive, ref} from 'vue';
import type {FormInstance} from 'element-plus';
import {ElMessage} 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 {treeList} from '/@/api/knowledge/type';
import {KnowledgeAdd, KnowledgeGetKnowledge, KnowledgeInfo, knowledgeTitle, KnowledgeUpdate} from '/@/api/knowledge';
import {hotSpotType} from '/@/api/business/order';
import {getCanUseOrg} from '/@/api/system/user';
import {templateList} from '/@/views/knowledge/index/template';
// 引入组件
const Editor = defineAsyncComponent(() => import('/@/components/Editor/index.vue')); // 富文本编辑器
const ProcessAudit = defineAsyncComponent(() => import('/@/components/ProcessAudit/index.vue')); // 流程审批
const KnowledgeStandard = defineAsyncComponent(() => import('/@/views/knowledge/component/Knowledge-standard-info.vue')); // 编写规范
const AnnexList = defineAsyncComponent(() => import('/@/components/AnnexList/index.vue')); // 附件组件
const KnowledgeKeywords = defineAsyncComponent(() => import('/@/views/knowledge/component/Knowledge-keywords.vue')); // 关键词组件

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		attribution: '', // 知识归属
		isPublic: true, // 是否公开
		keywords: [], // 关键字
    keywordsName:'', // 关键字名称
		knowledgeTypeId: '', // 知识分类
		hotspotId: '', // 热点分类
		knowledges: [], // 关联知识
	},
	typeData: [], // 知识分类
	loading: false,
	hotspotExternal: [],
	knowledgeOptions: [], //关联知识
});
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;
};
// 选择部门
const orgRef = ref<RefType>();
const selectOrg = () => {
	state.ruleForm.sourceOrganizeName = orgRef.value.getCheckedNodes()[0]?.label ?? '';
};
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.data.parentId) {
		arr.push(val.data.parentId);
		getParentId(val.parent, arr);
	}
	return arr;
};
const validatePass= (rule: any, value: any, callback: any)=>{
  if (value === '' || value === null) {
    callback(new Error('请输入知识标题'))
  } else if (Repeat.value) {
    callback(new Error("当前知识标题存在重复标题"))
  } else {
    callback()
  }
}
// 校验标题是否重复
const Repeat = ref<boolean>(false);
const isRepeat = ()=>{
  if(state.ruleForm.title){
    const id = state.ruleForm.id ? state.ruleForm.id : '';
    knowledgeTitle({Id:id,Title:state.ruleForm.title})
      .then((res:any)=>{
        Repeat.value = res.result;
        ruleFormRef.value.validateField('title');
      })
      .catch(()=>{
        state.ruleForm.title = '';
      })
  }
}
// 展示编写规范
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 knowledgeKeywordsRef = ref<RefType>();
const addKeywords = ()=>{
  knowledgeKeywordsRef.value.openDialog(state.ruleForm.keywords);
}
// 选择关键词
const selectKeyword = (val:any)=>{
  state.ruleForm.keywordsName = val.name;
  state.ruleForm.keywords = val.ids;
}
// 选择知识库模板
const selectTemplate = (val:any)=>{
  state.ruleForm.content = val;
}
// 提交审核
const processAuditRef = ref<RefType>(); // 流程组件
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);
		Reflect.deleteProperty(submitObj, 'creationTime');
    if (route.params.id) {
      //如果已经有ID 说明是已经提交过的数据 提交更新流程
      const params = {
        id: submitObj.workflowId ?? '',
        processType: '更新知识',
        extra: {
          dialogTitle: '更新知识',
          inputPlaceholder: '办理意见',
          annexName: '知识附件',
        },
        orderDetail: submitObj,
      };
      processAuditRef.value.openDialog(params);
    } else {
      // 新增
      const params = {
        id: '',
        processType: '新增知识',
        extra: {
          dialogTitle: '新增知识',
          inputPlaceholder: '办理意见',
          annexName: '知识附件',
        },
        orderDetail: submitObj,
      };
      processAuditRef.value.openDialog(params);
    }
	});
};
// 流程提交成功
const knowledgeProcessSuccess = () => {
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'knowledgeManage');
	router.push({
		path: '/knowledge/index',
	});
};
// 预览
const stores = useUserInfo(); // 用户信息
const { userInfos } = storeToRefs(stores); // 用户信息
const onPreview = () => {
	if (route.params.id) {
	} else {
		state.ruleForm.creatorName = userInfos.value?.name ?? '';
		state.ruleForm.creationTime = new Date();
		state.ruleForm.creatorOrgName = userInfos.value?.orgName ?? '';
	}
	Local.set('previewForm', state.ruleForm);
	router.push({
		name: 'knowledgePreview',
		params: {
			tagsViewName: '知识预览',
		},
	});
};
// 保存到草稿箱
const onSaveOnly = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
		const submitObj = other.deepClone(state.ruleForm);
		Reflect.deleteProperty(submitObj, 'creationTime');
		if (submitObj.workflowId) {
			// 如果是已经提交过的数据 直接新增草稿
			KnowledgeAdd({ data: submitObj })
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		} else {
			if (route.params.id) {
				// 更新
				KnowledgeUpdate({ data: submitObj })
					.then(handleSuccess)
					.catch(() => {
						state.loading = false;
					});
			} else {
				// 新增
				KnowledgeAdd({ data: submitObj })
					.then(handleSuccess)
					.catch(() => {
						state.loading = false;
					});
			}
		}
	});
}, 300);
const handleSuccess = () => {
	state.loading = false;
	ElMessage.success('操作成功');
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'knowledgeManage');
	router.push({
		path: '/knowledge/index',
	});
};
const orgsOptions = ref<EmptyArrayType>([]); // 来源单位
// 知识分类
const getKnowledgeType = async () => {
	state.loading = true;
	try {
		const [typeDataRes, knowledgeOptionsRes, orgsOptionsRes] = await Promise.all([
			treeList({ IsEnable: true }),
			KnowledgeGetKnowledge(),
			getCanUseOrg(),
		]);
		state.typeData = typeDataRes.result ?? [];
		state.knowledgeOptions = knowledgeOptionsRes.result ?? [];
		state.knowledgeOptions = state.knowledgeOptions.map((v: any) => ({
			label: v.title,
			value: v.id,
			...v,
		}));
		orgsOptions.value = orgsOptionsRes.result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
const saveText = ref('保存为草稿');
const getDetail = async () => {
	if (route.params.id) {
		const res: any = await KnowledgeInfo(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 ?? [];
    if(state.ruleForm.keywordsDto && state.ruleForm.keywordsDto.length){
      state.ruleForm.keywordsName = state.ruleForm.keywordsDto.map((item: any) => item.tag).join(',');
    }
	}
};
onMounted(() => {
	getKnowledgeType();
	getDetail();
});
</script>
