<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)拥有全部权限且不可修改。为其他角色勾选其可用的后台权限；可创建自定义角色并赋权。</p>
      <el-table v-loading="loading" :data="list" border stripe>
        <el-table-column prop="role_name" label="角色" width="160">
          <template #default="{ row }">
            <el-input v-if="row.is_custom" v-model="row.role_name" size="small" placeholder="角色名" style="width: 120px" />
            <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="400">
          <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-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="500px">
      <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="权限">
          <div class="perm-checkboxes">
            <el-checkbox v-for="p in allPermissions" :key="p.key" v-model="createForm._checked[p.key]">
              {{ p.name }}
            </el-checkbox>
          </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: {} })

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)
      const payload = { permissions }
      if (row.is_custom && row.role_name) payload.role_name = row.role_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) => {
    createForm._checked[p.key] = 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[p.key]).map((p) => p.key)
    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;
}
.perm-checkboxes {
  display: flex;
  flex-wrap: wrap;
}
</style>
