<template>
	<div class="layout-padding">
		<splitpanes>
			<!-- 左侧角色管理 -->
			<pane size="45">
				<div class="layout-padding-auto layout-padding-view">
					<el-row class="ml10" v-show="showSearch">
						<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
							<el-form-item :label="$t('approle.roleName')" prop="roleName">
								<el-input :placeholder="$t('approle.inputRoleNameTip')" style="max-width: 180px" v-model="state.queryForm.roleName" />
							</el-form-item>
							<el-form-item>
								<el-button @click="getDataList" icon="search" type="primary">
									{{ $t('common.queryBtn') }}
								</el-button>
								<el-button @click="resetQuery" icon="Refresh">{{ $t('common.resetBtn') }}</el-button>
							</el-form-item>
						</el-form>
					</el-row>
					<el-row>
						<div class="mb8" style="width: 100%">
							<el-button @click="roleDialogRef.openDialog()" class="ml10" icon="folder-add" type="primary" v-auth="'app_approle_add'">
								{{ $t('common.addBtn') }}
							</el-button>
							<el-button plain @click="excelUploadRef.show()" class="ml10" icon="upload-filled" type="primary" v-auth="'app_approle_export'">
								{{ $t('common.importBtn') }}
							</el-button>
							<el-button
								plain
								:disabled="multiple"
								@click="handleDelete(selectObjs)"
								class="ml10"
								icon="Delete"
								type="primary"
								v-auth="'app_approle_del'"
							>
								{{ $t('common.delBtn') }}
							</el-button>
							<right-toolbar
								:export="'app_approle_export'"
								@exportExcel="exportExcel"
								@queryTable="getDataList"
								class="ml10"
								style="float: right; margin-right: 20px"
								v-model:showSearch="showSearch"
							></right-toolbar>
						</div>
					</el-row>
					<el-table
						:data="state.dataList"
						@selection-change="handleSelectionChange"
						@row-click="handleRoleClick"
						style="width: 100%"
						v-loading="state.loading"
						border
						highlight-current-row
						:cell-style="tableStyle.cellStyle"
						:header-cell-style="tableStyle.headerCellStyle"
					>
						<el-table-column align="center" type="selection" width="40" />
						<el-table-column :label="$t('approle.index')" type="index" width="60" />
						<el-table-column :label="$t('approle.roleName')" prop="roleName" show-overflow-tooltip></el-table-column>
						<el-table-column :label="$t('approle.roleCode')" prop="roleCode" show-overflow-tooltip></el-table-column>
						<el-table-column :label="$t('common.action')" width="300">
							<template #default="scope">
								<el-button icon="edit-pen" @click="roleDialogRef.openDialog(scope.row.roleId)" text type="primary" v-auth="'app_approle_edit'"
									>{{ $t('common.editBtn') }}
								</el-button>

								<el-button icon="setting" @click="workbenchMenuDialogRef.openDialog(scope.row.roleId)" text type="primary" v-auth="'app_approle_edit'"
									>{{ $t('approle.workbenchMenuTip') }}
								</el-button>

								<el-button icon="delete" @click="handleDelete([scope.row.roleId])" text type="primary" v-auth="'app_approle_del'"
									>{{ $t('common.delBtn') }}
								</el-button>
							</template>
						</el-table-column>
					</el-table>
					<pagination @current-change="currentChangeHandle" @size-change="sizeChangeHandle" v-bind="state.pagination" />
				</div>
			</pane>

			<!-- 右侧用户角色管理 -->
			<pane size="55" class="ml8">
				<div class="layout-padding-auto layout-padding-view">
					<el-card shadow="never" style="height: 100%">
						<template #header>
							<div class="card-header">
								<div class="card-title">
									<el-icon class="title-icon" v-if="selectedRoleId">
										<User />
									</el-icon>
									<el-icon class="title-icon" v-else>
										<InfoFilled />
									</el-icon>
									<span class="title-text">
										{{ selectedRoleName ? `${selectedRoleName} - 授权用户` : '用户角色管理' }}
									</span>
								</div>
								<div class="card-subtitle" v-if="selectedRoleId">
									<el-tag type="info" size="small">
										{{ userState.pagination?.total || 0 }} 个授权用户
									</el-tag>
								</div>
							</div>
						</template>
						
						<div v-if="!selectedRoleId" class="empty-state">
							<el-empty description="请在左侧选择角色以查看对应的用户列表">
								<template #image>
									<el-icon size="100" color="var(--el-color-info)">
										<User />
									</el-icon>
								</template>
								<template #description>
									<p>选择左侧角色后，这里将显示该角色的授权用户</p>
								</template>
							</el-empty>
						</div>

						<div v-else>
							<!-- 搜索栏 -->
							<el-row class="mb8" v-show="showUserSearch">
								<el-form :inline="true" :model="userState.queryForm" @keyup.enter="getUserDataList" ref="userQueryRef">
									<el-form-item label="用户名" prop="username">
										<el-input placeholder="请输入用户名" style="max-width: 180px" v-model="userState.queryForm.username" />
									</el-form-item>
									<el-form-item>
										<el-button @click="getUserDataList" icon="search" type="primary">
											{{ $t('common.queryBtn') }}
										</el-button>
										<el-button @click="resetUserQuery" icon="Refresh">{{ $t('common.resetBtn') }}</el-button>
									</el-form-item>
								</el-form>
							</el-row>

							<!-- 操作按钮 -->
							<el-row>
								<div class="mb8" style="width: 100%">
									<el-button @click="addUserDialogRef.openDialog()" icon="folder-add" type="primary">
										新增用户
									</el-button>
									<right-toolbar
										@queryTable="getUserDataList"
										class="ml10"
										style="float: right; margin-right: 20px"
										v-model:showSearch="showUserSearch"
									></right-toolbar>
								</div>
							</el-row>

							<!-- 用户列表 -->
							<el-table
								:data="userState.dataList"
								style="width: 100%"
								v-loading="userState.loading"
								border
								:cell-style="tableStyle.cellStyle"
								:header-cell-style="tableStyle.headerCellStyle"
							>
								<el-table-column label="#" type="index" width="60" />
								<el-table-column label="用户名" prop="username" show-overflow-tooltip></el-table-column>
								<el-table-column label="姓名" prop="name" show-overflow-tooltip></el-table-column>
								<el-table-column label="操作" width="120">
									<template #default="scope">
										<el-button icon="delete" @click="handleRemoveUser(scope.row.userId)" text type="danger">
											取消授权
										</el-button>
									</template>
								</el-table-column>
								<template #empty>
									<el-empty description="该角色暂无授权用户">
										<template #image>
											<el-icon size="60" color="var(--el-color-info-light-5)">
												<User />
											</el-icon>
										</template>
										<template #description>
											<p>点击上方"新增用户"按钮为该角色添加用户</p>
										</template>
									</el-empty>
								</template>
							</el-table>
							<pagination @current-change="userCurrentChangeHandle" @size-change="userSizeChangeHandle" v-bind="userState.pagination" />
						</div>
					</el-card>
				</div>
			</pane>
		</splitpanes>

		<!-- 角色编辑、新增 -->
		<RoleDialog @refresh="getDataList()" ref="roleDialogRef" />
		<!-- 分配工作台菜单 -->
		<WorkbenchMenuDialog @refresh="getDataList()" ref="workbenchMenuDialogRef" />
		<!-- 新增用户对话框 -->
		<AddUserDialog @refresh="getUserDataList()" ref="addUserDialogRef" :roleId="selectedRoleId" />
		<!-- 导入角色 -->
		<upload-excel
			:title="$t('sysuser.importUserTip')"
			@refreshDataList="getDataList"
			ref="excelUploadRef"
			temp-url="/admin/sys-file/local/file/approle.xlsx"
			url="/admin/approle/import"
		/>
	</div>
</template>

<script lang="ts" name="systemRole" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { delObj, fetchList } from '/@/api/app/approle';
import { fetchList as fetchUserRoleList, delObj as delUserRole } from '/@/api/app/appuserrole';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
import { User, InfoFilled } from '@element-plus/icons-vue';

// 引入组件
const RoleDialog = defineAsyncComponent(() => import('./form.vue'));
const WorkbenchMenuDialog = defineAsyncComponent(() => import('./workbench-menu-dialog.vue'));
const AddUserDialog = defineAsyncComponent(() => import('./add-user-dialog.vue'));
const { t } = useI18n();

// 定义变量内容
const roleDialogRef = ref();
const workbenchMenuDialogRef = ref();
const addUserDialogRef = ref();
const excelUploadRef = ref();
const queryRef = ref();
const userQueryRef = ref();
const showSearch = ref(true);
const showUserSearch = ref(true);

// 角色相关状态
const selectObjs = ref([]) as any;
const multiple = ref(true);

// 用户相关状态
const selectedRoleId = ref('');
const selectedRoleName = ref('');

// 角色表格状态
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		roleName: '',
	},
	pageList: fetchList,
	descs: ['create_time'],
});

// 用户角色关联表格状态
const userState: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		roleId: '',
		username: '',
	},
	pageList: fetchUserRoleList
});

// 角色 table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 用户角色关联 table hook
const {
	getDataList: getUserDataList,
	currentChangeHandle: userCurrentChangeHandle,
	sizeChangeHandle: userSizeChangeHandle
} = useTable(userState);

// 清空角色搜索条件
const resetQuery = () => {
	queryRef.value.resetFields();
	getDataList();
};

// 清空用户搜索条件
const resetUserQuery = () => {
	userQueryRef.value.resetFields();
	getUserDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/app/approle/export', state.queryForm, 'approle.xlsx');
};

// 角色多选事件
const handleSelectionChange = (objs: { roleId: string }[]) => {
	selectObjs.value = objs.map(({ roleId }) => roleId);
	multiple.value = !objs.length;
};

// 点击角色行事件
const handleRoleClick = (row: any) => {
	selectedRoleId.value = row.roleId;
	selectedRoleName.value = row.roleName;
	userState.queryForm.roleId = row.roleId;
	getUserDataList();
};

// 删除角色操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}

	try {
		await delObj(ids);
		getDataList();
		useMessage().success(t('common.delSuccessText'));
		// 如果删除的角色是当前选中的角色，清空右侧
		if (ids.includes(selectedRoleId.value)) {
			selectedRoleId.value = '';
			selectedRoleName.value = '';
			userState.dataList = [];
		}
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

// 单个取消用户授权
const handleRemoveUser = async (userId: string) => {
	try {
		await useMessageBox().confirm('确认要取消该用户的角色授权吗？');
	} catch {
		return;
	}

	try {
		await delUserRole(userId);
		getUserDataList();
		useMessage().success('取消授权成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
</script>

<style scoped>
.empty-state {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 300px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	flex-wrap: wrap;
	gap: 8px;
}

.card-title {
	display: flex;
	align-items: center;
	gap: 8px;
	flex: 1;
}

.title-icon {
	font-size: 18px;
	color: var(--el-color-primary);
}

.title-text {
	font-size: 16px;
	font-weight: 600;
	color: var(--el-text-color-primary);
}

.card-subtitle {
	display: flex;
	align-items: center;
}

@media (max-width: 768px) {
	.card-header {
		flex-direction: column;
		align-items: flex-start;
	}
	
	.card-subtitle {
		width: 100%;
		justify-content: flex-start;
	}
}
</style>
