<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import DataTablePage from '@/components/DataTablePage.vue'
import { createTenant, getTenants, setTenantQuota, type Tenant } from '@/api/modules/tenant'

const router = useRouter()
const loading = ref(false)
const tenants = ref<Tenant[]>([])
const showCreate = ref(false)
const form = ref({ name: '', code: '', quota: '' as string })

async function load() {
  loading.value = true
  try {
    tenants.value = await getTenants()
  } finally {
    loading.value = false
  }
}

function openDetail(id: string) {
  router.push(`/tenants/${id}`)
}

async function submitCreate() {
  if (!form.value.name) {
    ElMessage.warning('请填写租户名称')
    return
  }
  let quota: Record<string, unknown> = {}
  if (form.value.quota) {
    try {
      quota = JSON.parse(form.value.quota)
    } catch {
      ElMessage.error('配额需为合法 JSON')
      return
    }
  }
  await createTenant({ name: form.value.name, code: form.value.code, quota })
  ElMessage.success('租户创建成功')
  showCreate.value = false
  form.value = { name: '', code: '', quota: '' }
  load()
}

async function setQuota(row: Tenant) {
  const input = await ElMessageBox.prompt('输入租户配额 JSON', '设置配额', {
    inputValue: JSON.stringify(row.quota || {}),
  }).catch(() => null)
  if (!input) return
  try {
    const q = JSON.parse(input.value)
    await setTenantQuota(row.id, q)
    ElMessage.success('配额已更新')
    load()
  } catch {
    ElMessage.error('无效的 JSON')
  }
}

onMounted(load)
</script>

<template>
  <div class="page">
    <DataTablePage title="租户管理" :data="tenants" :loading="loading">
      <template #toolbar-extra>
        <el-button type="primary" :icon="Plus" @click="showCreate = true">新建租户</el-button>
      </template>
      <template #columns>
        <el-table-column prop="name" label="租户名称" min-width="140" />
        <el-table-column prop="code" label="编码" min-width="100" />
        <el-table-column label="配额" min-width="160">
          <template #default="{ row }">
            {{ Object.keys(row.quota || {}).length ? JSON.stringify(row.quota) : '—' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100" />
        <el-table-column prop="create_time" label="创建时间" min-width="180" />
      </template>
      <template #actions="{ row }">
        <el-button link type="primary" @click="openDetail(row.id)">详情</el-button>
        <el-button link type="primary" @click="setQuota(row)">配额</el-button>
      </template>
    </DataTablePage>
    <el-dialog v-model="showCreate" title="新建租户" width="520px">
      <el-form label-width="90px">
        <el-form-item label="名称" required>
          <el-input v-model="form.name" placeholder="租户名称" />
        </el-form-item>
        <el-form-item label="编码">
          <el-input v-model="form.code" placeholder="tenant code" />
        </el-form-item>
        <el-form-item label="配额 JSON">
          <el-input v-model="form.quota" type="textarea" :rows="3" placeholder='{"gpu": 8}' />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreate = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.page { padding: 16px; }
</style>
