<template>
	<div class="system-role-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<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="IsDeleted">
					<el-select v-model="state.queryParams.IsDeleted" placeholder="请选择是否删除" @change="handleQuery">
						<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>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <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>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onOpenAddRole" v-auth="'system:role:add'" :loading="state.loading">
						<SvgIcon name="ele-Plus" class="mr5" />新增角色
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30 ,useKey: true}"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:print-config="{}"
					:scrollY="{ enabled: true, gt: 100 }"
					id="systemRole"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<vxe-column field="displayName" title="角色名称" min-width="120"></vxe-column>
					<vxe-column field="name" title="角色编码" min-width="120"></vxe-column>
					<vxe-column field="description" title="角色说明" min-width="140"></vxe-column>
					<vxe-column field="accountIds" title="人员" width="110">
						<template #default="{ row }">
							<el-button title="查看当前角色下的人员" text type="primary" @click="showUserList(row)" size="small">{{
								row.accountIds?.length
							}}</el-button>
						</template>
					</vxe-column>
					<vxe-column field="roleTypeText" title="角色类型" width="120"></vxe-column>
					<vxe-column field="lastModificationTime" title="更新时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.lastModificationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="state" title="状态" width="140"></vxe-column>
					<vxe-column title="操作" fixed="right" width="250" 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'" title="配置角色数据权限" v-if="!row.isDeleted">
								数据权限
							</el-button>
							<el-button link type="danger" @click="onRowDel(row)" v-auth="'system:role:delete'" title="删除角色" v-if="!row.isDeleted">
								删除
							</el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</div>
		<role-add ref="roleAddRef" @updateList="handleQuery" :baseData="baseData" />
		<role-edit ref="roleEditRef" @updateList="handleQuery" :baseData="baseData" />
		<role-permission ref="rolePermissionRef" @updateList="handleQuery" />
		<role-user-list ref="roleUserListRef" />
	</div>
</template>

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

// 定义变量内容
const ruleFormRef = ref<FormInstance>();
const state = reactive<any>({
	tableData: [],
	total: 0, // 总条数
	loading: false, // 表格loading
	isDeletedList: [
		// 是否删除下拉列表
		{
			label: '全部',
			value: '',
		},
		{
			label: '正常',
			value: false,
		},
		{
			label: '已删除',
			value: true,
		},
	],
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		Keyword: null, // 关键字
		IsDeleted: null, // 是否删除
	},
});
const router = useRouter(); // 路由实例
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	handleQuery();
};
/** 获取角色列表 */
const queryList = () => {
	state.loading = true;
	getRoleListPaged(state.queryParams)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.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({
		name: 'systemDataAuth',
		query: {
			id: row.id,
			code: row.name,
			roleDisplay: 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(() => {});
};
// 获取基础信息
const baseData = ref({});
const getBaseData = async () => {
	try {
		const { result } = await getRoleBaseData();
		baseData.value = result;
	} catch (error) {
		console.log(error);
	}
};
// 页面加载时
const tableRef = ref<RefType>();
const toolbarRef = ref<RefType>();
onMounted(() => {
	getBaseData();
	handleQuery();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
