<template>
  <view>
    <view class="toolbar">
      <view class="header-actions">
        <input
          class="search-input"
          v-model="keyword"
          placeholder="搜索用户/手机号..."
          placeholder-class="input-placeholder"
          @confirm="onSearch"
        />
        <button class="btn-primary btn-sm" @click="onSearch">搜索</button>
        <button class="btn-default btn-sm" @click="onExport">导出用户</button>
      </view>
    </view>

    <view class="page-card">
      <view class="data-table">
        <view class="t-header">
          <view class="t-row">
            <text class="t-th flex2">用户</text>
            <text class="t-th flex2">手机号</text>
            <text class="t-th flex1">绑定设备</text>
            <text class="t-th flex1">使用次数</text>
            <text class="t-th flex1">订阅状态</text>
            <text class="t-th flex1">用户状态</text>
            <text class="t-th flex2">注册时间</text>
            <text class="t-th flex1">操作</text>
          </view>
        </view>
        <view class="t-body">
          <view class="t-row" v-for="item in users" :key="item.user_id">
            <text class="t-td flex2">
              <view class="user-cell">
                <view class="avatar-circle">👤</view>
                <text>{{ item.nickname || '-' }}</text>
              </view>
            </text>
            <text class="t-td flex2">{{ item.phone || '-' }}</text>
            <text class="t-td flex1">{{ item.device_count || 0 }}</text>
            <text class="t-td flex1">{{ item.treatment_count || 0 }}次</text>
            <text class="t-td flex1">
              <text :class="subBadge(item.subscription_status)">{{ subStatusText(item.subscription_status) }}</text>
            </text>
            <text class="t-td flex1">
              <text :class="userStatusBadge(item.status)">{{ userStatusText(item.status) }}</text>
            </text>
            <text class="t-td flex2">{{ formatDate(item.created_at) }}</text>
            <text class="t-td flex1">
              <text class="action-link" @click="onDetail(item.user_id)">详情</text>
              <text class="action-link" @click="onViewRecords(item.user_id)">记录</text>
            </text>
          </view>
        </view>
      </view>

      <view class="empty-state" v-if="users.length === 0">暂无数据</view>

      <view class="pagination">
        <button class="btn-page" :disabled="page <= 1" @click="onPage(page - 1)">‹</button>
        <button class="btn-page active">{{ page }}</button>
        <button class="btn-page" :disabled="page >= totalPages" @click="onPage(page + 1)">›</button>
        <text class="page-info">共 {{ totalPages }} 页</text>
      </view>
    </view>
  </view>
</template>

<script>
import { get } from '../utils/request'
import { exportCSV } from '../utils/export'
import { formatDateShort } from '../utils/format'

export default {
  name: 'UserListView',
  data() {
    return {
      users: [],
      total: 0,
      page: 1,
      pageSize: 20,
      keyword: ''
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize) || 1
    }
  },
  mounted() {
    this.loadUsers()
  },
  methods: {
    async loadUsers() {
      try {
        const data = await get('/api/v1/admin/users', { page: this.page, page_size: this.pageSize, keyword: this.keyword })
        this.users = data.records || []
        this.total = data.total || 0
      } catch (e) {
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    onSearch() {
      this.page = 1
      this.loadUsers()
    },
    onPage(p) {
      this.page = p
      this.loadUsers()
    },
    onDetail(userId) {
      this.$emit('navigate', 'user-detail', { user_id: userId })
    },
    onViewRecords(userId) {
      this.$emit('navigate', 'record', { user_id: userId })
    },
    subStatusText(status) {
      return status === 1 ? '已订阅' : '未订阅'
    },
    subBadge(status) {
      return status === 1 ? 'badge badge-success' : 'badge badge-default'
    },
    userStatusText(status) {
      const map = { 1: '正常', 2: '禁用', 3: '已注销' }
      return map[status] || '未知'
    },
    userStatusBadge(status) {
      const map = { 1: 'badge badge-success', 2: 'badge badge-warning', 3: 'badge badge-error' }
      return map[status] || 'badge badge-default'
    },
    formatDate: formatDateShort,
    async onExport() {
      try {
        const data = await get('/api/v1/admin/users', { page: 1, page_size: 9999, keyword: this.keyword })
        const records = data.records || []
        exportCSV('users_' + new Date().toISOString().slice(0, 10) + '.csv',
          ['用户ID', '昵称', '手机号', '绑定设备数', '使用次数', '订阅状态', '用户状态', '注册时间'],
          records.map(function (r) {
            var userStatus = { 1: '正常', 2: '禁用', 3: '已注销' }[r.status] || '未知'
            return [r.user_id, r.nickname || '', r.phone || '', r.device_count || 0, r.treatment_count || 0, r.subscription_status === 1 ? '已订阅' : '未订阅', userStatus, r.created_at ? r.created_at.slice(0, 10) : '']
          })
        )
        uni.showToast({ title: '导出成功', icon: 'success' })
      } catch (e) {
        uni.showToast({ title: '导出失败', icon: 'none' })
      }
    }
  }
}
</script>

<style scoped>
@import '../styles/common.css';

.user-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.avatar-circle {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  flex-shrink: 0;
}

.pagination {
  justify-content: flex-end;
}
</style>
