<template>
  <div class="role-permissions">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色权限管理</span>
          <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
        </div>
      </template>
      <p class="tip">超级管理员(9527)拥有全部权限且不可修改。为其他角色勾选其可用的后台权限。</p>
      <el-table v-loading="loading" :data="list" border stripe>
        <el-table-column prop="role_name" label="角色" width="140" />
        <el-table-column prop="role_id" label="role_id" width="100" />
        <el-table-column label="权限">
          <template #default="{ row }">
            <span v-if="row.role_id === 9527" class="perm-all">（全部权限，不可修改）</span>
            <div v-else class="perm-checkboxes">
              <el-checkbox
                v-for="p in allPermissions"
                :key="p.key"
                v-model="row._checked[p.key]"
                style="margin-right: 16px; margin-bottom: 8px"
              >
                {{ p.name }}
              </el-checkbox>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getRolePermissionsList, updateRolePermissions } from '../../api/admin'

const list = ref([])
const allPermissions = ref([])
const loading = ref(false)
const saving = ref(false)

function buildChecked(permissions) {
  const o = {}
  allPermissions.value.forEach((p) => {
    o[p.key] = permissions.includes(p.key)
  })
  return o
}

const fetchList = async () => {
  loading.value = true
  try {
    const res = await getRolePermissionsList()
    allPermissions.value = res.all_permissions || []
    list.value = (res.list || []).map((r) => ({
      ...r,
      _checked: buildChecked(r.permissions || [])
    }))
  } catch (e) {
    ElMessage.error(e.message)
  } finally {
    loading.value = false
  }
}

const handleSave = async () => {
  saving.value = true
  try {
    for (const row of list.value) {
      if (row.role_id === 9527) continue
      const permissions = allPermissions.value.filter((p) => row._checked[p.key]).map((p) => p.key)
      await updateRolePermissions(row.role_id, { permissions })
    }
    ElMessage.success('保存成功')
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  } finally {
    saving.value = false
  }
}

onMounted(fetchList)
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tip {
  color: #666;
  font-size: 13px;
  margin-bottom: 16px;
}
.perm-checkboxes {
  display: flex;
  flex-wrap: wrap;
}
</style>
