<template>
  <div class="user-list-container">
    <h2>用户管理</h2>
    
    <!-- 筛选表单 -->
    <!-- <el-card class="filter-card">
      <el-form :model="filterForm" inline label-width="80px">
        <el-form-item label="用户名">
          <el-input
            v-model="filterForm.userName"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input
            v-model="filterForm.phoneNumber"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="部门">
          <el-select
            v-model="filterForm.department"
            placeholder="请选择部门"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="dept in departmentList"
              :key="dept"
              :label="dept"
              :value="dept"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card> -->
    
    <!-- 用户列表表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        stripe
        :empty-text="emptyText"
      >
        <el-table-column prop="userName" label="用户名" width="120"></el-table-column>
        <el-table-column prop="weChatName" label="微信名" width="120"></el-table-column>
        <el-table-column prop="phoneNumber" label="手机号" width="130">
          <template #default="scope">
            <span 
              class="phone-number" 
              @click="scope.row.showFullPhone = !scope.row.showFullPhone" 
              :title="'点击' + (scope.row.showFullPhone ? '隐藏' : '显示') + '完整号码'"
            >
              {{ formatPhoneNumber(scope.row.phoneNumber, scope.row.showFullPhone) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="部门" width="120"></el-table-column>
        <el-table-column prop="firstLoginTime" label="首次登录时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.firstLoginTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="isDisabled" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isDisabled ? 'danger' : 'success'">
              {{ scope.row.isDisabled ? '禁用' : '启用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 移除分页控件 -->
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'
import { formatPhoneNumber, formatDateTime } from '../utils/formatters'

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

// 移除分页数据
// const currentPage = ref(1)
// const pageSize = ref(10)
// const total = ref(0)

// 空状态文本
const emptyText = computed(() => loading.value ? '加载中...' : '暂无数据')

// 筛选表单数据
const filterForm = reactive({
  userName: '',
  phoneNumber: '',
  department: ''
})

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

// 部门列表（用于筛选）
const departmentList = ref([])

// 查询用户列表
const handleQuery = () => {
  fetchUsers()
}

// 重置筛选条件
const handleReset = () => {
  // 重置表单
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  fetchUsers()
}

// 移除分页变化处理
// const handlePageChange = (page) => {
//   currentPage.value = page
//   fetchUsers()
// }

// 切换用户状态（启用/禁用）
const handleToggleStatus = (user) => {
  ElMessage.confirm(
    `确定要${user.isDisabled ? '启用' : '禁用'}用户「${user.userName}」吗？`,
    '状态切换',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      // 这里可以调用API切换用户状态
      // 模拟API调用
      user.isDisabled = !user.isDisabled
      ElMessage.success(`${user.isDisabled ? '禁用' : '启用'}成功`)
    })
    .catch(() => {
      // 取消操作
    })
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    // 构建请求参数
    // const params = {
    //   userName: filterForm.userName,
    //   phoneNumber: filterForm.phoneNumber,
    //   department: filterForm.department
    // }
    
    // 调用API获取用户列表
    const data = await request.get('/Admin/QueryUsers')//, { params })

    // 检查返回数据格式，确保是数组
    const rawData = Array.isArray(data) ? data : data.data || []
    
    // 按首次登录时间排序（最新的用户在前面）
    userList.value = rawData.sort((a, b) => {
      // 使用时间戳进行比较，确保正确排序
      const timeA = new Date(a.firstLoginTime).getTime()
      const timeB = new Date(b.firstLoginTime).getTime()
      return timeB - timeA // 降序排列，最新的用户在前面
    })
    
    // 提取部门列表
    const depts = [...new Set(userList.value.map(user => user.department))]
    departmentList.value = depts.filter(dept => dept)
    
    // 移除分页逻辑
    // total.value = userList.value.length
  } catch (error) {
    ElMessage.error('获取用户列表失败：' + error.message)
    userList.value = []
    // total.value = 0
    departmentList.value = []
  } finally {
    loading.value = false
  }
}

// 页面初始化
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px 0;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

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

/* 手机号样式 */
.phone-number {
  cursor: pointer;
  color: #409eff;
  text-decoration: underline;
}

.phone-number:hover {
  color: #66b1ff;
}

/* 响应式样式 */
@media (max-width: 767px) {
  .user-list-container {
    padding: 6px 0;
  }
  
  .el-form {
    display: flex;
    flex-direction: column;
    align-items: stretch;
  }
  
  .el-form-item {
    margin-bottom: 16px;
  }
  
  .el-input,
  .el-select {
    width: 100% !important;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .el-table-column {
    padding: 8px 0;
  }
  
  .el-button {
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style>
