<template>
  <div class="user-role-manage">
    <el-card>
      <template #header>
        <div class="header">
          <span>用户角色管理</span>
        </div>
      </template>
      
      <el-form :inline="true" class="search-form">
        <el-form-item>
          <el-input v-model="searchUsername" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="userList" style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="是否超级管理员">
          <template #default="scope">
            <el-tag :type="scope.row.isSuperAdmin === 1 ? 'danger' : 'info'">
              {{ scope.row.isSuperAdmin === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button @click="handleSetUserRole(scope.row)" type="primary" size="small">
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        class="pagination"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handleCurrentChange"
      />
    </el-card>
    
    <!-- 角色分配对话框 -->
    <el-dialog v-model="roleDialogVisible" title="分配角色">
      <div v-if="currentUser">
        <p>当前用户：{{ currentUser.username }}</p>
        <el-checkbox-group v-model="selectedRoleIds">
          <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUserRoles">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getRoleList } from '@/api/role'
import { getAdminRoles, updateAdminRoles, getUserList } from '@/api/user'

export default {
  name: 'UserRoleManage',
  setup() {
    // 用户列表数据
    const loading = ref(false)
    const userList = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const searchUsername = ref('')
    
    // 角色数据
    const roleList = ref([])
    const roleDialogVisible = ref(false)
    const currentUser = ref(null)
    const selectedRoleIds = ref([])
    
    // 获取用户列表
    const fetchUserList = async () => {
      loading.value = true
      try {
        const res = await getUserList({
          page: currentPage.value,
          size: pageSize.value,
          username: searchUsername.value
        })
        userList.value = res.data || []
        total.value = res.total || 0
      } catch (error) {
        console.error('获取用户列表失败', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取角色列表
    const fetchRoleList = async () => {
      try {
        const res = await getRoleList()
        roleList.value = res.data || []
      } catch (error) {
        console.error('获取角色列表失败', error)
        ElMessage.error('获取角色列表失败')
      }
    }
    
    // 获取用户角色
    const fetchUserRoles = async (adminId) => {
      try {
        const res = await getAdminRoles(adminId)
        selectedRoleIds.value = res.data || []
      } catch (error) {
        console.error('获取用户角色失败', error)
        ElMessage.error('获取用户角色失败')
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchUserList()
    }
    
    // 页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchUserList()
    }
    
    // 设置用户角色
    const handleSetUserRole = async (user) => {
      currentUser.value = user
      await fetchRoleList()
      await fetchUserRoles(user.id)
      roleDialogVisible.value = true
    }
    
    // 保存用户角色
    const saveUserRoles = async () => {
      if (!currentUser.value) return
      
      try {
        await updateAdminRoles(currentUser.value.id, selectedRoleIds.value)
        ElMessage.success('角色分配成功')
        roleDialogVisible.value = false
      } catch (error) {
        console.error('角色分配失败', error)
        ElMessage.error('角色分配失败')
      }
    }
    
    onMounted(() => {
      fetchUserList()
    })
    
    return {
      loading,
      userList,
      total,
      currentPage,
      pageSize,
      searchUsername,
      roleList,
      roleDialogVisible,
      currentUser,
      selectedRoleIds,
      handleSearch,
      handleCurrentChange,
      handleSetUserRole,
      saveUserRoles
    }
  }
}
</script>

<style scoped>
.user-role-manage {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-form {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 