<template>
	<div class="system-organize-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"
					/>
				</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)" 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="onOpenAddOrg('')" v-auth="'system:organize:add'" v-if="showAdd">
						<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="systemOrganize"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:tree-config="{
						childrenField: 'children',
						transform: true,
						rowField: 'id',
						parentField: 'parentId',
					}"
				>
					<vxe-column field="name" title="部门名称" min-width="200" align="center" tree-node>
						<template #default="{ row }">
							<p style="display: flex; align-items: center">
								<span class="pl5" v-html="row.name"></span>
							</p>
						</template>
					</vxe-column>
					<vxe-column field="shortName" title="部门简称" min-width="200" align="center">
						<template #default="{ row }">
							<p style="display: flex; align-items: center">
								<span class="pl5" v-html="row.shortName"></span>
							</p>
						</template>
					</vxe-column>
					<vxe-column field="parentName" title="上级部门" min-width="200" align="center">
						<template #default="{ row }">
							<p style="display: flex; align-items: center">
								<span class="pl5" v-html="row.parentName"></span>
							</p>
						</template>
					</vxe-column>
					<vxe-column field="orgTypeText" title="部门类别" width="100"></vxe-column>
					<vxe-column field="id" title="部门编码" width="100"></vxe-column>
					<vxe-column field="areaName" title="所属区域" width="150"></vxe-column>
					<vxe-column field="areaCode" title="区域编码" width="100"></vxe-column>
					<vxe-column field="isEnable" title="状态" width="120" align="center">
						<template #default="{ row }">
							<el-tag :type="row.isEnable ? 'success' : 'info'">{{ row.isEnable ? '启用' : '禁用' }}</el-tag>
						</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="110" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onOpenEditOrg(row)" title="修改" v-auth="'system:organize:edit'"> 修改 </el-button>
							<el-button link type="primary" @click="onOpenAddOrg(row)" title="新增" v-auth="'system:organize:add'" v-if="showAdd"> 新增 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
		</div>
		<org-add ref="orgAddRef" @updateList="getOrgListApi" />
		<org-edit ref="orgEditRef" @updateList="getOrgListApi" />
	</div>
</template>
<script lang="tsx" setup name="systemOrganize">
import { computed, defineAsyncComponent, nextTick, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { baseData, getOrgListByUser } from '@/api/system/organize';
import { formatDate } from '@/utils/formatTime';
import { throttle } from '@/utils/tools';
import XEUtils from 'xe-utils';
// 引入组件
const OrgAdd = defineAsyncComponent(() => import('@/views/system/organize/components/Org-add.vue')); // 新增组织机构
const OrgEdit = defineAsyncComponent(() => import('@/views/system/organize/components/Org-edit.vue')); // 编辑组织机构

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		keyword: null, // 关键字
	},
	orgType: [], // 部门类别
	areas: [], // 区域
});
const ruleFormRef = ref<RefType>(); // 搜索表单ref
//  在正式上线前 先隐藏用户和部门的新增
const showAdd = computed(() => {
	return !['ZiGong', 'LuZhou'].includes(import.meta.env.VITE_MODE_NAME);
});
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	getOrgListApi();
}, 300);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getOrgListApi();
}, 300);
// 打开新增菜单弹窗
const orgAddRef = ref<RefType>(); // 新增组织机构ref
const onOpenAddOrg = (row?: any) => {
	orgAddRef.value.openDialog(tableData.value, state.orgType, state.areas, row);
};
// 打开编辑菜单弹窗
const orgEditRef = ref<RefType>(); // 编辑组织机构ref
const onOpenEditOrg = (row: any) => {
	orgEditRef.value.openDialog(row, tableData.value, state.orgType, state.areas);
};
// 删除当前行
// const onTableRowDel = (row: any) => {
// 	ElMessageBox.confirm(`此操作将永久删除部门结构：${row.name}, 是否继续?`, '提示', {
// 		confirmButtonText: '确定',
// 		cancelButtonText: '取消',
// 		type: 'warning',
// 	}).then(() => {
// 		removeOrg(row.id).then(() => {
// 			ElMessage.success('删除成功');
// 			getOrgListApi();
// 		})
// 	}).catch(() => { });
// };
// 获取所有部门结构
const tableData = ref<EmptyArrayType>([]);
const list = ref<any[]>([]);
const getOrgListApi = async () => {
	state.loading = true;
	try {
		const { result } = await getOrgListByUser();
		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 = ['name', 'shortName', 'parentName'];
			// 搜索为克隆数据，不会污染源数据
			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 getBaseData = async () => {
	try {
		const { result } = await baseData();
		state.orgType = result.orgTypeOptions; // 部门类别
		state.areas = result.areas; // 区域
	} catch (error) {
		console.log(error);
	}
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	getOrgListApi();
	getBaseData();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>