<template>
	<div class="system-organize-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<div class="flex-center-between mb20">
				<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent>
					<el-form-item label="关键字" prop="keyword" class="mb0">
						<el-input v-model="state.queryParams.keyword" placeholder="部门名称" clearable @keyup.enter="handleQuery" style="width: 250px" />
					</el-form-item>
					<el-form-item class="mb0">
						<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"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
					</el-form-item>
				</el-form>
				<div>
					<el-button type="primary" @click="expand"
						><SvgIcon
							name="ele-ArrowDownBold"
							style="transition: transform var(--el-transition-duration)"
							:style="state.isExpand ? 'transform: none' : 'transform: rotateZ(180deg)'"
							class="mr5"
						/>
						{{ state.isExpand ? '收起' : '展开' }}</el-button
					>
					<el-button type="primary" @click="onOpenAddOrg('')" v-auth="'system:organize:add'"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-auto-resizer class="table" v-loading="state.loading">
				<template #default="{ height, width }">
					<el-table-v2
						v-model:expanded-row-keys="state.expandedRowKeys"
						:columns="state.columns"
						:data="state.orgTableData"
						expand-column-key="orgName"
						fixed
						:width="width"
						:height="height"
					>
						<template #empty>
							<Empty />
						</template>
					</el-table-v2>
				</template>
			</el-auto-resizer>
		</div>
		<AddOrg ref="addOrgRef" @updateList="getOrgListApi" />
		<EditOrg ref="editOrgRef" @updateList="getOrgListApi" />
	</div>
</template>
<script lang="ts" setup name="organize">
import { defineAsyncComponent, ref, h, reactive, onMounted, watch } from 'vue';
import { ElButton, ElTag, ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { getOrgList, baseData } from '/@/api/system/organize';
import { formatDate } from '/@/utils/formatTime';
import { auth } from '/@/utils/authFunction';
import { throttle } from '/@/utils/tools';
// 引入组件
const AddOrg = defineAsyncComponent(() => import('/@/views/system/organize/component/addOrg.vue'));
const EditOrg = defineAsyncComponent(() => import('/@/views/system/organize/component/editOrg.vue'));

// 定义变量内容
const addOrgRef = ref();
const editOrgRef = ref();
const state = reactive({
	orgTableData: <any>[], // 获取所有菜单
	staticArr: <any>[],
	loading: false,
	queryParams: {
		keyword: '',
	},
	expandedRowKeys: <any>[],
	columns: [
		{
			key: 'orgName',
			dataKey: 'orgName',
			title: '部门名称',
			width: 400,
		},
		{
			key: 'orgShortName',
			dataKey: 'orgShortName',
			title: '部门简称',
			width: 400,
		},
		{
			key: 'parentName',
			dataKey: 'parentName',
			title: '上级部门',
			width: 200,
		},
		{
			key: 'orgTypeText',
			dataKey: 'orgTypeText',
			title: '部门类别',
			width: 100,
		},
		{
			key: 'orgCode',
			dataKey: 'orgCode',
			title: '部门编码',
			width: 200,
		},
		{
			key: 'isEnable',
			dataKey: 'isEnable',
			title: '状态',
			width: 100,
			cellRenderer: (data: any) => {
				return h(ElTag, { type: data.rowData.isEnable ? 'success' : 'info' }, { default: () => (data.rowData.isEnable ? '启用' : '禁用') });
			},
		},
		{
			key: 'creationTime',
			dataKey: 'creationTime',
			title: '更新时间',
			width: 200,
			cellRenderer: (data: any) => h('span', {}, { default: () => formatDate(new Date(data.rowData.creationTime), 'YYYY-mm-dd HH:MM:SS') }),
		},
		{
			key: 'handle',
			title: '操作',
			width: 100,
			fixed: 'right',
			align: 'center',
			cellRenderer: ({ rowData }: any) => {
				return h('span', { class: 'flex' }, [
					auth('system:organize:edit')
						? h(
								ElButton,
								{
									onClick: () => onOpenEditOrg(rowData),
									type: 'primary',
									title: '修改',
									link: true,
								},
								{ default: () => '修改' }
						)
						: '',
					auth('system:organize:add')
						? h(
								ElButton,
								{
									onClick: () => onOpenAddOrg(rowData),
									type: 'primary',
									title: '新增',
									link: true,
								},
								{ default: () => '新增' }
						)
						: '',
				]);
			},
		},
	],
	isExpand: true,
	orgType: [],
});
const ruleFormRef = ref();
// 搜索
const formatTable = (list: any[], keyword: string) => {
	if (!list.length || !Array.isArray(list)) return [];
	let emptyArr: any[] = [];
	list.map((item) => {
		if (item.orgName.includes(keyword)) {
			if (item.children && Array.isArray(item.children) && item.children.length > 0) {
				item.children = formatTable(item.children, keyword);
			}
			emptyArr.push(item);
		} else if (item.children && Array.isArray(item.children) && item.children.length > 0) {
			item.children = formatTable(item.children, keyword);
			if (item.children.length) {
				emptyArr.push(item);
			}
		}
	});
	return emptyArr;
};
let emptyArr: any[] = [];
const getExpand = (list: any[]) => {
	if (!list.length || !Array.isArray(list)) return [];
	list.map((item) => {
		if (item.children && Array.isArray(item.children) && item.children.length > 0) {
			getExpand(item.children);
		}
		emptyArr.push(item.id);
	});
	return emptyArr;
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	if (state.queryParams.keyword) {
		state.loading = true;
		state.expandedRowKeys = [];
		emptyArr = [];
		state.orgTableData = formatTable(JSON.parse(JSON.stringify(state.staticArr)), state.queryParams.keyword);
		state.expandedRowKeys = getExpand(state.orgTableData);
		state.loading = false;
	} else {
		getOrgListApi();
	}
}, 500);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getOrgListApi();
	state.expandedRowKeys = [];
	emptyArr = [];
}, 500);
// 打开新增菜单弹窗
const onOpenAddOrg = (row?: any) => {
	addOrgRef.value.openDialog(state.orgTableData, state.orgType, row);
};
// 打开编辑菜单弹窗
const onOpenEditOrg = (row: any) => {
	editOrgRef.value.openDialog(row, state.orgTableData, state.orgType);
};
const expand = () => {
	state.isExpand = !state.isExpand;
};
watch(
	() => state.isExpand,
	(old: Boolean) => {
		if (old) getAllIds(state.orgTableData);
		else state.expandedRowKeys = [];
	}
);
const getAllIds = (arr: any) => {
	if (!arr) return [];
	arr.forEach((v: any) => {
		if (v.children?.length) {
			getAllIds(v.children);
			state.expandedRowKeys.push(v.id);
		}
	});
};
// 删除当前行
// const onTabelRowDel = (row: any) => {
// 	ElMessageBox.confirm(`此操作将永久删除部门结构：${row.orgName}, 是否继续?`, '提示', {
// 		confirmButtonText: '确定',
// 		cancelButtonText: '取消',
// 		type: 'warning',
// 	}).then(() => {
// 		removeOrg(row.id).then(() => {
// 			ElMessage.success('删除成功');
// 			getOrgListApi();
// 		})
// 	}).catch(() => { });
// };
// 获取所有部门结构
const getOrgListApi = async () => {
	if (!auth('system:organize:query')) ElMessage.error('抱歉，您没有权限获取组织架构列表！');
	else {
		state.loading = true;
		try {
			const res: any = await Promise.all([getOrgList(), baseData()]);
			state.orgTableData = res[0].result ?? [];
			state.staticArr = res[0].result ?? [];
			state.expandedRowKeys = state.orgTableData.map((v: any) => {
				return v.children.map((i: any) => {
					return i.id;
				});
			});
			state.expandedRowKeys.push(state.orgTableData[0].id); //默认展开一级部门
			state.orgType = res[1].orgType;
			state.loading = false;
		} catch (error) {
			state.loading = false;
		}
	}
};
// 页面加载时
onMounted(() => {
	getOrgListApi();
});
</script>
<style lang="scss" scoped>
.system-organize-container {
	.table {
		flex: 1;
	}
}
</style>
