<template>
	<div class="system-user-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<splitpanes class="h100" Vertical>
				<pane min-size="16" max-size="25" size="16">
					<el-input v-model="filterOrg" placeholder="请输入部门名称" class="input-with-select mb10" clearable @input="onQueryChanged"> </el-input>
					<el-scrollbar style="height: calc(100% - 40px);'" ref="scrollBarRef">
						<el-skeleton :loading="state.loading" animated :rows="10">
							<template #default>
								<el-tree-v2
									:data="state.orgData"
									:filter-method="filterNodeOrg"
									ref="treRef"
									highlight-current
									:expand-on-click-node="false"
									@node-click="handleNodeClick"
									:item-size="40"
									:height="treeHeight"
									empty-text="暂无组织数据"
									:props="{ label: 'name', value: 'id' }"
								>
									<template #default="{ node }">
										<span>{{ node.label }}</span>
									</template>
								</el-tree-v2>
							</template>
						</el-skeleton>
					</el-scrollbar>
				</pane>
				<pane>
					<el-scrollbar class="pr10 scrollbar__view" ref="rightScrollRef">
						<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 label="角色" prop="Role">
								<el-select-v2
									v-model="state.queryParams.Role"
									filterable
									:options="state.roleOptions"
									:props="{
										label: 'displayName',
										value: 'id',
									}"
									placeholder="请选择角色"
									clearable
								/>
							</el-form-item>
							<el-form-item>
								<el-button type="primary" @click="handleQuery" :loading="state.tableLoading">
									<SvgIcon name="ele-Search" class="mr5" />查询
								</el-button>
								<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.tableLoading">
									<SvgIcon name="ele-Refresh" class="mr5" />重置
								</el-button>
							</el-form-item>
						</el-form>
						<ProTable
							ref="proTableRef"
							:columns="columns"
							:data="state.tableData"
							@updateTable="queryList"
							:loading="state.tableLoading"
							:total="state.total"
							v-model:page-index="state.queryParams.PageIndex"
							v-model:page-size="state.queryParams.PageSize"
						>
							<!-- 表格 header 按钮 -->
							<template #tableHeader="scope">
								<el-button type="primary" @click="onOpenAddUser" v-auth="'system:user:add'"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
							</template>
							<!-- 表格操作 -->
							<template #operation="{ row }">
								<el-button link type="primary" @click="onOpenEditUser(row)" v-auth="'system:user:edit'" title="修改" v-if="!row.isDeleted">
									修改
								</el-button>
								<el-button link type="warning" @click="onRestPwd(row)" title="重置密码" v-auth="'system:user:resetPwd'" v-if="!row.isDeleted">
									重置密码
								</el-button>
								<el-button link type="danger" @click="onRowDel(row)" v-auth="'system:user:delete'" title="删除" v-if="!row.isDeleted">
									删除
								</el-button>
							</template>
						</ProTable>
						<el-backtop target=".scrollbar__view > div" />
					</el-scrollbar>
				</pane>
			</splitpanes>
		</div>
		<user-add
			ref="userAddRef"
			@updateList="queryList"
			:roles="state.roleOptions"
			:baseOrg="state.orgData"
			:baseData="state.baseData"
			:telsList="state.telsList"
		/>
		<user-edit
			ref="userEditRef"
			@updateList="queryList"
			:roles="state.roleOptions"
			:baseOrg="state.orgData"
			:baseData="state.baseData"
			:telsList="state.telsList"
		/>
	</div>
</template>

<script lang="tsx" setup name="systemUser">
import { defineAsyncComponent, nextTick, onActivated, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { throttle } from '@/utils/tools';
import { delUser, getBaseData, getCanUseOrg, getRoles, getUserListPaged, restPwd } from '@/api/system/user';
import { getTelList } from '@/api/public/wex';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

// 引入组件
const UserAdd = defineAsyncComponent(() => import('@/views/system/user/component/User-add.vue')); // 新增用户组件
const UserEdit = defineAsyncComponent(() => import('@/views/system/user/component/User-edit.vue')); // 修改用户组件

const proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([
	{ prop: 'name', label: '姓名', width: 170 },
	{ prop: 'userName', label: '账号', width: 170 },
	{ prop: 'organization.name', label: '所属部门', width: 190 },
	{ prop: 'organization.orgTypeText', label: '部门类别', width: 190 },
	{ prop: 'roleNames', label: '角色', width: 300 },
	{ prop: 'phoneNo', label: '电话号码', width: 130 },
	{ prop: 'staffNo', label: '工号', width: 120 },
	{ prop: 'userTypeText', label: '用户类型' },
	{ prop: 'genderText', label: '性别', width: 80 },
	{
		prop: 'creationTime',
		label: '创建时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'state', label: '状态', width: 80 },
	{ prop: 'operation', label: '操作', fixed: 'right', width: 180, align: 'center' },
]);
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 10, // 每页条数
		Keyword: null, // 关键字
		Role: null, // 角色id
		OrgCode: null, // 组织code
	},
	tableData: [], // 表格数据
	total: 0, // 总条数
	loading: false, // 加载状态
	tableLoading: false, // 表格加载状态
	orgData: [], // 组织结构数据
	roleOptions: [], // 角色数据
	baseData: [], // 基础数据
	telsList: [], // 分机数据
});
const ruleFormRef = ref<FormInstance>(); //表单ref
const filterOrg = ref(''); // 搜索部门名称
const treRef = ref<RefType>(); // 树形组件ref
const onQueryChanged = (query: string) => {
	if (query) {
		treRef.value!.filter(query);
	} else {
		treRef.value!.filter(query);
		treRef.value?.setExpandedKeys([]);
	}
};
// 搜索部门名称
const filterNodeOrg = (query: string, data: any) => {
	return data.name!.includes(query);
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	state.queryParams.PageIndex = 1;
	queryList();
}, 300);
// 获取所有组织结构
const getOrgListApi = () => {
	state.loading = true;
	getCanUseOrg()
		.then((res: any) => {
			state.orgData = res?.result ?? [];
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
/** 获取用户列表 */
const rightScrollRef = ref<RefType>();
const queryList = () => {
	state.tableLoading = true;
	getUserListPaged(state.queryParams)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.total;
			rightScrollRef.value.setScrollTop(0); //滚动倒顶部
			state.tableLoading = false;
		})
		.catch(() => {
			state.tableLoading = false;
		});
};
// 获取角色
const getRolesFn = () => {
	getRoles({ PageIndex: 1, PageSize: 999, IsDeleted: false }).then((res: any) => {
		state.roleOptions = res?.result.items ?? [];
	});
};
// 查询页面基础信息
const getBaseDataFn = () => {
	getBaseData().then((res: any) => {
		state.baseData = res?.result ?? [];
	});
};
// 获取分机列表
const getTelsListFn = async (object?: object) => {
	const res: any = await getTelList(object);
	state.telsList = res?.result ?? [];
};
// 点击节点
const handleNodeClick = (data: any) => {
	state.queryParams.OrgCode = data.id;
	queryList();
};
// 打开新增用户弹窗
const userAddRef = ref<RefType>(); //新增用户
const onOpenAddUser = () => {
	userAddRef.value.openDialog();
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.OrgCode = '';
	treRef.value?.setCurrentKey(null);
	handleQuery();
}, 300);
// 打开修改用户弹窗
const userEditRef = ref<RefType>(); //修改用户信息
const onOpenEditUser = (row: any) => {
	userEditRef.value.openDialog(row);
};
// 重置密码
const onRestPwd = (row: any) => {
	ElMessageBox.confirm(`此操作将：“${row.name}的密码重置为Fwkj@789”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			restPwd(row.id).then(() => {
				ElMessage.success('操作成功');
				queryList();
				state.queryParams.OrgCode = '';
				getOrgListApi();
			});
		})
		.catch(() => {});
};
// 删除用户
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.name}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		draggable: true,
		cancelButtonClass: 'default-button',
		type: 'warning',
	})
		.then(() => {
			delUser(row.id).then(() => {
				ElMessage.success('删除成功');
				queryList();
				state.queryParams.OrgCode = '';
				getOrgListApi();
			});
		})
		.catch(() => {});
};
onMounted(() => {
	getRolesFn();
	getBaseDataFn();
	getTelsListFn();
	getOrgListApi();
	queryList();
});
const scrollBarRef = ref<RefType>(); // 滚动条ref
const treeHeight = ref(0);
onMounted(async () => {
	await nextTick();
	treeHeight.value = scrollBarRef.value.wrapRef.clientHeight;
	window.addEventListener('resize', () => {
		treeHeight.value = scrollBarRef.value.wrapRef.clientHeight;
	});
});
onActivated(() => {
	treRef.value.setData(state.orgData);
});
</script>
<style lang="scss" scoped>
.system-user-container {
	.orgTree {
		border-right: 1px solid var(--el-border-color);
		height: 100%;
	}
	:deep(.el-tree-node__content) {
		line-height: 40px;
	}
}
</style>
