<template>
  <div class="role-permissions">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色权限管理</span>
          <div>
            <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
            <el-button type="success" @click="showCreate = true">创建角色</el-button>
          </div>
        </div>
      </template>
      <p class="tip">
        超级管理员(9527)拥有全部权限且不可改权限勾选（防误操作）。<strong>超级用户(0)、普通用户(1)</strong>可修改权限与显示名称；自定义角色可删除。
      </p>
      <el-table v-loading="loading" :data="list" border stripe>
        <el-table-column prop="role_name" label="角色" width="200">
          <template #default="{ row }">
            <el-input v-if="row.role_id !== 9527" v-model="row.role_name" size="small" placeholder="显示名称" style="width: 160px" />
            <span v-else>{{ row.role_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="role_id" label="role_id" width="100" />
        <el-table-column label="权限" min-width="480">
          <template #default="{ row }">
            <span v-if="row.role_id === 9527" class="perm-all">（全部权限，不可修改）</span>
            <div v-else class="perm-grid">
              <label v-for="p in allPermissions" :key="permKey(p)" class="perm-item">
                <el-checkbox v-model="row._checked[permKey(p)]" />
                <span class="perm-text">
                  <span class="perm-name">{{ permLabel(p) }}</span>
                  <span class="perm-key">{{ permKey(p) }}</span>
                </span>
              </label>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.is_custom" link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            <span v-else>—</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="showCreate" title="创建角色" width="560px">
      <el-form label-width="90px">
        <el-form-item label="角色名称" required>
          <el-input v-model="createForm.role_name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限">
          <p class="dialog-perm-hint">勾选该角色可访问的后台能力：</p>
          <div class="perm-grid dialog-perm-grid">
            <label v-for="p in allPermissions" :key="permKey(p)" class="perm-item">
              <el-checkbox v-model="createForm._checked[permKey(p)]" />
              <span class="perm-text">
                <span class="perm-name">{{ permLabel(p) }}</span>
                <span class="perm-key">{{ permKey(p) }}</span>
              </span>
            </label>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreate = false">取消</el-button>
        <el-button type="primary" :loading="creating" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const list = ref([])
const allPermissions = ref([])
const loading = ref(false)
const saving = ref(false)
const showCreate = ref(false)
const creating = ref(false)
const createForm = reactive({ role_name: '', _checked: {} })

/** 兼容旧接口大写字段 Key/Name */
function permKey(p) {
  return p?.key || p?.Key || ''
}
function permLabel(p) {
  const k = permKey(p)
  return p?.name || p?.Name || k || '权限'
}

function buildChecked(permissions) {
  const o = {}
  allPermissions.value.forEach((p) => {
    const k = permKey(p)
    if (k) o[k] = (permissions || []).includes(k)
  })
  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[permKey(p)]).map((p) => permKey(p))
      const payload = { permissions }
      const name = (row.role_name || '').trim()
      if (name) payload.role_name = name
      await updateRolePermissions(row.role_id, payload)
    }
    ElMessage.success('保存成功')
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  } finally {
    saving.value = false
  }
}

const resetCreateForm = () => {
  createForm.role_name = ''
  createForm._checked = {}
  allPermissions.value.forEach((p) => {
    const k = permKey(p)
    if (k) createForm._checked[k] = false
  })
}

const handleCreate = async () => {
  const name = (createForm.role_name || '').trim()
  if (!name) {
    ElMessage.warning('请输入角色名称')
    return
  }
  creating.value = true
  try {
    const permissions = allPermissions.value.filter((p) => createForm._checked[permKey(p)]).map((p) => permKey(p))
    await createRole({ role_name: name, permissions })
    ElMessage.success('创建成功')
    showCreate.value = false
    resetCreateForm()
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  } finally {
    creating.value = false
  }
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm('确定删除该角色？删除后使用该角色的用户需重新分配角色。', '提示', { type: 'warning' })
  try {
    await deleteRole(row.role_id)
    ElMessage.success('删除成功')
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  }
}

watch(showCreate, (v) => {
  if (v) resetCreateForm()
})

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;
  line-height: 1.6;
}
.perm-all {
  color: #909399;
  font-size: 13px;
}
.perm-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 20px;
  align-items: flex-start;
}
.dialog-perm-grid {
  max-height: 360px;
  overflow-y: auto;
  padding: 8px 0;
}
.perm-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  cursor: pointer;
  min-width: 200px;
  max-width: 240px;
}
.perm-text {
  display: flex;
  flex-direction: column;
  gap: 2px;
  line-height: 1.35;
}
.perm-name {
  font-size: 13px;
  color: #303133;
}
.perm-key {
  font-size: 11px;
  color: #909399;
  font-family: ui-monospace, monospace;
  word-break: break-all;
}
.dialog-perm-hint {
  margin: 0 0 8px;
  font-size: 12px;
  color: #909399;
}
</style>
