<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" v-permission="'role: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.status" placeholder="全部" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </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>

      <!-- 表格 -->
      <el-table :data="roleList" v-loading="loading">
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="code" label="角色编码" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="170" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" v-permission="'role:update'" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" v-permission="'role:assign_menu'" @click="handleAssignMenu(row)">分配菜单</el-button>
            <el-button link type="primary" v-permission="'role:assign_permission'" @click="handleAssignPermission(row)">分配权限</el-button>
            <el-button link type="danger" v-permission="'role:delete'" @click="handleDelete(row)" :disabled="row.code === 'super_admin'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchData"
        @current-change="fetchData"
        class="pagination"
      />
    </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="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色编码" :disabled="isEdit" />
        </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-item label="排序" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </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>

    <!-- 分配菜单对话框 -->
    <el-dialog v-model="menuDialogVisible" title="分配菜单" width="500px">
      <el-tree
        ref="menuTreeRef"
        :data="menuTree"
        :props="{ label: 'name', children: 'children' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedMenuIds"
        :check-strictly="true"
      />
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitMenus" :loading="menuSubmitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="分配权限" width="700px">
      <div class="permission-dialog-content">
        <el-checkbox-group v-model="checkedPermissions">
          <div v-for="group in permissionGroups" :key="group.name" class="permission-group">
            <div class="group-header">
              <el-checkbox 
                :indeterminate="isGroupIndeterminate(group)" 
                :model-value="isGroupAllChecked(group)"
                @change="handleGroupCheckChange(group, $event)"
              >
                <span class="group-title">{{ group.name }}</span>
                <span class="group-count">({{ getGroupCheckedCount(group) }}/{{ group.permissions.length }})</span>
              </el-checkbox>
            </div>
            <div class="group-items">
              <el-checkbox v-for="perm in group.permissions" :key="perm.code" :value="perm.code">
                <span class="perm-name">{{ perm.name }}</span>
                <span class="perm-code">({{ perm.code }})</span>
              </el-checkbox>
            </div>
          </div>
        </el-checkbox-group>
      </div>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPermissions" :loading="permissionSubmitLoading">确定</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 type { ElTree } from 'element-plus'
import {
  getRoleList,
  createRole,
  updateRole,
  deleteRole,
  getRoleMenus,
  assignRoleMenus,
  getRolePermissions,
  assignRolePermissions,
  type Role,
  type RoleQuery
} from '@/api/role'
import { getMenuTree, type MenuTree } from '@/api/menu'
import { getAllPermissions, type Permission } from '@/api/permission'

const loading = ref(false)
const roleList = ref<Role[]>([])
const total = ref(0)

const queryParams = reactive<RoleQuery>({
  keyword: '',
  status: undefined,
  page: 1,
  pageSize: 10
})

// 表单相关
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,
  name: '',
  code: '',
  description: '',
  sortOrder: 0,
  status: 1
})

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

// 菜单分配相关
const menuDialogVisible = ref(false)
const menuTreeRef = ref<InstanceType<typeof ElTree>>()
const menuTree = ref<MenuTree[]>([])
const checkedMenuIds = ref<number[]>([])
const currentRoleId = ref(0)
const menuSubmitLoading = ref(false)

// 权限分配相关
const permissionDialogVisible = ref(false)
const allPermissions = ref<Permission[]>([])
const checkedPermissions = ref<string[]>([])
const permissionSubmitLoading = ref(false)

const permissionGroups = computed(() => {
  const groups: { name: string; permissions: Permission[] }[] = []
  const groupMap = new Map<string, Permission[]>()
  
  allPermissions.value.forEach(p => {
    const moduleName = p.module || '其他'
    if (!groupMap.has(moduleName)) {
      groupMap.set(moduleName, [])
    }
    groupMap.get(moduleName)!.push(p)
  })
  
  groupMap.forEach((permissions, name) => {
    groups.push({ name, permissions })
  })
  
  return groups
})

const fetchData = async () => {
  loading.value = true
  try {
    const res = await getRoleList(queryParams)
    roleList.value = res.data.list
    total.value = res.data.total
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  queryParams.page = 1
  fetchData()
}

const handleReset = () => {
  queryParams.keyword = ''
  queryParams.status = undefined
  queryParams.page = 1
  fetchData()
}

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

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

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

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

  submitLoading.value = true
  try {
    if (isEdit.value) {
      await updateRole(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await createRole(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchData()
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm(`确定要删除角色 "${row.name}" 吗？`, '提示', { type: 'warning' })
    await deleteRole(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消删除
  }
}

const handleAssignMenu = async (row: Role) => {
  currentRoleId.value = row.id
  // 加载菜单树
  if (menuTree.value.length === 0) {
    const res = await getMenuTree()
    menuTree.value = res.data
  }
  // 加载已分配菜单
  const res = await getRoleMenus(row.id)
  checkedMenuIds.value = res.data
  menuDialogVisible.value = true
}

const handleSubmitMenus = async () => {
  menuSubmitLoading.value = true
  try {
    const menuIds = menuTreeRef.value?.getCheckedKeys(false) as number[]
    await assignRoleMenus({ roleId: currentRoleId.value, menuIds })
    ElMessage.success('分配成功')
    menuDialogVisible.value = false
  } finally {
    menuSubmitLoading.value = false
  }
}

const handleAssignPermission = async (row: Role) => {
  currentRoleId.value = row.id
  // 加载所有权限
  if (allPermissions.value.length === 0) {
    const res = await getAllPermissions()
    allPermissions.value = res.data
  }
  // 加载已分配权限
  const res = await getRolePermissions(row.id)
  checkedPermissions.value = res.data
  permissionDialogVisible.value = true
}

const handleSubmitPermissions = async () => {
  permissionSubmitLoading.value = true
  try {
    await assignRolePermissions({ roleId: currentRoleId.value, permissionCodes: checkedPermissions.value })
    ElMessage.success('分配成功')
    permissionDialogVisible.value = false
  } finally {
    permissionSubmitLoading.value = false
  }
}

// 分组全选相关方法
const isGroupAllChecked = (group: { name: string; permissions: Permission[] }) => {
  return group.permissions.every(p => checkedPermissions.value.includes(p.code))
}

const isGroupIndeterminate = (group: { name: string; permissions: Permission[] }) => {
  const checkedCount = group.permissions.filter(p => checkedPermissions.value.includes(p.code)).length
  return checkedCount > 0 && checkedCount < group.permissions.length
}

const getGroupCheckedCount = (group: { name: string; permissions: Permission[] }) => {
  return group.permissions.filter(p => checkedPermissions.value.includes(p.code)).length
}

const handleGroupCheckChange = (group: { name: string; permissions: Permission[] }, checked: boolean) => {
  const groupCodes = group.permissions.map(p => p.code)
  if (checked) {
    // 全选：添加该组所有权限
    const newCodes = groupCodes.filter(code => !checkedPermissions.value.includes(code))
    checkedPermissions.value = [...checkedPermissions.value, ...newCodes]
  } else {
    // 取消全选：移除该组所有权限
    checkedPermissions.value = checkedPermissions.value.filter(code => !groupCodes.includes(code))
  }
}

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;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

.permission-group {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.group-header {
  background-color: #f5f7fa;
  padding: 10px 16px;
  border-bottom: 1px solid #ebeef5;
}

.group-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.group-count {
  color: #909399;
  font-size: 12px;
  margin-left: 4px;
}

.group-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px;
  padding: 12px 16px;
}

.group-items .el-checkbox {
  margin-right: 0;
}

.perm-name {
  color: #303133;
}

.perm-code {
  color: #909399;
  font-size: 12px;
  margin-left: 4px;
}

.permission-dialog-content {
  max-height: 500px;
  overflow-y: auto;
}
</style>
