<template>
	<div class="sys-org-container" v-loading="options.loading">
		<el-row :gutter="5" style="width: 100%; height: 100%">
			<el-col :span="4" :xs="24" style="display: flex; height: 100%">
				<OrgTree ref="orgTreeRef" @node-click="handleNodeChange" />
			</el-col>

			<el-col :span="20" :xs="24" style="display: flex; flex-direction: column; height: 100%">
				<el-card shadow="hover" :body-style="{ padding: '5px 5px 0 5px', display: 'flex', width: '100%', height: '100%', alignItems: 'start' }">
					<el-form :model="state.queryParams" ref="queryForm" :show-message="false" :inlineMessage="true" label-width="auto" style="flex: 1 1 0%">
						<el-row :gutter="10">
							<el-col class="mb5" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
								<el-form-item label="机构名称" prop="name">
									<el-input v-model="state.queryParams.name" placeholder="机构名称" clearable @keyup.enter.native="handleQuery" />
								</el-form-item>
							</el-col>
							<el-col class="mb5" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
								<el-form-item label="机构编码" prop="code">
									<el-input v-model="state.queryParams.code" placeholder="机构编码" clearable @keyup.enter.native="handleQuery" />
								</el-form-item>
							</el-col>
							<el-col class="mb5" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
								<el-form-item label="机构类型" prop="type">
									<el-select v-model="state.queryParams.type" filterable clearable class="w100" @clear="state.queryParams.type = undefined">
										<el-option v-for="item in state.orgTypeList" :key="item.value" :label="item.value" :value="item.code" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>

					<el-divider style="height: calc(100% - 5px); margin: 0 10px" direction="vertical" />

					<el-row>
						<el-col>
							<el-button-group>
								<el-button type="primary" icon="ele-Search" @click="handleQuery" :loading="options.loading"> 查询 </el-button>
								<el-button icon="ele-Refresh" @click="resetQuery" :loading="options.loading"> 重置 </el-button>
							</el-button-group>
						</el-col>
					</el-row>
				</el-card>

				<el-card class="full-table" shadow="hover" style="margin-top: 5px; flex: 1">
					<vxe-grid ref="xGrid" class="xGrid-style" v-bind="options" v-on="gridEvents">
						<template #toolbar_buttons>
							<el-button type="primary" icon="ele-Plus" @click="handleAdd" v-auth="'sysOrg:add'"> 新增 </el-button>
							<el-button-group style="padding-left: 12px">
								<el-button type="primary" icon="ele-Expand" @click="handleExpand"> 全部展开 </el-button>
								<el-button type="primary" icon="ele-Fold" @click="handleFold"> 全部折叠 </el-button>
							</el-button-group>
						</template>
						<template #toolbar_tools> </template>
						<template #empty>
							<el-empty :image-size="200" />
						</template>
						<template #row_status="{ row }">
							<el-tag v-if="row.status === 1" type="success">启用</el-tag>
							<el-tag v-else type="danger">禁用</el-tag>
						</template>
						<template #row_record="{ row }">
							<ModifyRecord :data="row" />
						</template>
						<template #row_buttons="{ row }">
							<el-tooltip content="编辑" placement="top">
								<el-button icon="ele-Edit" size="small" text type="primary" @click="handleEdit(row)" v-auth="'sysOrg:update'"></el-button>
							</el-tooltip>
							<el-tooltip content="删除" placement="top">
								<el-button icon="ele-Delete" size="small" text type="danger" @click="handleDelete(row)" v-auth="'sysOrg:delete'"></el-button>
							</el-tooltip>
						</template>
					</vxe-grid>
				</el-card>
			</el-col>
		</el-row>

		<EditOrg ref="editOrgRef" :title="state.title" :orgData="state.treeData" @reload="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="sysOrg">
import { onMounted, reactive, ref, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { auth } from '/@/utils/authFunction';
import { VxeGridInstance, VxeGridListeners } from 'vxe-table';
import { useVxeTable } from '/@/hooks/useVxeTableOptionsHook';

import OrgTree from '/@/views/system/org/component/orgTree.vue';
import EditOrg from '/@/views/system/org/component/editOrg.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';

import { getAPI } from '/@/utils/axios-utils';
import { SysDictDataApi, SysOrgApi } from '/@/api-services';
import { SysOrg } from '/@/api-services/models';

const xGrid = ref<VxeGridInstance>();
const editOrgRef = ref<InstanceType<typeof EditOrg>>();
const orgTreeRef = ref<InstanceType<typeof OrgTree>>();
const state = reactive({
	treeData: [] as Array<SysOrg>, // 机构树所有数据
	queryParams: {
		id: 0,
		name: undefined,
		code: undefined,
		type: undefined,
	},
	title: '',
	orgTypeList: [] as any,
});

// 表格参数配置
const options = useVxeTable<SysOrg>(
	{
		id: 'sysOrg',
		name: '机构',
		columns: [
			// { type: 'checkbox', width: 40, fixed: 'left' },
			{ type: 'seq', title: '序号', width: 60, fixed: 'left' },
			{ field: 'name', title: '机构名称', minWidth: 200, showOverflow: 'tooltip', treeNode: true },
			{ field: 'code', title: '机构编码', minWidth: 200, showOverflow: 'tooltip' },
			{ field: 'level', title: '级别', minWidth: 70, showOverflow: 'tooltip' },
			{ field: 'type', title: '机构类型', minWidth: 80, formatter: ({ cellValue }: any) => state.orgTypeList.find((u: any) => u.code == cellValue)?.value, showOverflow: 'tooltip' },
			{ field: 'orderNo', title: '排序', width: 80, showOverflow: 'tooltip' },
			{ field: 'status', title: '状态', width: 80, showOverflow: 'tooltip', slots: { default: 'row_status' } },
			{ field: '', title: '修改记录', width: 100, showOverflow: 'tooltip', slots: { default: 'row_record' } },
			{ title: '操作', fixed: 'right', width: 100, showOverflow: true, slots: { default: 'row_buttons' } },
		],
	},
	// vxeGrid配置参数(此处可覆写任何参数)，参考vxe-table官方文档
	{
		stripe: false,
		checkboxConfig: { range: false },
		// 代理配置
		proxyConfig: { autoLoad: true, ajax: { query: () => handleQueryApi() } },
		// 分页配置
		pagerConfig: { enabled: false },
		// 工具栏配置
		toolbarConfig: { export: false },
		treeConfig: { expandAll: false },
	}
);

// 页面初始化
onMounted(async () => {
	await handleQuery();
	let resDicData = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet('org_type');
	state.orgTypeList = resDicData.data.result;
	// 展开表格所有数据，数据量大时请勿开启
	nextTick(async () => {
		if (state.treeData?.length < 100) await xGrid.value?.setAllTreeExpand(true);
	});
});

// 查询api
const handleQueryApi = async () => {
	const params = Object.assign(state.queryParams);
	return getAPI(SysOrgApi).apiSysOrgListGet(params.id, params.name, params.code, params.type);
};

// 查询操作
const handleQuery = async (updateTree: boolean = false) => {
	options.loading = true;
	var res = await handleQueryApi();
	xGrid.value?.loadData(res.data.result ?? []);
	options.loading = false;
	// 是否更新左侧机构列表树
	if (updateTree == true) {
		const data = await orgTreeRef.value?.fetchTreeData();
		state.treeData = data ?? [];
	}
	// 若无选择节点并且查询条件为空时，更新编辑页面机构列表树
	if (state.queryParams.id == 0 && state.queryParams.name == undefined && state.queryParams.code == undefined && state.queryParams.type == undefined && updateTree == false)
		state.treeData = res.data.result ?? [];
};

// 重置操作
const resetQuery = async () => {
	state.queryParams.id = 0;
	state.queryParams.name = undefined;
	state.queryParams.code = undefined;
	state.queryParams.type = undefined;
	await xGrid.value?.commitProxy('reload');
};

// 打开新增页面
const handleAdd = () => {
	state.title = '添加机构';
	editOrgRef.value?.openDialog({ status: 1, orderNo: 100 });
};

// 打开编辑页面
const handleEdit = (row: any) => {
	state.title = '编辑机构';
	editOrgRef.value?.openDialog(row);
};

// 删除
const handleDelete = (row: any) => {
	ElMessageBox.confirm(`确定删除机构：【${row.name}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await getAPI(SysOrgApi).apiSysOrgDeletePost({ id: row.id });
			ElMessage.success('删除成功');
			await handleQuery(true);
		})
		.catch(() => {});
};

// 表格事件
const gridEvents: VxeGridListeners<SysOrg> = {
	// 只对 proxy-config.ajax.query 配置时有效，当手动点击查询时会触发该事件
	async proxyQuery() {
		state.treeData = xGrid.value?.getTableData().tableData ?? [];
	},
};

// 树组件点击
const handleNodeChange = async (node: any) => {
	state.queryParams.id = node.id;
	state.queryParams.name = undefined;
	state.queryParams.code = undefined;
	state.queryParams.type = undefined;
	orgTreeRef?.value?.setCurrentKey();
	await handleQuery();
};

// 全部展开
const handleExpand = () => {
	xGrid.value?.setAllTreeExpand(true);
};

// 全部折叠
const handleFold = () => {
	xGrid.value?.clearTreeExpand();
};
</script>
