<template>
  <div class="role-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="showAddDialog">新增角色</el-button>
        </div>
      </template>
      <el-table :data="roles" v-loading="loading">
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="data_scope" label="数据范围">
          <template #default="{ row }">
            <el-tag>{{ dataScopeLabel(row.data_scope) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_system" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_system ? 'info' : 'success'">{{ row.is_system ? '系统' : '自定义' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button size="small" @click="showPermissionDialog(row)">配置权限</el-button>
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" :disabled="row.is_system" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑角色' : '新增角色'" width="500px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="编码">
          <el-input v-model="form.code" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" />
        </el-form-item>
        <el-form-item label="数据范围">
          <el-select v-model="form.data_scope">
            <el-option label="仅自己" value="self_only" />
            <el-option label="下属" value="subordinate_only" />
            <el-option label="部门" value="dept_only" />
            <el-option label="全部" value="all" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="permDialogVisible" title="配置权限" width="600px">
      <el-tree
        :data="permTreeData"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermIds"
        :props="{ label: 'name' }"
        ref="permTreeRef"
        default-expand-all
      />
      <template #footer>
        <el-button @click="permDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePermSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { rbacApi } from '@/api'

const loading = ref(false)
const roles = ref<any[]>([])
const allPerms = ref<any[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const editingRole = ref<any>(null)
const form = ref<any>({ name: '', code: '', description: '', data_scope: 'self_only' })

const permDialogVisible = ref(false)
const permTreeRef = ref()
const checkedPermIds = ref<string[]>([])

const dataScopeLabels: Record<string, string> = {
  all: '全部',
  subordinate_only: '下属',
  dept_only: '部门',
  self_only: '仅自己',
}
function dataScopeLabel(s: string): string {
  return dataScopeLabels[s] || s
}

const permTreeData = ref<any[]>([])

onMounted(async () => {
  await loadRoles()
  await loadPerms()
})

async function loadRoles() {
  loading.value = true
  try {
    const res: any = await rbacApi.getRoles()
    roles.value = res || []
  } finally {
    loading.value = false
  }
}

async function loadPerms() {
  const res: any = await rbacApi.getPermissions()
  allPerms.value = res || []
  permTreeData.value = res?.map((p: any) => ({ id: p.id, name: `${p.name} (${p.code})` })) || []
}

function showAddDialog() {
  isEdit.value = false
  editingRole.value = null
  form.value = { name: '', code: '', description: '', data_scope: 'self_only' }
  dialogVisible.value = true
}

function showEditDialog(row: any) {
  isEdit.value = true
  editingRole.value = row
  form.value = { name: row.name, code: row.code, description: row.description, data_scope: row.data_scope }
  dialogVisible.value = true
}

async function showPermissionDialog(row: any) {
  editingRole.value = row
  checkedPermIds.value = row.permission_ids || []
  const role: any = await rbacApi.getRole(row.id)
  checkedPermIds.value = allPerms.value
    .filter((p: any) => role.permissions?.includes(p.code))
    .map((p: any) => p.id)
  permDialogVisible.value = true
}

async function handleSubmit() {
  try {
    if (isEdit.value) {
      await rbacApi.updateRole(editingRole.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await rbacApi.createRole(form.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    await loadRoles()
  } catch { /**/ }
}

async function handlePermSubmit() {
  const checked = permTreeRef.value?.getCheckedKeys() || []
  await rbacApi.updateRole(editingRole.value.id, { permission_ids: checked })
  ElMessage.success('权限配置已保存')
  permDialogVisible.value = false
  await loadRoles()
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm('确认删除该角色？', '提示', { type: 'warning' })
    await rbacApi.deleteRole(row.id)
    ElMessage.success('删除成功')
    await loadRoles()
  } catch { /**/ }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>