<script setup lang="ts">
import { useRoleManageStore } from '@/stores/role-manage'
import type { RoleRecord } from '@/stores/role-manage'
import RolePermissionModal from '@/components/RolePermissionModal.vue'

const roleStore = useRoleManageStore()

const columns = [
  { title: '角色名称', dataIndex: 'label', key: 'label' },
  { title: '标识', dataIndex: 'name', key: 'name' },
  { title: '用户数', dataIndex: 'users_count', key: 'users_count', width: 100 },
  { title: '路由组数', key: 'route_groups_count', width: 120 },
  { title: '操作', key: 'action', width: 120 },
]

const permModalOpen = ref(false)
const currentRole = ref<RoleRecord | null>(null)

function handleConfigPermission(record: RoleRecord) {
  currentRole.value = record
  permModalOpen.value = true
}

function handlePermSaved() {
  roleStore.fetchRoles()
}

onMounted(() => {
  roleStore.fetchRoles()
})
</script>

<template>
  <a-card title="角色管理">
    <a-table
      :columns="columns"
      :data-source="roleStore.roles"
      :loading="roleStore.loading"
      :pagination="false"
      row-key="id"
      size="middle"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'label'">
          <div>
            <div>{{ record.label }}</div>
            <div class="text-xs text-gray-400">{{ record.description }}</div>
          </div>
        </template>
        <template v-if="column.key === 'route_groups_count'">
          <a-tag v-if="record.name === 'administrator'" color="blue">全部</a-tag>
          <span v-else>{{ record.route_groups_count }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-button
            v-if="record.name !== 'administrator'"
            type="link"
            size="small"
            @click="handleConfigPermission(record as RoleRecord)"
          >
            配置权限
          </a-button>
        </template>
      </template>
    </a-table>
  </a-card>

  <RolePermissionModal
    v-model:open="permModalOpen"
    :role="currentRole"
    @saved="handlePermSaved"
  />
</template>
