<template>
  <MainLayout>
    <div class="permission-management">
      <el-tabs v-model="activeTab" type="border-card">
          <!-- 角色管理 -->
          <el-tab-pane label="角色管理" name="roles">
            <div class="toolbar">
              <el-button type="primary" @click="handleCreateRole" :disabled="!isAdmin">
                <el-icon><Plus /></el-icon>
                创建角色
              </el-button>
            </div>
            
            <el-table :data="roles" style="width: 100%" v-loading="loading">
              <el-table-column prop="name" label="角色名称" width="150" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="权限数量" width="120">
                <template #default="scope">
                  {{ scope.row.permissions?.length || 0 }}
                </template>
              </el-table-column>
              <el-table-column label="用户数量" width="120">
                <template #default="scope">
                  {{ scope.row.user_count || 0 }}
                </template>
              </el-table-column>
              <el-table-column label="系统角色" width="100">
                <template #default="scope">
                  <el-tag v-if="scope.row.is_system" type="info" size="small">是</el-tag>
                  <span v-else>否</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="handleEditRole(scope.row)" :disabled="scope.row.is_system || !isAdmin">
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="handleDeleteRole(scope.row)" :disabled="scope.row.is_system || !isAdmin">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          
          <!-- 权限列表 -->
          <el-tab-pane label="权限列表" name="permissions">
            <div class="filter-bar">
              <el-select v-model="permissionFilter.resource" placeholder="资源类型" clearable style="width: 150px">
                <el-option label="全部" value="" />
                <el-option label="工作流" value="workflow" />
                <el-option label="Agent" value="agent" />
                <el-option label="执行" value="execution" />
                <el-option label="数据源" value="data_source" />
                <el-option label="模型配置" value="model_config" />
              </el-select>
              <el-select v-model="permissionFilter.action" placeholder="操作类型" clearable style="width: 150px; margin-left: 10px">
                <el-option label="全部" value="" />
                <el-option label="创建" value="create" />
                <el-option label="查看" value="read" />
                <el-option label="更新" value="update" />
                <el-option label="删除" value="delete" />
                <el-option label="执行" value="execute" />
              </el-select>
            </div>
            
            <el-table :data="filteredPermissions" style="width: 100%" v-loading="permissionsLoading">
              <el-table-column prop="name" label="权限名称" width="200" />
              <el-table-column prop="code" label="权限代码" width="200" />
              <el-table-column prop="resource" label="资源类型" width="120" />
              <el-table-column prop="action" label="操作类型" width="120" />
              <el-table-column prop="description" label="描述" />
            </el-table>
          </el-tab-pane>
          
          <!-- 用户角色分配 -->
          <el-tab-pane label="用户角色" name="user-roles">
            <div class="toolbar">
              <el-input
                v-model="userSearch"
                placeholder="搜索用户"
                style="width: 300px"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            
            <el-table :data="filteredUsers" style="width: 100%" v-loading="usersLoading">
              <el-table-column prop="username" label="用户名" width="150" />
              <el-table-column prop="email" label="邮箱" width="200" />
              <el-table-column label="角色" width="300">
                <template #default="scope">
                  <el-tag
                    v-for="role in scope.row.roles"
                    :key="role.id"
                    style="margin-right: 5px"
                  >
                    {{ role.name }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="handleAssignRoles(scope.row)" :disabled="!isAdmin">
                    分配角色
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
    
      <!-- 角色创建/编辑对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="roleDialogTitle"
      width="600px"
    >
      <el-form :model="roleForm" label-width="100px">
        <el-form-item label="角色名称" required>
          <el-input v-model="roleForm.name" :disabled="editingRole?.is_system" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="权限">
          <el-checkbox-group v-model="roleForm.permission_ids">
            <el-checkbox
              v-for="permission in permissions"
              :key="permission.id"
              :label="permission.id"
            >
              {{ permission.name }} ({{ permission.code }})
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRole" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 用户角色分配对话框 -->
    <el-dialog
      v-model="userRoleDialogVisible"
      title="分配角色"
      width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="用户">
          <el-input :value="selectedUser?.username" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group v-model="userRoleForm.role_ids">
            <el-checkbox
              v-for="role in roles"
              :key="role.id"
              :label="role.id"
            >
              {{ role.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUserRoles" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import api from '@/api'
import MainLayout from '@/components/MainLayout.vue'
import { useUserStore } from '@/stores/user'

const activeTab = ref('roles')
const loading = ref(false)
const permissionsLoading = ref(false)
const usersLoading = ref(false)
const saving = ref(false)

const roles = ref<any[]>([])
const permissions = ref<any[]>([])
const users = ref<any[]>([])

const permissionFilter = ref({
  resource: '',
  action: ''
})

const userSearch = ref('')

const roleDialogVisible = ref(false)
const roleDialogTitle = ref('创建角色')
const editingRole = ref<any>(null)
const roleForm = ref({
  name: '',
  description: '',
  permission_ids: [] as string[]
})

const userRoleDialogVisible = ref(false)
const selectedUser = ref<any>(null)
const userRoleForm = ref({
  role_ids: [] as string[]
})

const userStore = useUserStore()
const isAdmin = computed(() => userStore.user?.role === 'admin')

// 过滤权限
const filteredPermissions = computed(() => {
  let result = permissions.value
  
  if (permissionFilter.value.resource) {
    result = result.filter(p => p.resource === permissionFilter.value.resource)
  }
  
  if (permissionFilter.value.action) {
    result = result.filter(p => p.action === permissionFilter.value.action)
  }
  
  return result
})

// 过滤用户
const filteredUsers = computed(() => {
  if (!userSearch.value) {
    return users.value
  }
  
  const search = userSearch.value.toLowerCase()
  return users.value.filter(u => 
    u.username.toLowerCase().includes(search) ||
    u.email.toLowerCase().includes(search)
  )
})

// 加载角色列表
const loadRoles = async () => {
  loading.value = true
  try {
    const response = await api.get('/api/v1/permissions/roles')
    roles.value = response.data
  } catch (error: any) {
    console.error('加载角色失败:', error)
    ElMessage.error('加载角色失败')
  } finally {
    loading.value = false
  }
}

// 加载权限列表
const loadPermissions = async () => {
  permissionsLoading.value = true
  try {
    const response = await api.get('/api/v1/permissions/permissions')
    permissions.value = response.data
  } catch (error: any) {
    console.error('加载权限失败:', error)
    ElMessage.error('加载权限失败')
  } finally {
    permissionsLoading.value = false
  }
}

// 加载用户列表
const loadUsers = async () => {
  usersLoading.value = true
  try {
    const response = await api.get('/api/v1/permissions/users')
    users.value = response.data || []
  } catch (error: any) {
    console.error('加载用户失败:', error)
    ElMessage.error('加载用户失败')
  } finally {
    usersLoading.value = false
  }
}

// 创建角色
const handleCreateRole = () => {
  editingRole.value = null
  roleForm.value = {
    name: '',
    description: '',
    permission_ids: []
  }
  roleDialogTitle.value = '创建角色'
  roleDialogVisible.value = true
}

// 编辑角色
const handleEditRole = (role: any) => {
  editingRole.value = role
  roleForm.value = {
    name: role.name,
    description: role.description || '',
    permission_ids: role.permissions?.map((p: any) => p.id) || []
  }
  roleDialogTitle.value = '编辑角色'
  roleDialogVisible.value = true
}

// 保存角色
const handleSaveRole = async () => {
  if (!roleForm.value.name) {
    ElMessage.warning('请输入角色名称')
    return
  }
  
  saving.value = true
  try {
    if (editingRole.value) {
      // 更新角色
      await api.put(`/api/v1/permissions/roles/${editingRole.value.id}`, {
        name: roleForm.value.name,
        description: roleForm.value.description,
        permission_ids: roleForm.value.permission_ids
      })
      ElMessage.success('角色更新成功')
    } else {
      // 创建角色
      await api.post('/api/v1/permissions/roles', {
        name: roleForm.value.name,
        description: roleForm.value.description,
        permission_ids: roleForm.value.permission_ids
      })
      ElMessage.success('角色创建成功')
    }
    
    roleDialogVisible.value = false
    await loadRoles()
  } catch (error: any) {
    console.error('保存角色失败:', error)
    ElMessage.error(error.response?.data?.detail || '保存角色失败')
  } finally {
    saving.value = false
  }
}

// 删除角色
const handleDeleteRole = async (role: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？`,
      '确认删除',
      {
        type: 'warning'
      }
    )
    
    await api.delete(`/api/v1/permissions/roles/${role.id}`)
    ElMessage.success('角色删除成功')
    await loadRoles()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error(error.response?.data?.detail || '删除角色失败')
    }
  }
}

// 分配角色
const handleAssignRoles = async (user: any) => {
  selectedUser.value = user
  userRoleForm.value = {
    role_ids: user.roles?.map((r: any) => r.id) || []
  }
  userRoleDialogVisible.value = true
}

// 保存用户角色
const handleSaveUserRoles = async () => {
  if (!selectedUser.value) return
  
  saving.value = true
  try {
    await api.post(`/api/v1/permissions/users/${selectedUser.value.id}/roles`, userRoleForm.value.role_ids)
    ElMessage.success('角色分配成功')
    userRoleDialogVisible.value = false
    await loadUsers()
  } catch (error: any) {
    console.error('分配角色失败:', error)
    ElMessage.error(error.response?.data?.detail || '分配角色失败')
  } finally {
    saving.value = false
  }
}

onMounted(async () => {
  await loadRoles()
  await loadPermissions()
  await loadUsers()
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.filter-bar {
  margin-bottom: 20px;
}
</style>
