<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" v-permission="'permission:create'" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增权限
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="queryParams.keyword" placeholder="权限名称/编码" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="模块">
          <el-select v-model="queryParams.module" placeholder="全部" clearable>
            <el-option v-for="m in moduleList" :key="m" :label="m" :value="m" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 按模块分组显示 -->
      <div v-loading="loading">
        <el-collapse v-model="activeModules">
          <el-collapse-item v-for="(permissions, moduleName) in filteredPermissions" :key="moduleName" :name="moduleName">
            <template #title>
              <span class="module-title">{{ moduleName }}</span>
              <el-tag size="small" type="info" class="module-count">{{ permissions.length }}</el-tag>
            </template>
            <el-table :data="permissions" :show-header="true" size="small">
              <el-table-column prop="code" label="权限编码" min-width="150" />
              <el-table-column prop="name" label="权限名称" min-width="120" />
              <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
              <el-table-column prop="createdAt" label="创建时间" width="170" />
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                  <el-button link type="primary" v-permission="'permission:update'" @click="handleEdit(row)">编辑</el-button>
                  <el-button link type="danger" v-permission="'permission:delete'" @click="handleDelete(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
        <el-empty v-if="Object.keys(filteredPermissions).length === 0" description="暂无数据" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="formData.code" placeholder="如: user:create" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="所属模块" prop="module">
          <el-select v-model="formData.module" placeholder="请选择或输入模块" filterable allow-create clearable style="width: 100%">
            <el-option v-for="m in moduleList" :key="m" :label="m" :value="m" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  getPermissionsByModule,
  createPermission,
  updatePermission,
  deletePermission,
  type Permission
} from '@/api/permission'

const loading = ref(false)
const permissionsByModule = ref<Record<string, Permission[]>>({})
const activeModules = ref<string[]>([])

const queryParams = reactive({
  keyword: '',
  module: ''
})

// 模块列表
const moduleList = computed(() => Object.keys(permissionsByModule.value))

// 过滤后的权限
const filteredPermissions = computed(() => {
  const result: Record<string, Permission[]> = {}
  for (const [moduleName, permissions] of Object.entries(permissionsByModule.value)) {
    // 模块过滤
    if (queryParams.module && moduleName !== queryParams.module) continue
    
    // 关键词过滤
    const filtered = permissions.filter(p => {
      if (!queryParams.keyword) return true
      const keyword = queryParams.keyword.toLowerCase()
      return p.name.toLowerCase().includes(keyword) || p.code.toLowerCase().includes(keyword)
    })
    
    if (filtered.length > 0) {
      result[moduleName] = filtered
    }
  }
  return result
})

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑权限' : '新增权限')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

const formData = reactive({
  id: 0,
  code: '',
  name: '',
  module: '',
  description: ''
})

const formRules: FormRules = {
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-z_:]+$/, message: '只能包含小写字母、下划线和冒号', trigger: 'blur' }
  ],
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }]
}

const fetchData = async () => {
  loading.value = true
  try {
    const res = await getPermissionsByModule()
    permissionsByModule.value = res.data
    // 默认展开所有模块
    activeModules.value = Object.keys(res.data)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 搜索时展开所有匹配的模块
  activeModules.value = Object.keys(filteredPermissions.value)
}

const handleReset = () => {
  queryParams.keyword = ''
  queryParams.module = ''
  activeModules.value = Object.keys(permissionsByModule.value)
}

const resetForm = () => {
  formData.id = 0
  formData.code = ''
  formData.name = ''
  formData.module = ''
  formData.description = ''
  formRef.value?.resetFields()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: Permission) => {
  isEdit.value = true
  formData.id = row.id
  formData.code = row.code
  formData.name = row.name
  formData.module = row.module || ''
  formData.description = row.description || ''
  dialogVisible.value = true
}

const handleSubmit = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    if (isEdit.value) {
      await updatePermission(formData.id, {
        name: formData.name,
        module: formData.module || undefined,
        description: formData.description || undefined
      })
      ElMessage.success('更新成功')
    } else {
      await createPermission({
        code: formData.code,
        name: formData.name,
        module: formData.module || undefined,
        description: formData.description || undefined
      })
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchData()
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = async (row: Permission) => {
  try {
    await ElMessageBox.confirm(`确定要删除权限 "${row.name}" 吗？删除后相关角色将失去此权限。`, '提示', { type: 'warning' })
    await deletePermission(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消删除
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 16px;
}

.module-title {
  font-weight: bold;
  margin-right: 8px;
}

.module-count {
  margin-left: 8px;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 0;
}
</style>
