<template>
  <div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <h2>租户管理</h2>
      <el-input v-model="search" placeholder="搜索用户名/邮箱" style="width:240px" clearable @clear="loadTenants" @keyup.enter="loadTenants">
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
    </div>

    <el-table :data="tenants" v-loading="loading">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="type" label="类型">
        <template #default="{ row }">
          <el-tag :type="row.type === 'MAIN' ? 'primary' : 'info'">
            {{ row.type === 'MAIN' ? '主账号' : '子账号' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ row.status === 'ACTIVE' ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="注册时间" width="180">
        <template #default="{ row }">{{ new Date(row.createdAt).toLocaleString('zh-CN') }}</template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button link :type="row.status === 'ACTIVE' ? 'danger' : 'success'"
            @click="toggleStatus(row)">
            {{ row.status === 'ACTIVE' ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top:16px"
      :current-page="page + 1" :page-size="size" :total="total"
      layout="prev, pager, next" @current-change="(p: number) => { page = p - 1; loadTenants() }" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { opsApi, type TenantItem } from '@/api/ops'

const tenants = ref<TenantItem[]>([])
const loading = ref(false)
const search = ref('')
const page = ref(0)
const size = ref(20)
const total = ref(0)

async function loadTenants() {
  loading.value = true
  try {
    const res = await opsApi.listTenants(search.value, page.value, size.value)
    tenants.value = res.data.data.content
    total.value = res.data.data.total
  } catch {
    tenants.value = []
  } finally {
    loading.value = false
  }
}

async function toggleStatus(row: TenantItem) {
  await opsApi.toggleStatus(row.id)
  ElMessage.success('状态已更新')
  loadTenants()
}

onMounted(loadTenants)
</script>
