<template>
	<div class="plan-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="12" :lg="12" :xl="8">
						<el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="预案分类">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="预案分类" prop="planTypeId" :rules="[{ required: true, message: '请选择预案分类', trigger: 'change' }]">
									<VTreeDrop
										:data="state.typeData"
										checkable
										keyField="id"
										titleField="name"
										v-model="state.ruleForm.planTypeId"
										@checked-change="selectType"
										:dropHeight="400"
										dropPlaceholder="预案分类"
										dropdownWidthFixed
										clearable
										searchPlaceholder="预案分类名称"
										checkedButtonText="查看已选"
										:show-footer="false"
										:cascade="false"
									>
									</VTreeDrop>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
						<el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item>
									<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-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<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"
										:disabled-date="disabledDate"
										popper-class="no-atTheMoment"
									/>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
						<el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="热点分类">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="热点分类" prop="hotspotId" :rules="[{ required: false, message: '请选择热点分类', trigger: 'change' }]">
									<hot-spot-select v-model="state.ruleForm.hotspotId" v-model:externalArr="state.hotspotExternal" @change="chooseHotSpot" clearable />
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="预案标题">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="预案标题" prop="title" :rules="[{ required: true, validator: validatePassTitle, trigger: 'blur' }]">
									<el-input v-model="state.ruleForm.title" placeholder="请填写预案标题" clearable @blur="isRepeat('title')"></el-input>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="预案内容">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="预案内容" prop="content" :rules="[{ required: true, validator: validatePassContent, trigger: 'blur' }]">
									<editor
										v-model:get-html="state.ruleForm.content"
										:disable="state.disable"
										placeholder="请填写预案内容"
										:defaultContent="defaultContent"
										ref="editorRef"
										@blur="isRepeat('content')"
									/>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="附件">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="附件" prop="files" :rules="[{ required: false, message: '请选择附件', trigger: 'change' }]">
									<annex-list
										name="预案附件"
										v-model="state.ruleForm.files"
										v-model:format="filesFormat"
										:businessId="state.ruleForm.id"
										classify="预案上传"
									/>
								</el-form-item>
							</template>
						</el-skeleton>
					</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-button class="default-button" @click="onCancel" :loading="state.loading">取消 </el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<!-- 删除或者更新提交审核 -->
		<edit-submit-audit ref="editSubmitAuditRef" @updateList="processSuccess" />
	</div>
</template>

<script setup lang="ts" name="planEdit">
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, transformFile } from '@/utils/tools';
import { disabledDate } from '@/utils/constants';
import { VTreeDrop } from '@wsfe/vue-tree';
import { planTreeList } from '@/api/plan/type';
import { addPlanDraft, addPlanDraftAudit, editPlanDraft, planDetail, planRepeat } from '@/api/plan';
// 引入组件
const Editor = defineAsyncComponent(() => import('@/components/Editor/index.vue')); // 富文本编辑器
const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件组件
const EditSubmitAudit = defineAsyncComponent(() => import('@/views/plan/index/components/Edit-submit-audit.vue')); // 删除或者更新 提交审核
const HotSpotSelect = defineAsyncComponent(() => import('@/components/Hotspot/index.vue')); // 选择热点

const stores = useUserInfo(); // 用户信息
const { userInfos } = storeToRefs(stores); // 用户信息

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		attribution: '中心预案库', // 预案归属
		isPublic: true, // 是否公开
		files: [], // 附件
		content: '', // 内容
		title: null, // 标题
	},
	typeData: [], // 分类
	loading: false,
	hotspotExternal: [],
});
const ruleFormRef = ref<any>(); // 表单ref
const validatePassTitle = (rule: any, value: any, callback: any) => {
	if (value === '' || value === null) {
		callback(new Error('请填写案例标题'));
	} else if (Repeat.value) {
		callback(new Error('有相似标题，请检查！'));
	} else {
		callback();
	}
};
const validatePassContent = (rule: any, value: any, callback: any) => {
	if (value === '' || value === null || value === '<p style="line-height: 2;"><br></p>') {
		callback(new Error('请填写案例内容'));
	} else if (Repeat.value) {
		callback(new Error('有相似内容，请检查！'));
	} else {
		callback();
	}
};
// 校验标题/摘要/内容是否重复  根据输入标题检测出关键词填入
const Repeat = ref<boolean>(false);
const isRepeat = (type: string) => {
	if (state.ruleForm[type]) {
		planRepeat({ [type]: state.ruleForm[type], id: state.ruleForm.id })
			.then((res: any) => {
				Repeat.value = res.result;
				ruleFormRef.value.validateField(type);
			})
			.catch(() => {
				state.ruleForm[type] = '';
			});
	}
};
// 默认配置
const defaultContent = ref([
	{
		type: 'paragraph',
		children: [{ text: '', fontFamily: '仿宋', fontSize: '20px' }],
		lineHeight: '2',
	},
]);
const selectType = (value: any) => {
	state.ruleForm.planTypes = value.map((item: any) => {
		return { planTypeName: item.name, planTypeId: item.id, planTypeSpliceName: item.spliceName };
  //   return { name: item.name, id: item.id, spliceName: item.spliceName };
	});
	state.ruleForm.planTypeId = value.map((item: any) => item.id);
	ruleFormRef.value.validateField('planTypeId');
};
// 提交审核
const route = useRoute(); // 获取路由
const router = useRouter(); // 路由跳转
const filesFormat = ref<EmptyArrayType>([]); // 附件列表格式化
const editSubmitAuditRef = ref<RefType>(); // 删除或者更新 提交审核
const onSubmitReview = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.ruleForm.files = filesFormat.value;
		const submitObj = other.deepClone(state.ruleForm);
		Reflect.deleteProperty(submitObj, 'creationTime');
		//如果已经有ID 说明是已经提交过的数据  更新审核
		if (route.params.id) {
			editSubmitAuditRef.value.openDialog(submitObj, 'update');
		} else {
			state.loading = true;
			addPlanDraftAudit(submitObj)
				.then(() => {
					ElMessage.success('新增预案审核提交成功');
					processSuccess();
				})
				.catch(() => {
					state.loading = false;
				});
			state.loading = false;
		}
	});
};
// 流程提交成功
const processSuccess = () => {
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'planManage');
	router.push({
		path: '/plan/index',
	});
};
// 预览
const onPreview = () => {
	if (route.params.id) {
		/* empty */
	} else {
		state.ruleForm.creatorName = userInfos.value?.name ?? '';
		state.ruleForm.creationTime = new Date();
		state.ruleForm.creatorOrgName = userInfos.value?.orgName ?? '';
	}
	Local.set('planPreviewForm', state.ruleForm);
	router.push({
		name: 'planPreview',
		params: {
			tagsViewName: '案例预览',
			id: '0',
		},
	});
};
// 选择热点分类
const chooseHotSpot = (val: any, node: any, externalArr: any) => {
	if (val) {
		state.ruleForm.hotspotSpliceName = val.hotSpotFullName; // 热点分类拼接名称
		state.ruleForm.hotspotName = val.hotSpotName; // 热点分类名称
		state.ruleForm.hotspotCode = val.provinceCode; // 热点分类code
		state.ruleForm.hotspotExternal = externalArr.join(',') ?? ''; // 热点分类默认展开项
	} else {
		state.ruleForm.hotspotSpliceName = null;
		state.ruleForm.hotspotName = null;
		state.ruleForm.hotspotCode = null;
		state.ruleForm.hotspotExternal = null;
	}
};
// 保存到草稿箱
const onSaveOnly = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		state.ruleForm.files = filesFormat.value;
		const submitObj = other.deepClone(state.ruleForm);
		Reflect.deleteProperty(submitObj, 'creationTime');
		if (route.params.id) {
			// 更新
			editPlanDraft(submitObj)
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		} else {
			// 新增
			addPlanDraft(submitObj)
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		}
	});
}, 300);
// 取消
const onCancel = () => {
	state.loading = true;
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'planManage');
	router.push({
		path: '/plan/index',
	});
	state.loading = false;
};
const handleSuccess = () => {
	state.loading = false;
	ElMessage.success('操作成功');
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'planManage');
	router.push({
		path: '/plan/index',
	});
};
// 获取分类
const getType = async () => {
	state.loading = true;
	try {
		const [typeDataRes] = await Promise.all([planTreeList({ IsEnable: true })]);
		state.typeData = typeDataRes.result ?? [];
		state.loading = false;
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
const editorRef = ref<RefType>();
const getDetail = async () => {
	if (route.params.id) {
		const res: any = await planDetail({ id: route.params.id }); //详情
		state.ruleForm = res.result ?? {};
		if (state.ruleForm.hotspotExternal) {
			//热点分类默认展开
			state.hotspotExternal = state.ruleForm.hotspotExternal.split(',');
		}
		state.ruleForm.files = transformFile(state.ruleForm.files);
		state.ruleForm.planTypeId = state.ruleForm.planTypes?.map((item: any) => item.planTypeId);
	}
};
onMounted(async () => {
	await getType();
	await getDetail();
});
</script>
<style lang="scss">
.vtree-tree-drop__wrapper {
	width: 100%;
}
</style>
