<template>
  <div class="page">
    <section class="page-hero">
      <div>
        <h1>租户管理</h1>
        <p>平台超级管理员用于开通租户，并同步创建该租户的管理员账号。</p>
      </div>
      <el-button type="primary" round @click="dialogVisible = true">新增租户</el-button>
    </section>

    <div class="toolbar">
      <el-input v-model="keyword" placeholder="搜索租户名称/编码" style="width: 280px" clearable @change="handleFilterChange" />
    </div>

    <el-card class="modern-card" shadow="never">
      <el-table :data="tenants" v-loading="loading" class="modern-table">
        <el-table-column prop="name" label="租户名称" />
        <el-table-column prop="code" label="租户编码" />
        <el-table-column label="管理员账号">
          <template #default="{ row }">{{ row.users?.[0]?.username ?? '-' }}</template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-switch v-model="row.enabled" @change="toggleTenant(row)" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="180">
          <template #default="{ row }">{{ formatTime(row.createdAt) }}</template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        layout="total, sizes, prev, pager, next"
        :total="total"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <el-dialog v-model="dialogVisible" title="新增租户" width="560px">
      <el-form :model="form" label-width="110px">
        <el-form-item label="租户名称"><el-input v-model="form.name" placeholder="例如：高邮市照明中心" /></el-form-item>
        <el-form-item label="租户编码"><el-input v-model="form.code" placeholder="例如：gaoyou" /></el-form-item>
        <el-divider>租户管理员</el-divider>
        <el-form-item label="管理员账号"><el-input v-model="form.adminUsername" placeholder="默认 admin" /></el-form-item>
        <el-form-item label="管理员姓名"><el-input v-model="form.adminName" placeholder="默认 租户管理员" /></el-form-item>
        <el-form-item label="初始密码">
          <el-input v-model="form.adminPassword" type="password" show-password placeholder="至少 6 位" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="create">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const tenants = ref<any[]>([]);
const keyword = ref('');
const loading = ref(false);
const saving = ref(false);
const dialogVisible = ref(false);
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
const form = reactive({
  name: '',
  code: '',
  adminUsername: 'admin',
  adminName: '租户管理员',
  adminPassword: 'admin123456',
});

function formatTime(value: string) {
  return value ? new Date(value).toLocaleString() : '-';
}

async function load() {
  loading.value = true;
  try {
    const result = await systemApi.tenants({ keyword: keyword.value, page: page.value, pageSize: pageSize.value });
    tenants.value = result.items ?? [];
    total.value = result.total ?? 0;
  } finally {
    loading.value = false;
  }
}

function resetForm() {
  form.name = '';
  form.code = '';
  form.adminUsername = 'admin';
  form.adminName = '租户管理员';
  form.adminPassword = 'admin123456';
}

async function create() {
  saving.value = true;
  try {
    await systemApi.createTenant({ ...form });
    ElMessage.success('租户创建成功');
    dialogVisible.value = false;
    resetForm();
    await load();
  } finally {
    saving.value = false;
  }
}

async function toggleTenant(row: any) {
  await systemApi.updateTenant(row.id, { enabled: row.enabled });
  ElMessage.success(row.enabled ? '租户已启用' : '租户已停用');
}

function handleFilterChange() {
  page.value = 1;
  void load();
}

function handlePageChange(value: number) {
  page.value = value;
  void load();
}

function handleSizeChange(value: number) {
  pageSize.value = value;
  page.value = 1;
  void load();
}

onMounted(load);
</script>

<style scoped>
.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
