<template>
  <div class="role-permissions">
    <div class="page-header">
      <h1>角色权限管理</h1>
      <a-button type="primary" @click="showCreateModal">
        <PlusOutlined />
        新增角色
      </a-button>
    </div>

    <!-- 角色列表 -->
    <a-card title="角色列表" :bordered="false">
      <template #extra>
        <a-input-search
          v-model="searchText"
          placeholder="搜索角色名称"
          style="width: 200px"
          @search="handleSearch"
        />
      </template>

      <a-table
        :columns="columns"
        :data-source="roles"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-switch
              :checked="record.status"
              @change="(checked) => handleStatusChange(record, checked)"
              :checked-children="'启用'"
              :un-checked-children="'禁用'"
              :loading="record.statusChanging"
            />
          </template>
          
          
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="editRole(record)">
                编辑
              </a-button>
              <a-dropdown>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="menu" @click="manageMenuPermissions(record)">
                      菜单权限
                    </a-menu-item>
                    <a-menu-item key="function" @click="manageFunctionPermissions(record)">
                      功能权限
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button type="link" size="small">
                  权限管理 <DownOutlined />
                </a-button>
              </a-dropdown>
              <a-popconfirm
                title="确定要删除这个角色吗？"
                @confirm="deleteRole(record.id)"
              >
                <a-button type="link" size="small" danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑角色模态框 -->
    <a-modal
      :open="modalVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      @update:open="modalVisible = $event"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="角色名称" name="name">
          <a-input :value="formData.name" placeholder="请输入角色名称" @update:value="formData.name = $event" />
        </a-form-item>
        
        <a-form-item label="角色描述" name="description">
          <a-textarea :value="formData.description" placeholder="请输入角色描述" @update:value="formData.description = $event" />
        </a-form-item>
        
        <a-form-item label="状态" name="status">
          <a-switch :checked="formData.status" @update:checked="formData.status = $event" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 菜单权限管理模态框 -->
    <a-modal
      :open="menuPermissionModalVisible"
      title="菜单权限管理"
      width="800px"
      @ok="handleMenuPermissionOk"
      @cancel="handleMenuPermissionCancel"
      @update:open="menuPermissionModalVisible = $event"
    >
      <div class="permission-container">
        <div class="permission-header">
          <h3>角色：{{ currentRole?.name }}</h3>
          <a-space>
            <a-button @click="checkAllMenus">全选</a-button>
            <a-button @click="uncheckAllMenus">全不选</a-button>
          </a-space>
        </div>
        
        <a-tree
          :checkedKeys="menuCheckedKeys"
          :tree-data="menuTree"
          :field-names="{ children: 'children', title: 'name', key: 'id' }"
          checkable
          :check-strictly="false"
          @check="handleMenuTreeCheck"
          @update:checkedKeys="menuCheckedKeys = $event"
        />
      </div>
    </a-modal>

    <!-- 功能权限管理模态框 -->
    <a-modal
      :open="functionPermissionModalVisible"
      title="功能权限管理"
      width="1000px"
      @ok="handleFunctionPermissionOk"
      @cancel="handleFunctionPermissionCancel"
      @update:open="functionPermissionModalVisible = $event"
    >
      <div class="permission-container">
        <div class="permission-header">
          <h3>角色：{{ currentRole?.name }}</h3>
          <a-space>
            <a-select
              :value="selectedModule"
              placeholder="选择模块"
              style="width: 150px"
              @update:value="selectedModule = $event"
              @change="filterPermissions"
            >
              <a-select-option value="">全部模块</a-select-option>
              <a-select-option v-for="module in permissionModules" :key="module" :value="module">
                {{ module }}
              </a-select-option>
            </a-select>
            <a-button @click="checkAllFunctions">全选</a-button>
            <a-button @click="uncheckAllFunctions">全不选</a-button>
          </a-space>
        </div>
        
        <div class="function-permissions">
          <a-collapse v-model="activeModules">
            <a-collapse-panel v-for="(permissions, module) in filteredPermissions" :key="module" :header="module">
              <a-checkbox-group
                :value="functionCheckedKeys"
                @update:value="functionCheckedKeys = $event"
                @change="handleFunctionCheck"
              >
                <a-row :gutter="[16, 8]">
                  <a-col v-for="permission in permissions" :key="permission.id" :span="8">
                    <a-checkbox :value="permission.id">
                      {{ permission.permission_name }}
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { PlusOutlined, DownOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { rolePermissionService } from '../utils/dataService'

// 响应式数据
const loading = ref(false)
const searchText = ref('')
const roles = ref([])
const menuTree = ref([])
const menuCheckedKeys = ref([])
const functionCheckedKeys = ref([])
const allPermissions = ref([])
const permissionModules = ref([])
const selectedModule = ref('')
const activeModules = ref([])

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 模态框状态
const modalVisible = ref(false)
const menuPermissionModalVisible = ref(false)
const functionPermissionModalVisible = ref(false)
const isEdit = ref(false)
const currentRole = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  description: '',
  status: true
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ]
}

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '角色名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 计算属性
const filteredPermissions = computed(() => {
  if (!selectedModule.value) {
    return allPermissions.value.reduce((acc, permission) => {
      const module = permission.module;
      if (!acc[module]) {
        acc[module] = [];
      }
      acc[module].push(permission);
      return acc;
    }, {});
  }
  
  return allPermissions.value
    .filter(permission => permission.module === selectedModule.value)
    .reduce((acc, permission) => {
      const module = permission.module;
      if (!acc[module]) {
        acc[module] = [];
      }
      acc[module].push(permission);
      return acc;
    }, {});
});

// 加载角色列表
const loadRoles = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchText.value
    }
    
    const response = await rolePermissionService.getRoles(params)
    roles.value = response.list || []
    pagination.total = response.pagination?.total || 0
  } catch (error) {
    console.error('加载角色列表失败:', error)
    message.error('加载角色列表失败')
  } finally {
    loading.value = false
  }
}

// 加载菜单树
const loadMenuTree = async () => {
  try {
    const response = await rolePermissionService.getPermissionTree()
    
    // 转换字段名以匹配前端组件期望的格式
    const convertMenuFields = (menu) => {
      return {
        id: menu.id,
        name: menu.menu_name || menu.name, // 映射 menu_name 到 name
        key: menu.id,
        children: menu.children ? menu.children.map(convertMenuFields) : []
      }
    }
    
    menuTree.value = response ? response.map(convertMenuFields) : []
  } catch (error) {
    console.error('加载菜单树失败:', error)
    message.error('加载菜单树失败')
  }
}

// 加载所有权限
const loadAllPermissions = async () => {
  try {
    const response = await rolePermissionService.getAllPermissions()
    allPermissions.value = response.data?.permissions || []
  } catch (error) {
    console.error('加载权限列表失败:', error)
    message.error('加载权限列表失败')
  }
}

// 加载权限模块列表
const loadPermissionModules = async () => {
  try {
    const response = await rolePermissionService.getPermissionModules()
    permissionModules.value = response.data || []
    // 默认展开所有模块
    activeModules.value = permissionModules.value
  } catch (error) {
    console.error('加载权限模块失败:', error)
    message.error('加载权限模块失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadRoles()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadRoles()
}

// 显示创建模态框
const showCreateModal = () => {
  isEdit.value = false
  modalVisible.value = true
  resetForm()
}

// 编辑角色
const editRole = (record) => {
  isEdit.value = true
  modalVisible.value = true
  Object.assign(formData, record)
}

// 管理菜单权限
const manageMenuPermissions = async (record) => {
  currentRole.value = record
  menuPermissionModalVisible.value = true
  
  try {
    // 加载角色的菜单权限
    console.log('🔍 [菜单权限加载] 角色ID:', record.id)
    console.log('🔍 [菜单权限加载] 调用API: /role-permissions/public/roles/' + record.id + '/menus')
    
    const response = await rolePermissionService.getRoleMenuPermissions(record.id)
    console.log('🔍 [菜单权限加载] API响应:', response)
    console.log('🔍 [菜单权限加载] 权限数组:', response.data?.permissions)
    console.log('🔍 [菜单权限加载] 权限数组长度:', response.data?.permissions?.length)
    
    const permissionIds = response.data?.permissions?.map(p => p.id) || []
    console.log('🔍 [菜单权限加载] 权限ID数组:', permissionIds)
    console.log('🔍 [菜单权限加载] 权限ID数组长度:', permissionIds.length)
    
    menuCheckedKeys.value = permissionIds
    console.log('🔍 [菜单权限加载] 设置后的menuCheckedKeys:', menuCheckedKeys.value)
  } catch (error) {
    console.error('加载角色菜单权限失败:', error)
    message.error('加载角色菜单权限失败')
  }
}

// 管理功能权限
const manageFunctionPermissions = async (record) => {
  currentRole.value = record
  functionPermissionModalVisible.value = true
  
  try {
    // 加载角色的功能权限
    const response = await rolePermissionService.getRoleFunctionPermissions(record.id)
    functionCheckedKeys.value = response.data?.permissions?.map(p => p.id) || []
  } catch (error) {
    console.error('加载角色功能权限失败:', error)
    message.error('加载角色功能权限失败')
  }
}

// 删除角色
const deleteRole = async (id) => {
  try {
    await rolePermissionService.deleteRole(id)
    message.success('删除成功')
    loadRoles()
  } catch (error) {
    console.error('删除角色失败:', error)
    message.error('删除角色失败')
  }
}

// 模态框确定
const handleModalOk = async () => {
  try {
    if (isEdit.value) {
      await rolePermissionService.updateRole(formData.id, formData)
      message.success('更新成功')
    } else {
      await rolePermissionService.createRole(formData)
      message.success('创建成功')
    }
    
    modalVisible.value = false
    loadRoles()
  } catch (error) {
    console.error('保存角色失败:', error)
    message.error('保存角色失败')
  }
}

// 模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 菜单权限管理确定
const handleMenuPermissionOk = async () => {
  try {
    console.log('🔍 [菜单权限保存] 角色ID:', currentRole.value.id)
    console.log('🔍 [菜单权限保存] 要保存的权限ID:', menuCheckedKeys.value)
    
    await rolePermissionService.setRoleMenuPermissions(currentRole.value.id, {
      menuIds: menuCheckedKeys.value
    })
    
    console.log('🔍 [菜单权限保存] 保存成功')
    message.success('菜单权限设置成功')
    menuPermissionModalVisible.value = false
    loadRoles()
  } catch (error) {
    console.error('设置菜单权限失败:', error)
    message.error('设置菜单权限失败')
  }
}

// 菜单权限管理取消
const handleMenuPermissionCancel = () => {
  menuPermissionModalVisible.value = false
  menuCheckedKeys.value = []
}

// 功能权限管理确定
const handleFunctionPermissionOk = async () => {
  try {
    await rolePermissionService.setRoleFunctionPermissions(currentRole.value.id, {
      permissionIds: functionCheckedKeys.value
    })
    message.success('功能权限设置成功')
    functionPermissionModalVisible.value = false
    loadRoles()
  } catch (error) {
    console.error('设置功能权限失败:', error)
    message.error('设置功能权限失败')
  }
}

// 功能权限管理取消
const handleFunctionPermissionCancel = () => {
  functionPermissionModalVisible.value = false
  functionCheckedKeys.value = []
}

// 菜单树形选择变化
const handleMenuTreeCheck = (checkedKeysValue) => {
  menuCheckedKeys.value = checkedKeysValue
}

// 功能权限选择变化
const handleFunctionCheck = (checkedValues) => {
  functionCheckedKeys.value = checkedValues
}

// 过滤权限
const filterPermissions = () => {
  // 重新计算过滤后的权限
}

// 菜单权限全选
const checkAllMenus = () => {
  const getAllKeys = (tree) => {
    let keys = []
    tree.forEach(node => {
      keys.push(node.id)
      if (node.children) {
        keys = keys.concat(getAllKeys(node.children))
      }
    })
    return keys
  }
  menuCheckedKeys.value = getAllKeys(menuTree.value)
}

// 菜单权限全不选
const uncheckAllMenus = () => {
  menuCheckedKeys.value = []
}

// 功能权限全选
const checkAllFunctions = () => {
  functionCheckedKeys.value = allPermissions.value.map(p => p.id)
}

// 功能权限全不选
const uncheckAllFunctions = () => {
  functionCheckedKeys.value = []
}

// 处理角色状态切换
const handleStatusChange = async (record, checked) => {
  try {
    // 设置加载状态
    record.statusChanging = true
    
    await rolePermissionService.toggleRoleStatus(record.id, { status: checked })
    
    // 更新本地状态
    record.status = checked
    
    message.success(`角色${checked ? '启用' : '禁用'}成功`)
  } catch (error) {
    console.error('切换角色状态失败:', error)
    message.error('切换角色状态失败')
    
    // 恢复原状态
    record.status = !checked
  } finally {
    record.statusChanging = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    description: '',
    status: true
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadRoles()
  loadMenuTree()
  loadAllPermissions()
  loadPermissionModules()
})
</script>

<style scoped>
.role-permissions {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.permission-container {
  max-height: 400px;
  overflow-y: auto;
}

.permission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.permission-header h3 {
  margin: 0;
  color: #1890ff;
}

.function-permissions {
  max-height: 500px;
  overflow-y: auto;
}

.function-permissions .ant-collapse {
  border: none;
}

.function-permissions .ant-collapse-item {
  margin-bottom: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.function-permissions .ant-collapse-header {
  background: #fafafa;
  font-weight: 500;
}
</style>

