<template>
  <view class="container">
    <view class="toolbar">
      <u-search v-model="keyword" placeholder="搜索用户昵称" @search="onSearch" @clear="onSearch" />
    </view>

    <view class="table-wrap">
      <u-table>
        <u-tr>
          <u-th>用户ID</u-th>
          <u-th>昵称</u-th>
          <u-th>设备数</u-th>
          <u-th>订阅到期</u-th>
          <u-th>注册时间</u-th>
        </u-tr>
        <u-tr v-for="item in users" :key="item.user_id" @click="onDetail(item.user_id)">
          <u-td>{{ item.user_id }}</u-td>
          <u-td>{{ item.nickname || '-' }}</u-td>
          <u-td>{{ item.device_count || 0 }}</u-td>
          <u-td>{{ formatDate(item.subscription_expire) }}</u-td>
          <u-td>{{ formatDate(item.created_at) }}</u-td>
        </u-tr>
      </u-table>
    </view>

    <view class="pagination">
      <u-button size="small" :disabled="page <= 1" @click="onPage(page - 1)">上一页</u-button>
      <text class="page-info">第 {{ page }} 页 / 共 {{ totalPages }} 页</text>
      <u-button size="small" :disabled="page >= totalPages" @click="onPage(page + 1)">下一页</u-button>
    </view>
  </view>
</template>

<script>
import { get } from '../../utils/request'

export default {
  data() {
    return {
      users: [],
      total: 0,
      page: 1,
      pageSize: 20,
      keyword: ''
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize) || 1
    }
  },
  onShow() {
    this.loadUsers()
  },
  methods: {
    async loadUsers() {
      try {
        const data = await get('/api/v1/admin/users', { page: this.page, page_size: this.pageSize })
        this.users = data.records || []
        this.total = data.total || 0
      } catch (e) {}
    },
    onSearch() {
      this.page = 1
      this.loadUsers()
    },
    onPage(p) {
      this.page = p
      this.loadUsers()
    },
    onDetail(userId) {
      uni.navigateTo({ url: '/pages/user-detail/index?user_id=' + userId })
    },
    formatDate(d) {
      return d ? d.slice(0, 10) : '-'
    }
  }
}
</script>

<style scoped>
.container {
  padding: 16px;
}

.toolbar {
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-top: 16px;
}

.page-info {
  font-size: 13px;
  color: #999999;
}
</style>
