<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" :loading="state.loading"> <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>
		<org-add ref="orgAddRef" @updateList="getOrgListApi" />
		<org-edit ref="orgEditRef" @updateList="getOrgListApi" />
	</div>
</template>
<script lang="ts" setup name="systemOrganize">
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';
import other from '/@/utils/other';
// 引入组件
const OrgAdd = defineAsyncComponent(() => import('/@/views/system/organize/component/Org-add.vue'));  // 新增组织机构
const OrgEdit = defineAsyncComponent(() => import('/@/views/system/organize/component/Org-edit.vue'));  // 编辑组织机构

// 定义变量内容
const state = reactive({
	orgTableData: <EmptyArrayType>[], // 获取所有菜单
	staticArr: <EmptyArrayType>[],  // 静态数据
	loading: false, // 加载状态
	queryParams: {
		keyword: '',  // 关键字
	},
	expandedRowKeys: <EmptyArrayType>[],  // 展开行
	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: 100,
		},
    {
      key: 'areaName',
      dataKey: 'areaName',
      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: false, // 是否展开
	orgType: [],  // 部门类别
  areas: [],  // 区域
});
const ruleFormRef = ref<RefType>(); // 搜索表单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(other.deepClone(state.staticArr), state.queryParams.keyword);
		state.expandedRowKeys = getExpand(state.orgTableData);
		state.loading = false;
	} else {
		getOrgListApi();
	}
}, 300);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getOrgListApi();
	state.expandedRowKeys = [];
	emptyArr = [];
}, 300);
// 打开新增菜单弹窗
const orgAddRef = ref<RefType>(); // 新增组织机构ref
const onOpenAddOrg = (row?: any) => {
	orgAddRef.value.openDialog(state.orgTableData, state.orgType,state.areas, row);
};
// 打开编辑菜单弹窗
const orgEditRef = ref<RefType>();  // 编辑组织机构ref
const onOpenEditOrg = (row: any) => {
	orgEditRef.value.openDialog(row, state.orgTableData, state.orgType,state.areas);
};
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 onTableRowDel = (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.orgType = res[1].result.orgTypeOptions; // 部门类别
      state.areas = res[1].result.areas; // 区域
			state.loading = false;
		} catch (error) {
      console.log(error)
			state.loading = false;
		}
	}
};
// 页面加载时
onMounted(() => {
	getOrgListApi();
});
</script>
<style lang="scss" scoped>
.system-organize-container {
	.table {
		flex: 1;
	}
}
</style>
