<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { http, type PageResult } from '../api/http';

const router = useRouter();
const loading = ref(false);
const query = reactive({ keyword: '', plan: '', status: undefined as number | undefined, page: 1, size: 20 });
const page = ref<PageResult<any>>({ records: [], total: 0, page: 1, size: 20 });

async function load() {
  loading.value = true;
  try {
    page.value = await http.get('/tenants', { params: query });
  } finally {
    loading.value = false;
  }
}

onMounted(load);
</script>

<template>
  <div>
    <div class="page-head">
      <div><h1>租户管理</h1><p>跨租户查询、套餐与状态操作</p></div>
    </div>
    <div class="toolbar">
      <el-input v-model="query.keyword" :prefix-icon="Search" placeholder="名称 / slug" style="width: 240px" clearable />
      <el-select v-model="query.plan" placeholder="套餐" clearable style="width: 160px">
        <el-option label="Free" value="free" />
        <el-option label="Pro" value="pro" />
        <el-option label="Team" value="team" />
        <el-option label="Enterprise" value="enterprise" />
      </el-select>
      <el-select v-model="query.status" placeholder="状态" clearable style="width: 140px">
        <el-option label="正常" :value="1" />
        <el-option label="暂停" :value="0" />
      </el-select>
      <el-button type="primary" @click="load">查询</el-button>
    </div>
    <div class="panel">
      <el-table :data="page.records" v-loading="loading" row-key="id">
        <el-table-column prop="name" label="租户" min-width="180" />
        <el-table-column prop="slug" label="Slug" min-width="140" />
        <el-table-column prop="plan" label="套餐" width="120" />
        <el-table-column prop="balance" label="余额" width="120" />
        <el-table-column prop="memberCount" label="成员" width="90" />
        <el-table-column prop="projectCount" label="项目" width="90" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="plain">{{ row.status === 1 ? '正常' : '暂停' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110" fixed="right">
          <template #default="{ row }"><el-button text type="primary" @click="router.push(`/tenants/${row.id}`)">详情</el-button></template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="query.page" v-model:page-size="query.size" layout="total, prev, pager, next" :total="page.total" @current-change="load" />
    </div>
  </div>
</template>
