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

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

async function load() {
  page.value = await http.get('/users', { params: query });
}

async function setStatus(row: any, status: number) {
  await http.patch(`/users/${row.id}/status`, { status });
  await load();
}

async function kickout(row: any) {
  await http.post(`/users/${row.id}/kickout`);
}

async function resetPassword(row: any) {
  const res = await http.post<any>(`/users/${row.id}/reset-password`);
  ElMessage.success(`新密码：${res.password}`);
}

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" placeholder="邮箱 / 用户名 / 手机" style="width: 260px" />
      <el-input v-model="query.tenantId" placeholder="租户 ID" style="width: 180px" />
      <el-button type="primary" @click="load">查询</el-button>
    </div>
    <div class="panel">
      <el-table :data="page.records">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="tenantId" label="租户" />
        <el-table-column prop="role" label="角色" />
        <el-table-column prop="status" label="状态" />
        <el-table-column label="操作" width="240">
          <template #default="{ row }">
            <el-button text type="primary" @click="setStatus(row, row.status === 1 ? 0 : 1)">{{ row.status === 1 ? '禁用' : '启用' }}</el-button>
            <el-button text @click="kickout(row)">下线</el-button>
            <el-button text @click="resetPassword(row)">重置</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
