<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="4" :lg="4" :xl="4" class="orgTree">
					<el-scrollbar height="100%" class="pr10">
						<template v-if="state.orgData.length">
							<el-tree
								:data="state.orgData"
								highlight-current
								:expand-on-click-node="false"
								default-expand-all
								:props="{ children: 'children', label: 'orgName' }"
								@node-click="handleNodeClick"
								ref="treRef"
								v-loading="state.loading"
								node-key="id"
							>
							</el-tree>
						</template>
						<template v-else>
							<Empty description="暂无组织数据" />
						</template>
					</el-scrollbar>
				</el-col>
				<!-- 右侧表格 -->
				<el-col :xs="18" :sm="18" :md="20" :lg="20" :xl="20" class="rightContent">
					<el-scrollbar class="pr10" ref="rightScrollRef">
						<div class="flex-column">
							<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" v-waves>
										<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 class="flex-center-between mb20">
								<p class="table-title"></p>
								<div>
									<el-button type="primary" @click="onOpenAddUser" v-waves v-auth="'100102'"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
									<el-button type="primary" v-waves @click="onImportTable" :disabled="!state.multipleSelection.length">
										<SvgIcon name="iconfont icon-daochu" class="mr5" />导出
									</el-button>
								</div>
							</div>
							<!-- 表格 -->
							<el-table :data="state.tableData" v-loading="state.tableLoading" row-key="id" @selection-change="handleSelectionChange">
								<el-table-column type="selection" width="55" :reserve-selection="true" />
								<el-table-column type="index" width="60" label="序号" />
								<el-table-column prop="name" label="姓名" show-overflow-tooltip width="120"></el-table-column>
								<el-table-column prop="userName" label="账号" show-overflow-tooltip width="120"></el-table-column>
								<el-table-column prop="orgName" label="所属部门" show-overflow-tooltip width="190"></el-table-column>
								<el-table-column prop="roles" 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="80"></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="scope">
										<span>{{ formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
									</template>
								</el-table-column>
								<el-table-column prop="state" label="状态" show-overflow-tooltip width="60"></el-table-column>
								<el-table-column label="操作" width="140" fixed="right" align="center">
									<template #default="scope">
										<el-button text type="primary" @click="onOpenEditUser(scope.row)" v-auth="'100103'" title="修改">
											<SvgIcon name="ele-Edit" size="var(--hotline-table-icon-font-size)" />
										</el-button>
										<el-button text type="success" @click="onSetRole(scope.row)" v-auth="'100105'" title="设置角色">
											<SvgIcon name="ele-Setting" size="var(--hotline-table-icon-font-size)" />
										</el-button>
										<el-button text type="warning" @click="onRestPwd(scope.row)" title="重置密码">
											<SvgIcon name="ele-Refresh" size="var(--hotline-table-icon-font-size)" />
										</el-button>
										<el-button text type="danger" @click="onRowDel(scope.row)" v-auth="'100104'" title="删除">
											<SvgIcon name="ele-Delete" size="var(--hotline-table-icon-font-size)" />
										</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"
							/>
						</div>
					</el-scrollbar>
				</el-col>
			</el-row>
		</div>

		<AddUer ref="addUserRef" @updateList="handleQuery" />
		<EditUser ref="editUserRef" @updateList="handleQuery" />
		<SetRole ref="setRoleRef" @updateList="handleQuery" />
	</div>
</template>

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

// 引入组件
const AddUer = defineAsyncComponent(() => import('/@/views/system/user/component/addUser.vue'));
const EditUser = defineAsyncComponent(() => import('/@/views/system/user/component/editUser.vue'));
const SetRole = defineAsyncComponent(() => import('/@/views/system/user/component/setRole.vue'));

// 定义接口来定义对象的类型
interface QueryState {
	queryParams: {
		PageIndex: number;
		PageSize: number;
		PhoneNo?: string;
		Name?: string;
		Keyword?: string;
		OrgCode?: string | null;
		Role?: string | null;
	};
	tableData: Array<any>;
	total: number;
	tableLoading: boolean;
	loading: boolean;
	multipleSelection: Array<any>;
	orgData: Array<any>;
	options: Array<any>;
}

// 定义变量内容
const state = reactive<QueryState>({
	queryParams: {
		PageIndex: 1,
		PageSize: 10,
		Keyword: '',
		Role: null, // 角色id
		OrgCode: null, // 组织code
	},
	tableData: [],
	total: 0,
	loading: false,
	tableLoading:false,
	multipleSelection: [],
	orgData: [],
	options: [],
});
const ruleFormRef = ref<FormInstance>(); //表单ref
const addUserRef = ref(); //新增用户
const editUserRef = ref(); //修改用户信息
const setRoleRef = ref(); //设置角色
const treRef = ref();
const rightScrollRef = ref();
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	state.queryParams.PageIndex = 1;
	getList();
}, 1000);
// 获取所有组织结构
const getOrgListApi = () => {
	state.loading = true;
	getOrgList()
		.then((res: any) => {
			state.orgData = res?.result ?? [];
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
/** 获取用户列表 */
const getList = () => {
	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 }).then((res: any) => {
		state.options = res?.result.items ?? [];
		state.options = state.options.map((item) => ({
			value: item.id,
			label: item.displayName,
		}));
	});
};
// 点击节点
const handleNodeClick = (data: any) => {
	state.queryParams.OrgCode = data.orgCode;
	getList();
};
// 打开新增用户弹窗
const onOpenAddUser = () => {
	addUserRef.value.openDialog();
};
// 打开设置用户角色弹窗
const onSetRole = (row: any) => {
	setRoleRef.value.openDialog(row);
};
// 表格多选
const handleSelectionChange = (val: any) => {
	state.multipleSelection = val;
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.OrgCode = '';
	treRef.value?.setCurrentKey(null);
	handleQuery();
}, 1000);
// 打开修改用户弹窗
const onOpenEditUser = (row: any) => {
	editUserRef.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('操作成功');
				handleQuery();
				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('删除成功');
				handleQuery();
				state.queryParams.OrgCode = '';
				getOrgListApi();
			});
		})
		.catch(() => {});
};
// 导出表格
const onImportTable = () => {
	const tabeHeader = [
		{ key: 'name', colWidth: '', title: '姓名', type: 'text', isCheck: true },
		{ key: 'userName', colWidth: '', title: '账号', type: 'text', isCheck: true },
		{ key: 'orgName', colWidth: '', title: '所属部门', type: 'text', isCheck: true },
		{ key: 'roles', colWidth: '', title: '角色', type: 'text', isCheck: true },
		{ key: 'phoneNo', colWidth: '', title: '电话号码', type: 'text', isCheck: true },
		{ key: 'staffNo', colWidth: '', title: '工号', type: 'text', isCheck: true },
		{ key: 'defaultTelNo', colWidth: '', title: '默认分机', type: 'text', isCheck: true },
		{ key: 'creationTime', colWidth: '', title: '更新时间', type: 'text', isCheck: true },
	];
	table2excel(tabeHeader, state.multipleSelection, `用户信息 ${formatDate(new Date(), 'YYYY-mm-dd HH-MM')}`);
};
onMounted(() => {
	getRolesFn();
	getList();
	getOrgListApi();
});
</script>
<style lang="scss" scoped>
.system-user-container {
	.orgTree {
		border-right: 1px solid var(--el-border-color);
		height: 100%;
	}

	.rightContent {
		height: 100%;
		.flex-column {
			display: flex;
			flex-direction: column;
			height: 100%;
			.el-table {
				flex: 1;
			}
		}
	}

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