<template>
	<div class="auxiliary-event-class-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
				<el-form-item label="关键字" prop="keyword">
					<el-input v-model="state.queryParams.keyword" placeholder="事件名称" @keyup.enter="handleQuery" class="keyword-input" v-trim />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Refresh" class="mr5" />重置
					</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onAdd" v-auth="'auxiliary:eventClass:add'" :loading="state.loading">
						<SvgIcon name="ele-Plus" class="mr5" />新增
					</el-button>
					<el-button type="danger" @click="onDelete" v-auth="'auxiliary:eventClass:delete'" :loading="state.loading" :disabled="disabled">
						<SvgIcon name="ele-Delete" class="mr5" />删除
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					:loading="state.loading"
					:data="list"
					:column-config="{ resizable: true, useKey: true }"
					:row-config="{ isCurrent: true, isHover: true, useKey: true, height: 36 }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 0 }"
					id="auxiliaryEvent"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:tree-config="{
						childrenField: 'children',
						transform: true,
						rowField: 'id',
						parentField: 'parentId',
					}"
					:checkbox-config="{ labelField: 'id', highlight: true }"
					@checkbox-change="selectChangeEvent"
				>
					<vxe-column type="checkbox" title="编码" min-width="150" tree-node></vxe-column>
					<vxe-column field="eventName" title="事件名称" min-width="400">
						<template #default="{ row }">
							<p style="display: flex; align-items: center">
								<span class="pl5" v-html="row.eventName"></span>
							</p>
						</template>
					</vxe-column>
					<vxe-column field="orderBy" title="排序" width="120"></vxe-column>
					<vxe-column field="creationTime" title="更新时间" width="160" align="center">
						<template #default="{ row }">
							<span>{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="80" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onEdit(row)" title="修改" v-auth="'auxiliary:eventClass:edit'"> 修改 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
		</div>
		<event-add ref="eventRef" @updateList="queryList" />
		<event-edit ref="eventEditRef" @updateList="queryList" />
	</div>
</template>
<script lang="tsx" setup name="auxiliaryEventClass">
import { computed, defineAsyncComponent, nextTick, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { throttle } from '@/utils/tools';
import { treeEventClassAll, treeEventClassDelete } from '@/api/auxiliary/eventClass';
import XEUtils from 'xe-utils';
// 引入组件
const EventAdd = defineAsyncComponent(() => import('@/views/auxiliary/eventClass/components/Event-add.vue')); // 新增事件
const EventEdit = defineAsyncComponent(() => import('@/views/auxiliary/eventClass/components/Event-edit.vue')); // 修改事件

// 定义变量内容
const state = reactive<any>({
	tableData: [], // 获取所有菜单
	staticArr: [], // 静态数据
	loading: false, // 加载状态
	queryParams: {
		keyword: null, // 关键字
	},
	expandedRowKeys: [], // 展开行
	isExpand: false, // 是否展开
});
const ruleFormRef = ref<RefType>(); // 搜索表单ref
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	queryList();
}, 300);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
}, 300);
// 打开新增弹窗
const eventRef = ref<RefType>(); // 新增组织机构ref
const onAdd = (row?: any) => {
	eventRef.value.openDialog(state.tableData, row);
};
const disabled = computed(() => {
	return !Boolean(checkedTable.value.length);
});
// 获取所有事件结构
const tableData = ref<EmptyArrayType>([]);
const list = ref<any[]>([]);
const queryList = async () => {
	state.loading = true;
	try {
		const { result } = await treeEventClassAll();
		tableData.value = result ?? [];
		const filterVal = XEUtils.toValueString(state.queryParams.keyword)?.trim().toLowerCase();
		if (filterVal) {
			const filterRE = new RegExp(filterVal, 'gi');
			const options = { children: 'children' };
			const searchProps = ['eventName'];
			// 搜索为克隆数据，不会污染源数据
			const rest = XEUtils.searchTree(
				tableData.value,
				(item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterVal) > -1),
				options
			);
			XEUtils.eachTree(
				rest,
				(item) => {
					searchProps.forEach((key) => {
						item[key] = String(item[key]).replace(filterRE, (match) => `<span class="keyword-highlight">${match}</span>`);
					});
				},
				options
			);
			list.value = rest;
			list.value = XEUtils.toTreeArray(list.value);
			await nextTick(() => {
				// 搜索之后默认展开所有子节点
				if (tableRef.value) {
					tableRef.value.setAllTreeExpand(true);
				}
			});
		} else {
			list.value = tableData.value;
			list.value = XEUtils.toTreeArray(list.value);
		}
		state.loading = false;
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
// 修改
const eventEditRef = ref<RefType>();
const onEdit = (data: any) => {
	eventEditRef.value.openDialog(data);
};
// 删除当前行
const onDelete = () => {
	const ids = checkedTable.value.map((item=>item.id));
	ElMessageBox.confirm(`此操作将永久删除选择中的事件, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			treeEventClassDelete(ids).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
const checkedTable = ref<EmptyArrayType>([]);
const selectChangeEvent = () => {
	if (tableRef.value) {
		checkedTable.value = tableRef.value.getCheckboxRecords();
	}
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
