<template>
	<div class="system-role-container layout-pd">
		<el-card shadow="never">
			<!-- 通用搜索 -->
			<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent>
				<el-form-item label="是否删除" prop="IsDeleted">
					<el-select v-model="state.queryParams.IsDeleted" placeholder="请选择是否删除">
						<el-option v-for="item in state.isDeletedList" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="关键字" prop="Keyword">
					<el-input v-model="state.queryParams.Keyword" placeholder="角色名称/角色编码" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading" v-waves> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Refresh" class="mr5" />重置
					</el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card shadow="never">
			<div class="mb20">
				<el-button type="primary" @click="onOpenAddRole" v-waves v-auth="'system:role:add'"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.loading" row-key="id">
				<el-table-column type="index" width="60" label="序号" />
				<el-table-column prop="displayName" label="角色名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="name" label="角色编码" show-overflow-tooltip></el-table-column>
				<el-table-column prop="description" label="角色说明" show-overflow-tooltip width="400"></el-table-column>
				<el-table-column label="人员" show-overflow-tooltip width="80">
					<template #default="{ row }">
						<el-button title="查看当前角色下的人员" text type="primary" @click="showUserList(row)">{{ row.accountIds.length }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="state" label="状态" show-overflow-tooltip width="80"> </el-table-column>
				<el-table-column prop="lastModificationTime" label="更新时间" show-overflow-tooltip width="170">
					<template #default="{ row }">
						<span>{{ formatDate(row.lastModificationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="260" fixed="right" align="center">
					<template #default="{ row }">
						<el-button link type="primary" @click="onOpenEditRole(row)" title="修改角色信息" v-auth="'system:role:edit'" v-if="!row.isDeleted">
							修改
						</el-button>
						<el-button link type="success" @click="onPermissions(row)" title="分配角色权限" v-auth="'system:role:assign'" v-if="!row.isDeleted">
							分配权限
						</el-button>
						<el-button link type="info" @click="onDataAuth(row)" v-auth="'system:role:dataAuth:query'" title="配置角色数据权限" v-if="!row.isDeleted">
							数据权限
						</el-button>
						<el-button link type="danger" @click="onRowDel(row)" v-auth="'system:role:edit'" title="删除角色" v-if="!row.isDeleted"> 删除 </el-button>
					</template>
				</el-table-column>
				<template #empty>
					<Empty />
				</template>
			</el-table>
			<!-- 分页 -->
			<pagination
				:total="state.tableData.total"
				v-model:page="state.queryParams.PageIndex"
				v-model:limit="state.queryParams.PageSize"
				@pagination="queryList"
			/>
		</el-card>
		<role-add ref="roleAddRef" @updateList="handleQuery" />
		<role-edit ref="roleEditRef" @updateList="handleQuery" />
		<role-permission ref="rolePermissionRef" @updateList="handleQuery" />
		<role-user-list ref="roleUserListRef" />
	</div>
</template>

<script lang="ts" setup name="systemRole">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { useRouter } from 'vue-router';
import { throttle } from '/@/utils/tools';
import { getRoleListPaged, delRole } from '/@/api/system/roles';
import { auth } from '/@/utils/authFunction';
import { formatDate } from '/@/utils/formatTime';
import mittBus from '/@/utils/mitt';
// 引入组件
const RoleAdd = defineAsyncComponent(() => import('/@/views/system/roles/component/Role-add.vue')); // 角色新增组件
const RoleEdit = defineAsyncComponent(() => import('/@/views/system/roles/component/Role-edit.vue'));   // 角色编辑组件
const RolePermission = defineAsyncComponent(() => import('/@/views/system/roles/component/Role-permission.vue')); // 角色权限组件
const RoleUserList = defineAsyncComponent(() => import('/@/views/system/roles/component/Role-user-list.vue'));  // 角色人员组件

// 定义变量内容
const ruleFormRef = ref<FormInstance>();
const state = reactive<any>({
	tableData: {
		data: [], // 表格数据
		total: 0, // 总条数
	},
	loading: false, // 表格loading
	isDeletedList: [  // 是否删除下拉列表
		{
			label: '全部',
			value: '',
		},
		{
			label: '正常',
			value: false,
		},
		{
			label: '已删除',
			value: true,
		},
	],
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 10, // 每页条数
		Keyword: '',  // 关键字
		IsDeleted: '',  // 是否删除
	},
});
const router = useRouter(); // 路由实例
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	state.queryParams.PageIndex = 1;
	queryList();
}, 500);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	handleQuery();
}, 500);
/** 获取角色列表 */
const queryList = () => {
	if (!auth('system:role:query')) ElMessage.error('抱歉，您没有获取角色列表权限！');
	else {
		state.loading = true;
		getRoleListPaged(state.queryParams)
			.then((response: any) => {
				state.tableData.data = response?.result.items ?? [];
				state.tableData.total = response?.result.total ?? 0;
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	}
};
// 打开新增角色弹窗
const roleAddRef = ref<RefType>();
const onOpenAddRole = () => {
	roleAddRef.value.openDialog();
};
// 打开修改角色弹窗
const roleEditRef = ref<RefType>();
const onOpenEditRole = (row: Object) => {
	roleEditRef.value.openDialog(row);
};
// 打开配置权限弹窗
const rolePermissionRef = ref<RefType>();
const onPermissions = (row: Object) => {
	rolePermissionRef.value.openDialog(row);
};
// 打开人员列表弹窗
const roleUserListRef = ref<RefType>();
const showUserList = (row: Object) => {
	roleUserListRef.value.openDialog(row);
};
// 打开数据权限
const onDataAuth = (row: any) => {
	router.push({
		path: '/system/roles/dataAuth',
		query: {
			id: row.id,
			code: row.name,
			roleDisplay: row.displayName,
			tagsViewName: '数据权限 ' + row.displayName,
		},
	});
};
// 删除角色
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除角色名称：“${row.displayName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			delRole(row.id).then(() => {
				ElMessage.success('删除成功');
				handleQuery();
				mittBus.emit('clearCache', 'systemUser');
			});
		})
		.catch(() => {});
};
// 页面加载时
onMounted(() => {
	handleQuery();
});
</script>
<style lang="scss" scoped>
.system-role-container {
	.el-table {
		flex: 1;
	}
}
</style>
