<template>
	<div class="knowledge-knowledge-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-row :gutter="20" class="h100">
				<!-- 左侧组织树 -->
				<el-col :xs="6" :sm="6" :md="4" :lg="4" :xl="4" class="orgTree">
					<div class="h100 pr10">
						<el-tabs v-model="state.activeName" stretch>
							<el-tab-pane label="部门" name="0">
								<el-input v-model="filterOrg" placeholder="请输入部门名称" class="input-with-select mt10 mb10" clearable>
									<template #append>
										<el-button type="primary" class="btn" :loading="state.loading" @click="getList">搜索</el-button>
									</template>
								</el-input>
							</el-tab-pane>
							<el-tab-pane label="类型" name="1">
								<el-input v-model="filterType" placeholder="请输入类型名称" class="input-with-select mt10 mb10" clearable>
									<template #append>
										<el-button type="primary" class="btn" :loading="state.loading" @click="getList">搜索</el-button>
									</template>
								</el-input>
							</el-tab-pane>
							<el-tab-pane label="热点" name="2">
								<el-input v-model="filterHot" placeholder="请输入热点名称" class="input-with-select mt10 mb10" clearable>
									<template #append>
										<el-button type="primary" class="btn" :loading="state.loading" @click="getList">搜索</el-button>
									</template>
								</el-input>
							</el-tab-pane>
						</el-tabs>
						<div v-show="state.activeName === '0'" style="height: calc(100% - 100px);'">
							<el-scrollbar>
								<el-tree
									:data="state.orgData"
									highlight-current
									:expand-on-click-node="false"
									:props="{ children: 'children', label: 'orgName' }"
									@node-click="handleNodeClick"
									ref="orgRef"
									v-loading="state.loading"
									:filter-node-method="filterNode"
									default-expand-all
									node-key="id"
									style="min-width: 100%; display: inline-block"
								>
								</el-tree>
							</el-scrollbar>
						</div>
						<div v-show="state.activeName === '1'" style="height: calc(100% - 100px);'">
							<el-scrollbar>
								<el-tree
									:data="state.typeData"
									highlight-current
									:expand-on-click-node="false"
									:props="{ children: 'child', label: 'name' }"
									@node-click="handleNodeClick"
									ref="typeRef"
									v-loading="state.loading"
									:filter-node-method="filterNodeType"
									default-expand-all
									node-key="id"
									style="min-width: 100%; display: inline-block"
								>
								</el-tree>
							</el-scrollbar>
						</div>
						<div v-show="state.activeName === '2'" style="height: calc(100% - 100px);'">
							<el-scrollbar>
								<el-tree
									filterable
									highlight-current
									placeholder="请选择热点分类"
									:props="HotspotProps"
									@node-click="handleNodeClick"
									lazy
									:load="load"
									node-key="id"
									ref="hotRef"
									:filter-node-method="filterNodeHot"
									:expand-on-click-node="false"
									style="min-width: 100%; display: inline-block"
								>
									<template #default="{ data }">
										<span :title="data.hotSpotName">
											{{ data.hotSpotName }}
										</span>
									</template>
								</el-tree>
							</el-scrollbar>
						</div>
					</div>
				</el-col>
				<!-- 右侧表格 -->
				<el-col :xs="18" :sm="18" :md="20" :lg="20" :xl="20" class="rightContent">
					<el-scrollbar class="pr10" ref="rightScrollRef">
						<div class="flex-column">
							<el-tabs v-model="state.queryParams.Status" @tab-change="handleClick">
								<el-tab-pane label="全部" name=" "></el-tab-pane>
								<el-tab-pane label="已上架" name="3"></el-tab-pane>
								<el-tab-pane label="已下架" name="4"></el-tab-pane>
								<el-tab-pane label="审核中" name="1"></el-tab-pane>
								<el-tab-pane label="审核不通过" name="2"></el-tab-pane>
							</el-tabs>
							<!-- 搜索条件 -->
							<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent class="pl15 pr15 pt15">
								<el-form-item label="关键字" prop="Keyword">
									<el-input
										v-model="state.queryParams.Keyword"
										placeholder="标题/创建人/创建部门"
										clearable
										@keyup.enter="handleQuery"
										style="width: 300px"
									/>
								</el-form-item>
								<el-form-item label="创建时间" prop="crTime">
									<el-date-picker
										v-model="state.queryParams.crTime"
										type="datetimerange"
										unlink-panels
										range-separator="至"
										start-placeholder="开始日期"
										end-placeholder="结束日期"
										:shortcuts="shortcuts"
										@change="timeStartChangeCr"
										value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
									/>
								</el-form-item>
								<el-form-item label="上架时间" prop="sjTime">
									<el-date-picker
										v-model="state.queryParams.sjTime"
										type="datetimerange"
										unlink-panels
										range-separator="至"
										start-placeholder="开始日期"
										end-placeholder="结束日期"
										:shortcuts="shortcuts"
										@change="timeStartChangeSj"
										value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
									/>
								</el-form-item>
								<el-form-item label="下架时间" prop="xjTime">
									<el-date-picker
										v-model="state.queryParams.xjTime"
										type="datetimerange"
										unlink-panels
										range-separator="至"
										start-placeholder="开始日期"
										end-placeholder="结束日期"
										:shortcuts="shortcuts"
										@change="timeStartChangeXj"
										value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
									/>
								</el-form-item>
								<el-form-item>
									<el-button type="primary" @click="handleQuery" :loading="state.tableLoading">
										<SvgIcon name="ele-Search" class="mr5" />查询
									</el-button>
									<el-button @click="resetQuery(ruleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
								</el-form-item>
							</el-form>
							<div class="flex-center-between mb20">
								<p class="table-title"></p>
								<div>
									<el-button type="primary" @click="onOpenAddUser"> <SvgIcon name="ele-Plus" class="mr5" />创建知识 </el-button>
									<el-button type="primary" @click="onImportTable" :disabled="!state.multipleSelection.length">
										<SvgIcon name="iconfont icon-daochu" class="mr5" />导出
									</el-button>
								</div>
							</div>
							<!-- 表格 -->
							<el-table :data="state.tableData" v-loading="state.tableLoading" row-key="id" @selection-change="handleSelectionChange">
								<el-table-column type="selection" width="55" :reserve-selection="true" />
								<el-table-column prop="title" label="标题" show-overflow-tooltip width="120"></el-table-column>
								<el-table-column prop="knowledgeTypeName" label="类型" show-overflow-tooltip width="200"></el-table-column>
								<el-table-column prop="hotspotName" label="热点" show-overflow-tooltip width="200"></el-table-column>
								<el-table-column prop="creationName" label="创建人" show-overflow-tooltip width="120"></el-table-column>
								<el-table-column prop="creationBMName" label="创建部门" show-overflow-tooltip width="150"></el-table-column>
								<el-table-column prop="creationTime" label="创建时间" show-overflow-tooltip width="170">
									<template #default="scope">
										<span>{{ formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
									</template>
								</el-table-column>
								<el-table-column prop="pageView" label="阅读次数" show-overflow-tooltip></el-table-column>
								<el-table-column prop="onShelfTime" label="上架时间" show-overflow-tooltip width="170">
									<template #default="scope">
										<span>{{ formatDate(scope.row.onShelfTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
									</template>
								</el-table-column>
								<el-table-column prop="offShelfTime" label="下架时间" show-overflow-tooltip width="170">
									<template #default="scope">
										<span>{{ formatDate(scope.row.offShelfTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
									</template>
								</el-table-column>
								<el-table-column prop="lastModificationTime" label="更新时间" show-overflow-tooltip width="170">
									<template #default="scope">
										<span>{{ formatDate(scope.row.lastModificationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
									</template>
								</el-table-column>
								<el-table-column prop="status" label="状态" show-overflow-tooltip width="100">
									<template #default="{ row }">
										<span v-if="row.status === 1" style="color: var(--el-color-primary)">审核中</span>
										<span v-if="row.status === 2" style="color: var(--el-color-danger)">审核不通过</span>
										<span v-if="row.status === 3" style="color: var(--el-color-success)">已上架</span>
										<span v-if="row.status === 4" style="color: var(--el-color-info)">已下架</span>
									</template>
								</el-table-column>
								<el-table-column label="操作" width="300" fixed="right" align="center">
									<template #default="{ row }">
										<el-button text type="primary" @click="onPreview(row)" title="预览" v-if="[1, 2, 3, 4].includes(row.status)"> 预览 </el-button>
										<el-button text type="primary" @click="onEdit(row)" title="编辑" v-if="[2, 3, 4].includes(row.status)"> 编辑 </el-button>
										<el-button text type="primary" @click="onOffshelf(row)" title="下架" v-if="[3].includes(row.status)"> 下架 </el-button>
										<el-button text type="primary" @click="ontheshelf(row)" title="上架" v-if="[4].includes(row.status)"> 上架 </el-button>
										<el-button text type="primary" @click="onRecord(row)" title="查看审核记录" v-if="[1, 2].includes(row.status)">
											查看审核记录
										</el-button>
										<el-button text type="danger" @click="onRecall(row)" title="撤回" v-if="[1].includes(row.status)"> 撤回 </el-button>
										<el-button text type="danger" @click="onRowDel(row)" title="删除" v-if="[2, 3, 4].includes(row.status)"> 删除 </el-button>
										<el-button text type="primary" @click="onRenew(row)" title="发起更新申请" v-if="[3, 4].includes(row.status)">
											发起更新申请
										</el-button>
									</template>
								</el-table-column>
								<template #empty>
									<Empty />
								</template>
							</el-table>
							<!-- 分页 -->
							<pagination
								:total="state.total"
								v-model:page="state.queryParams.PageIndex"
								v-model:limit="state.queryParams.PageSize"
								@pagination="getList"
							/>
						</div>
					</el-scrollbar>
				</el-col>
			</el-row>
		</div>
		<!-- 预览 -->
		<Preview ref="previewRef" />
		<!-- 审核记录 -->
		<ProcessRecord ref="processRecordRef" />
		<!-- 流程组件 -->
		<Process ref="processRef" @onSubmitProcess="onSubmitProcess" />
	</div>
</template>

<script lang="ts" setup name="knowledge">
import { ref, reactive, onMounted, watch, onActivated, defineAsyncComponent } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import table2excel from 'js-table2excel';
import { formatDate } from '/@/utils/formatTime';
import { throttle, commonEeum } from '/@/utils/tools';
import { KnowledgePaged, KnowledgeRevoke, KnowledgeOffshelf, KnowledgeOntheshelf } from '/@/api/knowledge';
import { getOrgList } from '/@/api/system/organize';
import { treelist } from '/@/api/knowledge/type';
import { hotspottype } from '/@/api/business/order';

// 引入组件
const Preview = defineAsyncComponent(() => import('/@/views/knowledge/component/Preview.vue'));
const ProcessRecord = defineAsyncComponent(() => import('/@/views/knowledge/component/ProcessRecord.vue'));
const Process = defineAsyncComponent(() => import('/@/views/knowledge/component/Process.vue'));
const shortcuts = [
	{
		text: '近一周',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			return [start, end];
		},
	},
	{
		text: '近一个月',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			return [start, end];
		},
	},
	{
		text: '近三个月',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			return [start, end];
		},
	},
];
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1,
		PageSize: 10,
		Keyword: '',
		Status: ' ',
	},
	activeName: '0',
	tableData: [],
	total: 0,
	loading: false,
	tableLoading: false,
	multipleSelection: [],
	orgData: [],
	typeData: [],
	options: [],
});
const router = useRouter();
const ruleFormRef = ref<FormInstance>(); //表单ref
const rightScrollRef = ref();
const previewRef = ref();
const processRecordRef = ref();
const processRef = 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 filterOrg = ref('');
const orgRef = ref();
watch(filterOrg, (val) => {
	orgRef.value!.filter(val);
});
const filterNode = (value: string, data: any) => {
	if (!value) return true;
	return data.orgName.includes(value);
};
const filterType = ref('');
const typeRef = ref();
watch(filterType, (val) => {
	typeRef.value!.filter(val);
});
const filterNodeType = (value: string, data: any) => {
	if (!value) return true;
	return data.name.includes(value);
};
const filterHot = ref('');
const hotRef = ref();
watch(filterHot, (val) => {
	hotRef.value!.filter(val);
});
const filterNodeHot = (value: string, data: any) => {
	if (!value) return true;
	return data.hotSpotName.includes(value);
};

// 切换tab 查询列表
const handleClick = () => {
	getList();
};
// 创建时间
const timeStartChangeCr = (val: string[]) => {
	if (val) {
		state.queryParams.CreationStartTime = val[0];
		state.queryParams.CreationEndTime = val[1];
		getList();
	} else {
		state.queryParams.CreationStartTime = '';
		state.queryParams.CreationEndTime = '';
		getList();
	}
};
// 上架时间
const timeStartChangeSj = (val: string[]) => {
	if (val) {
		state.queryParams.StartOnShelfTime = val[0];
		state.queryParams.EndOnShelfTime = val[1];
		getList();
	} else {
		state.queryParams.StartOnShelfTime = '';
		state.queryParams.EndOnShelfTime = '';
		getList();
	}
};
// 下架时间
const timeStartChangeXj = (val: string[]) => {
	if (val) {
		state.queryParams.StartOffShelfTime = val[0];
		state.queryParams.EndOffShelfTime = val[1];
		getList();
	} else {
		state.queryParams.StartOffShelfTime = '';
		state.queryParams.EndOffShelfTime = '';
		getList();
	}
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	state.queryParams.PageIndex = 1;
	getList();
}, 1000);
// 获取所有组织结构
const getOrgListApi = async () => {
	state.loading = true;
	try {
		const res: any = await Promise.all([getOrgList(), treelist({IsEnable:1})]);
		state.orgData = res[0].result ?? [];
		state.typeData = res[1].result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
/** 获取知识列表 */
const getList = () => {
	state.tableLoading = true;
	let request = JSON.parse(JSON.stringify(state.queryParams));
	Reflect.deleteProperty(request, 'crTime'); // 删除无用的参数
	Reflect.deleteProperty(request, 'sjTime'); // 删除无用的参数
	Reflect.deleteProperty(request, 'xjTime'); // 删除无用的参数
	KnowledgePaged(request)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.total;
			rightScrollRef.value.setScrollTop(0); //滚动倒顶部
			state.tableLoading = false;
		})
		.catch(() => {
			state.tableLoading = false;
		});
};
// 点击节点
const handleNodeClick = (data: any) => {
	switch (state.activeName) {
		case '0':
			state.queryParams.CreateOrgId = data.orgCode;
			break;
		case '1':
			state.queryParams.KnowledgeTypeId = data.id;
			break;
		case '2':
			state.queryParams.HotspotId = data.id;
			break;

		default:
			break;
	}
	getList();
};
// 表格多选
const handleSelectionChange = (val: any) => {
	state.multipleSelection = val;
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.CreateOrgId = '';
	state.queryParams.HotspotId = '';
	state.queryParams.KnowledgeTypeId = '';
	state.queryParams.CreationStartTime = '';
	state.queryParams.CreationEndTime = '';
	state.queryParams.StartOffShelfTime = '';
	state.queryParams.EndOffShelfTime = '';
	state.queryParams.StartOnShelfTime = '';
	state.queryParams.EndOnShelfTime = '';
	typeRef.value?.setCurrentKey(null);
	orgRef.value?.setCurrentKey(null);
	hotRef.value?.setCurrentKey(null);
	handleQuery();
}, 1000);
// 创建知识
const onOpenAddUser = () => {
	router.push({
		path: '/knowledge/add',
	});
};
// 修改知识
const onEdit = (row: any) => {
	router.push({
		name: 'knowledgeEdit',
		params: {
			id: row.id,
			tagsViewName: '编辑知识',
		},
	});
};
// 预览
const onPreview = (row: any) => {
	previewRef.value.openDialog(row);
};
// 查看审核记录
const onRecord = (row: any) => {
	processRecordRef.value.openDialog(row);
};
// 发起更新 修改申请
const onRenew = (row: any) => {
	processRef.value.openDialog({ id: row.id, title: '更新知识', commonEeum: commonEeum.Seat, processType: 'editStart' });
};
// 发起更新成功
const onSubmitProcess = () => {
	handleQuery();
};
// 下架
const onOffshelf = (row: any) => {
	ElMessageBox.confirm(`是否确定要下架？知识下架后，将不会被检索到！`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeOffshelf(row.id).then(() => {
				ElMessage.success('操作成功');
				handleQuery();
				state.queryParams.OrgCode = '';
				getOrgListApi();
			});
		})
		.catch(() => {});
};
// 上架
const ontheshelf = (row: any) => {
	ElMessageBox.confirm(`是否确定要上架？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeOntheshelf(row.id).then(() => {
				ElMessage.success('操作成功');
				handleQuery();
				state.queryParams.OrgCode = '';
				getOrgListApi();
			});
		})
		.catch(() => {});
	// ElMessageBox.confirm(`知识已过有效期，无法直接上架，请到【编辑】页面，修改有效期。`, '提示', {
	// 	confirmButtonText: '去编辑',
	// 	cancelButtonText: '取消',
	// 	type: 'warning',
	// 	draggable: true,
	// 	cancelButtonClass: 'default-button',
	// })
	// 	.then(() => {
	// 		restPwd(row.id).then(() => {
	// 			ElMessage.success('操作成功');
	// 			handleQuery();
	// 			state.queryParams.OrgCode = '';
	// 			getOrgListApi();
	// 		});
	// 	})
	// 	.catch(() => {});
};

// 撤回
const onRecall = (row: any) => {
	ElMessageBox.confirm(`是否确定要撤回？撤回成功后请到【我的草稿箱】中进行查看和管理`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeRevoke(row.workflowId).then(() => {
				ElMessage.success('操作成功');
				handleQuery();
				state.queryParams.OrgCode = '';
				getOrgListApi();
			});
		})
		.catch(() => {});
};
// 删除知识
const onRowDel = (row: any) => {
	processRef.value.openDialog({ id: row.id, title: '删除知识', commonEeum: commonEeum.Seat, processType: 'deleteStart' });
};
// 导出表格
const onImportTable = () => {
	const tabeHeader = [
		{ key: 'name', colWidth: '', title: '姓名', type: 'text', isCheck: true },
		{ key: 'userName', colWidth: '', title: '账号', type: 'text', isCheck: true },
		{ key: 'orgName', colWidth: '', title: '所属部门', type: 'text', isCheck: true },
		{ key: 'roles', colWidth: '', title: '角色', type: 'text', isCheck: true },
		{ key: 'phoneNo', colWidth: '', title: '电话号码', type: 'text', isCheck: true },
		{ key: 'staffNo', colWidth: '', title: '工号', type: 'text', isCheck: true },
		{ key: 'defaultTelNo', colWidth: '', title: '默认分机', type: 'text', isCheck: true },
		{ key: 'creationTime', colWidth: '', title: '更新时间', type: 'text', isCheck: true },
	];
	table2excel(tabeHeader, state.multipleSelection, `用户信息 ${formatDate(new Date(), 'YYYY-mm-dd HH-MM')}`);
};
onMounted(() => {
	getList();
	getOrgListApi();
});
onActivated(() => {
	getList();
});
</script>
<style lang="scss" scoped>
.knowledge-knowledge-container {
	.orgTree {
		border-right: 1px solid var(--el-border-color);
		height: 100%;
	}

	.rightContent {
		height: 100%;
		.flex-column {
			display: flex;
			flex-direction: column;
			height: 100%;
			.el-table {
				flex: 1;
			}
		}
	}

	:deep(.el-tree-node__content) {
		height: 40px;
	}
}
</style>
