<template>
	<div class="auxiliary-area-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="区域名称" clearable @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.tableLoading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onAddArea" v-auth="'auxiliary:area:add'" :loading="state.loading"> <SvgIcon name="ele-Plus" 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="auxiliaryArea"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:tree-config="{
						childrenField: 'children',
						transform: true,
						rowField: 'id',
						parentField: 'parentId',
					}"
				>
					<vxe-column field="areaName" title="区域名称" min-width="400" treeNode>
						<template #default="{ row }">
							<p style="display: flex; align-items: center">
								<span class="pl5" v-html="row.areaName"></span>
							</p>
						</template>
					</vxe-column>
					<vxe-column field="id" title="区域代码" min-width="350">
						<template #default="{ row }">
							<p style="display: flex; align-items: center">
								<span class="pl5" v-html="row.id"></span>
							</p>
						</template>
					</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="150" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onEditArea(row)" title="修改" v-auth="'auxiliary:area:edit'" v-if="row.isCanModify">
								修改
							</el-button>
							<el-button link type="danger" @click="onDelArea(row)" title="删除" v-auth="'auxiliary:area:delete'" v-if="row.isCanModify">
								删除
							</el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
		</div>
		<area-add ref="areaAddRef" @updateList="queryList" />
		<area-edit ref="areaEditRef" @updateList="queryList" />
	</div>
</template>
<script lang="tsx" setup name="auxiliaryArea">
import { defineAsyncComponent, nextTick, onMounted, reactive, ref, watch } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { treeArea, treeAreaDelete } from '@/api/auxiliary/area';
import XEUtils from 'xe-utils';
// 引入组件
const AreaAdd = defineAsyncComponent(() => import('@/views/auxiliary/area/components/Area-add.vue')); // 新增区域
const AreaEdit = defineAsyncComponent(() => import('@/views/auxiliary/area/components/Area-edit.vue')); // 编辑区域

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		keyword: null, // 关键字
	},
});
const ruleFormRef = ref<RefType>(); // 搜索表单ref
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	queryList();
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 打开新增弹窗
const areaAddRef = ref<RefType>(); // 新增组织机构ref
const onAddArea = (row?: any) => {
	areaAddRef.value.openDialog(tableData.value, row);
};
// 打开编辑弹窗
const areaEditRef = ref<RefType>(); // 编辑组织机构ref
const onEditArea = (row: any) => {
	areaEditRef.value.openDialog(row, tableData.value);
};
// 删除当前行
const onDelArea = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除次区域：${row.areaName}, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			treeAreaDelete(row.id).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 获取所有部门结构
const tableData = ref<EmptyArrayType>([]);
const list = ref<any[]>([]);
const queryList = async () => {
	state.loading = true;
	try {
		const res: any = await treeArea();
		tableData.value = res?.result ?? [];

		const filterVal = XEUtils.toValueString(state.queryParams.keyword)?.trim().toLowerCase();
		if (filterVal) {
			const filterRE = new RegExp(filterVal, 'gi');
			const options = { children: 'children' };
			const searchProps = ['areaName', 'id'];
			// 搜索为克隆数据，不会污染源数据
			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 toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
