<template>
  <div class="admin-users">
    <!-- 搜索和筛选区域 -->
    <div class="filter-area">
      <el-form :inline="true" :model="searchForm" class="filter-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="用户名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="全部角色" clearable>
            <el-option label="普通用户" :value="1" />
            <el-option label="管理员" :value="2" />
            <el-option label="超级管理员" :value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="冻结" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetForm">
            <el-icon><RefreshLeft /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        border
        stripe
        row-key="id"
      >
        <el-table-column type="index" width="60" align="center" label="序号" />
        
        <el-table-column label="用户信息" min-width="180">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="40" :src="row.avatar" />
              <div class="user-meta">
                <div class="username">{{ row.username }}</div>
                <div class="user-id">ID: {{ row.id }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="统计数据" width="240">
          <template #default="{ row }">
            <div class="user-stats">
              <span title="发帖"><el-icon><Document /></el-icon> {{ row.postCount || 0 }}</span>
              <span title="评论"><el-icon><ChatDotRound /></el-icon> {{ row.commentCount || 0 }}</span>
              <span title="粉丝"><el-icon><User /></el-icon> {{ row.followerCount || 0 }}</span>
              <span title="积分"><el-icon><Medal /></el-icon> {{ row.integral || 0 }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="注册时间" width="180" sortable />
        
        <el-table-column label="角色" width="120" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.role === 1" type="info">普通用户</el-tag>
            <el-tag v-else-if="row.role === 2" type="warning">管理员</el-tag>
            <el-tag v-else-if="row.role === 3" type="danger">超级管理员</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status === 1" type="success">正常</el-tag>
            <el-tag v-else-if="row.status === 2" type="danger">冻结</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status === 1" size="small" type="danger" @click="handleFreezeUser(row)">
              冻结账号
            </el-button>
            <el-button v-if="row.status === 2" size="small" type="success" @click="handleUnfreezeUser(row)">
              解冻账号
            </el-button>
            
            <el-dropdown trigger="click" @command="(cmd) => handleRoleChange(cmd, row)">
              <el-button size="small" type="primary">
                设置角色 <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="1" :disabled="row.role === 1">普通用户</el-dropdown-item>
                  <el-dropdown-item :command="2" :disabled="row.role === 2">管理员</el-dropdown-item>
                  <el-dropdown-item :command="3" :disabled="row.role === 3 || currentUserRole !== 3">超级管理员</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { Search, RefreshLeft, Document, ChatDotRound, User, Medal, ArrowDown } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores/user.js';
import axios from 'axios';

const userStore = useUserStore();
const currentUserRole = computed(() => userStore.userInfo?.role || 1);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  role: null,
  status: null
});

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

// 数据加载状态
const loading = ref(false);

// 用户列表
const userList = ref([]);

// 加载用户列表
const loadUsers = async () => {
  try {
    loading.value = true;
    const response = await axios.get('/api/admin/users', {
      params: {
        page: pagination.page,
        size: pagination.size,
        keyword: searchForm.keyword || null,
        role: searchForm.role || null,
        status: searchForm.status || null
      }
    });
    
    if (response.data.code === 200) {
      const data = response.data.data;
      userList.value = data.records;
      pagination.total = data.total;
    } else {
      ElMessage.error(response.data.msg || '加载用户列表失败');
    }
  } catch (error) {
    console.error('加载用户列表失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadUsers();
};

// 重置表单
const resetForm = () => {
  searchForm.keyword = '';
  searchForm.role = null;
  searchForm.status = null;
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size;
  loadUsers();
};

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page;
  loadUsers();
};

// 冻结用户
const handleFreezeUser = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要冻结该用户吗？冻结后用户将无法登录系统',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await axios.put(`/api/admin/users/${row.id}/status`, null, {
      params: { status: 2 }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('用户已冻结');
      loadUsers();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('冻结用户失败:', error);
      ElMessage.error('网络错误，请稍后重试');
    }
  }
};

// 解冻用户
const handleUnfreezeUser = async (row) => {
  try {
    const response = await axios.put(`/api/admin/users/${row.id}/status`, null, {
      params: { status: 1 }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('用户已解冻');
      loadUsers();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('解冻用户失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 修改用户角色
const handleRoleChange = async (role, row) => {
  if (role === row.role) return;
  
  try {
    await ElMessageBox.confirm(
      `确定要将该用户角色修改为${role === 1 ? '普通用户' : role === 2 ? '管理员' : '超级管理员'}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await axios.put(`/api/admin/users/${row.id}/role`, null, {
      params: { role }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('用户角色已修改');
      loadUsers();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改用户角色失败:', error);
      ElMessage.error('网络错误，请稍后重试');
    }
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.admin-users {
  width: 100%;
}

.filter-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-meta {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  font-size: 14px;
  color: #333;
}

.user-id {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.user-stats {
  display: flex;
  gap: 15px;
}

.user-stats span {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.user-stats .el-icon {
  margin-right: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格响应式调整 */
@media screen and (max-width: 1200px) {
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
}
</style> 