<template>
	<div class="system-user-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-row :gutter="20" class="h100">
				<!-- 左侧组织树 -->
				<el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="4" class="orgTree">
					<div class="h100 pr10">
						<el-input v-model="filterOrg" placeholder="请输入部门名称" class="input-with-select mt10 mb10" clearable> </el-input>
						<el-scrollbar style="height: calc(100% - 40px);'">
							<template v-if="state.orgData.length">
								<el-tree
									:data="state.orgData"
									highlight-current
									:expand-on-click-node="false"
									:props="{ children: 'children', label: 'orgName' }"
									@node-click="handleNodeClick"
									ref="treRef"
									v-loading="state.loading"
									node-key="orgCode"
									style="min-width: 100%; display: inline-block"
									:filter-node-method="filterNodeOrg"
									:default-expanded-keys="state.defaultExpandedKeys"
								>
								</el-tree>
							</template>
							<template v-else>
								<Empty description="暂无组织数据" />
							</template>
						</el-scrollbar>
					</div>
				</el-col>
				<!-- 右侧表格 -->
				<el-col :xs="18" :sm="18" :md="18" :lg="20" :xl="20" class="rightContent">
					<el-scrollbar class="pr10 scrollbar__view" ref="rightScrollRef">
						<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent>
							<el-form-item label="关键字" prop="Keyword">
								<el-input v-model="state.queryParams.Keyword" placeholder="姓名/电话号码" clearable @keyup.enter="handleQuery" />
							</el-form-item>
							<el-form-item label="角色" prop="Role">
								<el-select-v2 v-model="state.queryParams.Role" filterable :options="state.options" 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>
						<div class="mb20">
							<el-button type="primary" @click="onOpenAddUser" v-auth="'system:user:add'"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
						</div>
						<!-- 表格 -->
						<el-table :data="state.tableData" v-loading="state.tableLoading" row-key="id">
							<el-table-column type="index" width="60" label="序号" />
							<el-table-column prop="name" label="姓名" show-overflow-tooltip width="170"></el-table-column>
							<el-table-column prop="userName" label="账号" show-overflow-tooltip width="170"></el-table-column>
							<el-table-column prop="organization.orgName" label="所属部门" show-overflow-tooltip width="190"></el-table-column>
							<el-table-column prop="organization.orgTypeText" label="部门类别" show-overflow-tooltip width="190"></el-table-column>
							<el-table-column prop="roleNames" label="角色" show-overflow-tooltip width="300"></el-table-column>
							<el-table-column prop="phoneNo" label="电话号码" show-overflow-tooltip width="130"></el-table-column>
							<el-table-column prop="staffNo" label="工号" show-overflow-tooltip width="120"></el-table-column>
							<el-table-column prop="genderText" label="性别" show-overflow-tooltip width="80"></el-table-column>
							<el-table-column prop="creationTime" label="更新时间" show-overflow-tooltip width="170">
								<template #default="{ row }">
									<span>{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="state" label="状态" show-overflow-tooltip width="80"></el-table-column>
							<el-table-column label="操作" width="180" fixed="right" align="center">
								<template #default="{ 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>
							</el-table-column>
							<template #empty>
								<Empty />
							</template>
						</el-table>
						<!-- 分页 -->
						<pagination
							:total="state.total"
							v-model:page="state.queryParams.PageIndex"
							v-model:limit="state.queryParams.PageSize"
							@pagination="getList"
						/>
						<el-backtop target=".scrollbar__view > div" />
					</el-scrollbar>
				</el-col>
			</el-row>
		</div>
		<user-add ref="userAddRef" @updateList="getList" />
		<user-edit ref="userEditRef" @updateList="getList" />
	</div>
</template>

<script lang="ts" setup name="systemUser">
import { defineAsyncComponent, ref, reactive, onMounted, watch, onActivated } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { auth } from '/@/utils/authFunction';
import { throttle } from '/@/utils/tools';
import { delUser, getUserListPaged, restPwd, getRoles } from '/@/api/system/user';
import { getOrgList } from '/@/api/system/organize';

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

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 10, // 每页条数
		Keyword: '',  // 关键字
		Role: null, // 角色id
		OrgCode: null, // 组织code
	},
	tableData: [],  // 表格数据
	total: 0, // 总条数
	loading: false, // 加载状态
	tableLoading: false,  // 表格加载状态
	orgData: [],  // 组织结构数据
	options: [],  // 角色数据
	defaultExpandedKeys: [],  // 默认展开的节点
});
const ruleFormRef = ref<FormInstance>(); //表单ref
const filterOrg = ref('');  // 搜索部门名称
const treRef = ref<RefType>();  // 树形组件ref
watch(filterOrg, (val) => {
	treRef.value!.filter(val);
});
// 搜索部门名称
const filterNodeOrg = (value: string, data: any) => {
	if (!value) return true;
	return data.orgName.includes(value);
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	state.queryParams.PageIndex = 1;
	getList();
}, 300);
// 获取所有组织结构
const getOrgListApi = () => {
	if (!auth('system:organize:query')) ElMessage.error('抱歉，您没有权限获取组织架构！');
	else {
		state.loading = true;
		getOrgList()
			.then((res: any) => {
				state.orgData = res?.result ?? [];
				state.defaultExpandedKeys = state.orgData.map((v: any) => {
					return v.children.map((i: any) => {
						return i.orgCode;
					});
				});
				state.defaultExpandedKeys.push(state.orgData[0].orgCode); //默认展开一级部门
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	}
};
/** 获取用户列表 */
const rightScrollRef = ref<RefType>();
const getList = () => {
	if (!auth('system:user:query')) ElMessage.error('抱歉，您没有权限获取用户列表！');
	else {
		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 = () => {
	if (!auth('system:role:query')) ElMessage.error('抱歉，您没有权限获取角色列表！');
	else {
		getRoles({ PageIndex: 1, PageSize: 999 }).then((res: any) => {
			state.options = res?.result.items ?? [];
			state.options = state.options.map((item: any) => ({
				value: item.id,
				label: item.displayName,
			}));
		});
	}
};
// 点击节点
const handleNodeClick = (data: any) => {
	state.queryParams.OrgCode = data.orgCode;
	getList();
};
// 打开新增用户弹窗
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('操作成功');
				getList();
				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('删除成功');
				getList();
				state.queryParams.OrgCode = '';
				getOrgListApi();
			});
		})
		.catch(() => {});
};
onMounted(() => {
	getRolesFn();
	getList();
	getOrgListApi();
});
onActivated(() => {});
</script>
<style lang="scss" scoped>
.system-user-container {
	.orgTree {
		border-right: 1px solid var(--el-border-color);
		height: 100%;
	}

	.rightContent {
		height: 100%;
	}

	:deep(.el-tree-node__content) {
		height: 40px;
	}
}
</style>
