<template>
	<div class="knowledge-index-container layout-padding">
		<el-card shadow="never" class="h100">
			<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: 'name' }"
									@node-click="handleNodeClick"
									ref="orgRef"
									v-loading="state.loading"
									:filter-node-method="filterNode"
									node-key="id"
									:style="state.activeName === '0' ? '' : '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: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: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: 250px"
								/>
							</el-form-item>
							<el-form-item label="标题" prop="Title">
								<el-input v-model="state.queryParams.Title" placeholder="标题" clearable @keyup.enter="handleQuery" />
							</el-form-item>
							<el-form-item label="是否公开" prop="IsPublic">
								<el-select v-model="state.queryParams.IsPublic" placeholder="请选择是否公开" class="w100">
									<el-option label="公开" :value="true" />
									<el-option label="不公开" :value="false" />
								</el-select>
							</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:index: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="300">
								<template #default="{ row }">
									<el-link type="primary" :underline="false" @click="onPreview(row)">
										{{ row.title }}
									</el-link>
								</template>
							</el-table-column>
							<el-table-column prop="knowledgeTypeName" label="知识分类" show-overflow-tooltip width="120"></el-table-column>
							<el-table-column prop="statusName" label="知识状态" show-overflow-tooltip></el-table-column>
							<el-table-column prop="hotspotName" label="热点" show-overflow-tooltip width="120"></el-table-column>
							<el-table-column prop="hotspotName" label="是否公开" show-overflow-tooltip>
								<template #default="{ row }">
									<span>{{ row.isPublic ? '公开' : '不公开' }}</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="creatorName" label="创建人" show-overflow-tooltip width="120"></el-table-column>
							<el-table-column prop="creatorOrgName" 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="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 label="操作" width="200" fixed="right" align="center">
								<template #default="{ row }">
									<el-button link type="primary" @click="onEdit(row)" title="编辑" v-if="[0, 4].includes(row.status)" v-auth="'knowledge:index:edit'">
										编辑
									</el-button>
									<el-button
										link
										type="danger"
										@click="onRowDel(row)"
										title="删除"
										v-if="[0, 2, 4].includes(row.status)"
										v-auth="'knowledge:index:delete'"
									>
										删除
									</el-button>
									<el-button
										link
										type="primary"
										@click="offShelfFn(row)"
										title="下架"
										v-if="[3].includes(row.status)"
										v-auth="'knowledge:index:undercarriage'"
									>
										下架
									</el-button>
									<el-button
										link
										type="primary"
										@click="groundingFn(row)"
										title="上架"
										v-if="[4].includes(row.status)"
										v-auth="'knowledge:index:grounding'"
									>
										上架
									</el-button>
<!--									<el-button
										link
										type="primary"
										@click="onAudit(row)"
										title="审批"
										v-if="[1, 2].includes(row.status) && row.isCanHandle"
										v-auth="'business:order:handle'"
									>
										审批
									</el-button>-->
									<el-button
										link
										type="primary"
										@click="onPreview(row)"
										title="查看"
										v-if="[1, 2, 3, 4].includes(row.status)"
										v-auth="'knowledge:index:preview'"
									>
										查看
									</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>
		</el-card>
		<!-- 流程审批 -->
		<process-audit ref="processAuditRef" @orderProcessSuccess="queryList" />
	</div>
</template>

<script lang="ts" setup name="knowledgeManage">
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 } from '/@/utils/constants';
import { auth } from '/@/utils/authFunction';
import {KnowledgePaged, KnowledgeOffShelf, KnowledgeOnTheShelf, baseData, KnowledgeDel} from '/@/api/knowledge';
import { getOrgList } from '/@/api/system/organize';
import { treeList } from '/@/api/knowledge/type';
import { hotSpotType } from '/@/api/business/order';

// 引入组件
const ProcessAudit = defineAsyncComponent(() => import('/@/components/ProcessAudit/index.vue')); // 流程审批

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, //页码
		PageSize: 10, //每页条数
		Keyword: null, //关键字
		Status: ' ', //状态
		OrgId: null, //组织机构
		HotSpotTypeId: null, //热点分类
		KnowledgeTypeId: null, //知识类型
		Title: null, //标题
		Summary: null, //摘要
	},
	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.name.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 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:index:query')) ElMessage.error('抱歉，您没有权限获取知识库列表');
	else {
		state.tableLoading = true;
		KnowledgePaged(state.queryParams)
			.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.id;
			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 = null;
	state.queryParams.KnowledgeTypeId = null;
	state.queryParams.HotspotId = null;
	filterOrg.value = '';
	filterType.value = '';
	filterHot.value = '';
	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 processAuditRef = ref<RefType>(); //审核记录ref
const onAudit = (row: any) => {
	const params = {
		id: row.workflowId,
		processType: '工单办理',
		orderDetail: {},
		extra: {
			dialogTitle: '知识审批',
			inputPlaceholder: '办理意见',
			annexName: '知识附件',
		},
	};
	processAuditRef.value.openDialog(params);
};
// 下架
const offShelfFn = (row: any) => {
	ElMessageBox.confirm(`是否确定要下架【${row.title}】？知识下架后，将不会被检索到！`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeOffShelf(row.id).then(() => {
				ElMessage.success('操作成功');
				handleQuery();
			});
		})
		.catch(() => {});
};
// 上架
const groundingFn = (row: any) => {
	ElMessageBox.confirm(`是否确定要上架【${row.title}】？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeOnTheShelf(row.id).then(() => {
				ElMessage.success('操作成功');
				handleQuery();
			});
		})
		.catch(() => {});
};
// 删除知识
const onRowDel = (row: any) => {
  if(row.workflowId){ // 如果有流程id，说明是审批中的知识
    const params = {
      id: row.workflowId,
      processType: '删除知识',
      extra: {
        dialogTitle: '删除知识',
        inputPlaceholder: '办理意见',
        annexName: '知识附件',
      },
      orderDetail: row,
    };
    processAuditRef.value.openDialog(params);
  }else{ // 否则直接删除
    ElMessageBox.confirm(`是否确定要删除【${row.title}】？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      cancelButtonClass: 'default-button',
    })
        .then(() => {
          KnowledgeDel({data:row}).then(() => {
            ElMessage.success('操作成功');
            handleQuery();
          });
        })
        .catch(() => {});
  }
};
onMounted(() => {
	queryList();
	getOrgListApi();
});
</script>
<style lang="scss" scoped>
.knowledge-index-container {
	.orgTree {
		border-right: 1px solid var(--el-border-color);
		height: 100%;
	}
	.rightContent {
		height: 100%;
	}
	:deep(.el-tree-node__content) {
		height: 40px;
	}
	:deep(.el-card__body) {
		height: 100%;
	}
}
</style>
