<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="6" :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> </el-input>
							</el-tab-pane>
							<el-tab-pane label="类型" name="1">
								<el-input v-model="filterType" placeholder="请输入类型名称" class="input-with-select mt10 mb10" clearable> </el-input>
							</el-tab-pane>
							<el-tab-pane label="热点" name="2">
								<el-input v-model="filterHot" placeholder="请输入热点名称" class="input-with-select mt10 mb10" clearable> </el-input>
							</el-tab-pane>
						</el-tabs>
						<div style="height: calc(100% - 100px);'">
							<el-scrollbar>
								<el-tree
                  v-show="state.activeName === '0'"
									: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"
									node-key="orgCode"
                  :style="state.activeName === '0'? 'display:inline-block' : 'display:none'"
									:default-expanded-keys="state.defaultExpandedOrgKeys"
								>
								</el-tree>
                <el-tree
                    :data="state.knowledgeOptions"
                    highlight-current
                    :expand-on-click-node="false"
                    :props="{ children: 'children', label: 'name' }"
                    @node-click="handleNodeClick"
                    ref="typeRef"
                    v-loading="state.loading"
                    :filter-node-method="filterNodeType"
                    node-key="id"
                    :style="state.activeName === '1'? 'display:inline-block' : 'display:none'"
                    :default-expanded-keys="state.defaultExpandedTypeKeys"
                >
                </el-tree>
                <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="state.activeName === '2'? 'display:inline-block' : 'display:none'"
                >
                  <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="18" :lg="20" :xl="20" class="rightContent">
					<el-scrollbar class="pr10 scrollbar__view">
						<el-tabs v-model="state.queryParams.Status" @tab-change="handleClick">
							<el-tab-pane label="全部" name=" "></el-tab-pane>
							<el-tab-pane :label="v.value" :name="v.key" v-for="(v, i) in state.statusOptions" :key="i"></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"
								/>
							</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"
								/>
							</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"
								/>
							</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" :loading="state.tableLoading">
									<SvgIcon name="ele-Refresh" class="mr5" />重置
								</el-button>
							</el-form-item>
						</el-form>
						<div class="mb20">
							<el-button type="primary" @click="onOpenAddUser" v-auth="'knowledge:add'"> <SvgIcon name="ele-Plus" class="mr5" />创建知识 </el-button>
						</div>
						<!-- 表格 -->
						<el-table :data="state.tableData" v-loading="state.tableLoading" row-key="id">
							<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="{ row }">
									<span>{{ formatDate(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="{ row }">
									<span>{{ formatDate(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="{ row }">
									<span>{{ formatDate(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="{ row }">
									<span>{{ formatDate(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" class="color-primary">{{ row.statusName }}</span>
									<span v-if="row.status === 2" class="color-danger">{{ row.statusName }}</span>
									<span v-if="row.status === 3" class="color-success">{{ row.statusName }}</span>
									<span v-if="row.status === 4" class="color-info">{{ row.statusName }}</span>
								</template>
							</el-table-column>
							<el-table-column label="操作" width="300" fixed="right" align="center">
								<template #default="{ row }">
									<el-button
										link
										type="info"
										@click="onPreview(row)"
										title="预览"
										v-if="[1, 2, 3, 4].includes(row.status)"
										v-auth="'knowledge:preview'"
									>
										预览
									</el-button>
									<el-button link type="primary" @click="onEdit(row)" title="编辑" v-if="[2, 3, 4].includes(row.status)" v-auth="'knowledge:edit'">
										编辑
									</el-button>
									<el-button
										link
										type="warning"
										@click="offShelfFn(row)"
										title="下架"
										v-if="[3].includes(row.status)"
										v-auth="'knowledge:undercarriage'"
									>
										下架
									</el-button>
									<el-button
										link
										type="success"
										@click="groundingFn(row)"
										title="上架"
										v-if="[4].includes(row.status)"
										v-auth="'knowledge:grounding'"
									>
										上架
									</el-button>
									<el-button
										link
										type="primary"
										@click="onRecord(row)"
										title="查看审核记录"
										v-if="[1, 2].includes(row.status)"
										v-auth="'system:workflow:record'"
									>
										查看审核记录
									</el-button>
									<el-button link type="danger" @click="onRecall(row)" title="撤回" v-if="[1].includes(row.status)" v-auth="'system:workflow:stop'">
										撤回
									</el-button>
									<el-button link type="danger" @click="onRowDel(row)" title="删除" v-if="[2, 3, 4].includes(row.status)" v-auth="'knowledge:delete'">
										删除
									</el-button>
									<el-button
										link
										type="primary"
										@click="onRenew(row)"
										title="发起更新申请"
										v-if="[3, 4].includes(row.status)"
										v-auth="'knowledge:myApply:add'"
									>
										发起更新申请
									</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="queryList"
						/>
						<el-backtop target=".scrollbar__view > div" />
					</el-scrollbar>
				</el-col>
			</el-row>
		</div>
		<!-- 审核记录 -->
		<audit-record ref="auditRecordRef" />
		<!-- 流程组件 -->
		<knowledge-process ref="knowledgeProcessRef" @knowledgeProcessSuccess="knowledgeProcessSuccess" />
		<!-- 更新申请 -->
		<knowledge-update ref="knowledgeUpdateRef" @updateList="queryList" />
	</div>
</template>

<script lang="ts" setup name="knowledge">
import { ref, reactive, onMounted, watch, defineAsyncComponent } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { throttle} from '/@/utils/tools';
import {commonEnum, shortcuts } from '/@/utils/constants';
import { auth } from '/@/utils/authFunction';
import { KnowledgePaged, KnowledgeOffShelf, KnowledgeOnTheShelf, baseData } from '/@/api/knowledge';
import { workflowTerminate } from '/@/api/system/workflow';
import { getOrgList } from '/@/api/system/organize';
import { treeList } from '/@/api/knowledge/type';
import { hotSpotType } from '/@/api/business/order';

// 引入组件
const KnowledgeProcess = defineAsyncComponent(() => import('/@/views/knowledge/component/Knowledge-process.vue'));  //流程组件
const KnowledgeUpdate = defineAsyncComponent(() => import('/@/views/knowledge/knowledge/component/Knowledge-update.vue'));  //更新申请
const AuditRecord = defineAsyncComponent(() => import('/@/components/AuditRecord/index.vue'));  //审核记录

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, //页码
		PageSize: 10, //每页条数
		Keyword: '',  //关键字
		Status: ' ',  //状态
    OrgId: '',    //组织机构
    HotSpotTypeId: '', //热点分类
    CreationStartTime: '', //创建开始时间
    CreationEndTime: '', //创建结束时间
    StartOnShelfTime: '', //上架开始时间
    EndOnShelfTime: '', //上架结束时间
    StartOffShelfTime: '', //下架开始时间
    EndOffShelfTime: '', //下架结束时间
	},
	activeName: '0', //tab切换
	tableData: [],  //表格数据
	total: 0, //总条数
	loading: false, //表格loading
	tableLoading: false,  //表格loading
	orgData: [],  //组织机构数据
	knowledgeOptions: [], //知识库类型数据
	statusOptions: [], //状态数据
	defaultExpandedOrgKeys: [], //默认展开的组织机构
	defaultExpandedTypeKeys: [],  //默认展开的知识库类型
});
const router = useRouter(); //路由
const ruleFormRef = ref<FormInstance>(); //表单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<RefType>();
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<RefType>();
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<RefType>();
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 = () => {
	queryList();
};
const handleTimeChange = (val: string[], startKey: string, endKey: string) => {
	if (val) {
		state.queryParams[startKey] = val[0];
		state.queryParams[endKey] = val[1];
	} else {
		state.queryParams[startKey] = '';
		state.queryParams[endKey] = '';
	}
	queryList();
};
// 创建时间
const timeStartChangeCr = (val: string[]) => {
	handleTimeChange(val, 'CreationStartTime', 'CreationEndTime');
};
// 上架时间
const timeStartChangeSj = (val: string[]) => {
	handleTimeChange(val, 'StartOnShelfTime', 'EndOnShelfTime');
};
// 下架时间
const timeStartChangeXj = (val: string[]) => {
	handleTimeChange(val, 'StartOffShelfTime', 'EndOffShelfTime');
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	state.queryParams.PageIndex = 1;
	queryList();
}, 500);
// 获取所有组织结构 和基础数据
const getOrgListApi = async () => {
	state.loading = true;
	try {
		const res: any = await Promise.all([getOrgList(), treeList({ IsEnable: true }),baseData()]);
		state.orgData = res[0].result ?? []; //部门
		state.knowledgeOptions = res[1].result ?? []; // 知识类型
    state.statusOptions = res[2].result ?? []; // 列表状态
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
/** 获取知识列表 */
const queryList = () => {
	if (!auth('knowledge:query')) ElMessage.error('抱歉，您没有权限获取知识库列表');
	else {
		state.tableLoading = true;
    let request = {
      PageIndex: state.queryParams.PageIndex,
      PageSize: state.queryParams.PageSize,
      Keyword: state.queryParams.Keyword,
      Status: state.queryParams.Status,
      OrgId: state.queryParams.OrgId,
      HotSpotTypeId: state.queryParams.HotSpotTypeId,
      CreationStartTime: state.queryParams.CreationStartTime,
      CreationEndTime: state.queryParams.CreationEndTime,
      StartOnShelfTime: state.queryParams.StartOnShelfTime,
      EndOnShelfTime: state.queryParams.EndOnShelfTime,
      StartOffShelfTime: state.queryParams.StartOffShelfTime,
      EndOffShelfTime: state.queryParams.EndOffShelfTime,
    }
		KnowledgePaged(request)
			.then((response: any) => {
				state.tableData = response?.result.items ?? [];
				state.total = response?.result.total;
				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;
	}
	queryList();
};
/** 重置按钮操作 */
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();
}, 500);
// 创建知识
const onOpenAddUser = () => {
	router.push({
		name: 'knowledgeEdit',
		params: {
			tagsViewName: '创建知识',
		},
	});
};
// 修改知识
const onEdit = (row: any) => {
	router.push({
		name: 'knowledgeEdit',
		params: {
			id: row.id,
			tagsViewName: '编辑知识',
		},
	});
};
// 预览
const onPreview = (row: any) => {
	router.push({
		name: 'knowledgePreview',
		params: {
			id: row.id,
			tagsViewName: '知识预览',
		},
	});
};
// 查看审核记录
const auditRecordRef = ref<RefType>();  //审核记录ref
const onRecord = (row: any) => {
	const params = {
		dialogTitle: `审核记录 （${row.title}）`,
		...row,
	};
	auditRecordRef.value.openDialog(params);
};
// 发起更新
const knowledgeUpdateRef = ref<RefType>();  //更新申请ref
const onRenew = (row: any) => {
	knowledgeUpdateRef.value.openDialog(row, state.orgData, state.knowledgeOptions);
};
// 申请流程成功
const knowledgeProcessSuccess = () => {
	handleQuery();
};
// 下架
const offShelfFn = (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 groundingFn = (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.prompt('撤回原因', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		inputPlaceholder: '请输入撤回原因，不超过50字符',
		draggable: true,
		inputErrorMessage: '请输入撤回原因',
		inputType: 'textarea',
		inputValidator: (value) => {
			if (value) return true;
			else return '请输入撤回原因';
		},
	})
		.then(({ value }) => {
			let req = {
				workflowId: row.workflowId,
				opinion: value,
			};
			ElMessageBox.confirm(`是否确定要撤回？撤回成功后请到【我的草稿箱】中进行查看和管理`, '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				draggable: true,
				cancelButtonClass: 'default-button',
				autofocus: false,
			})
				.then(() => {
					workflowTerminate(req)
						.then(() => {
							ElMessage.success('操作成功');
							handleQuery();
							state.queryParams.OrgCode = '';
							getOrgListApi();
						})
						.catch(() => {});
				})
				.catch(() => {});
		})
		.catch(() => {});
};
// 删除知识
const knowledgeProcessRef = ref<RefType>(); //流程组件ref
const onRowDel = (row: any) => {
	knowledgeProcessRef.value.openDialog({ id: row.id, title: '删除知识', commonEnum: commonEnum.Seat, processType: 'deleteStart' });
};
onMounted(() => {
	queryList();
	getOrgListApi();
});
</script>
<style lang="scss" scoped>
.knowledge-knowledge-container {
	.orgTree {
		border-right: 1px solid var(--el-border-color);
		height: 100%;
	}
	.rightContent {
		height: 100%;
	}
	:deep(.el-tree-node__content) {
		height: 40px;
	}
}
</style>
