<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import { useMessage, NCard, NDataTable, NButton, NInput, NTag, NSpace, NModal, NForm, NFormItem, NSelect, NPopconfirm, NIcon, type FormRules } from 'naive-ui'
import { SearchOutline, SaveOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'
import { toBeijingDate } from '../../utils/date'

interface Tenant {
  id: string
  name: string
  slug: string
  hospital_name: string
  plan_type: string
  status: string
  created_at: string
  member_count?: number
  [key: string]: unknown
}

interface TenantListResponse {
  items: Tenant[]
  total: number
}

const tenants = ref<Tenant[]>([])
const total = ref(0)
const loading = ref(true)
const searchQ = ref('')
const showModal = ref(false)
const editing = ref<Tenant | null>(null)
const saving = ref(false)
const formRef = ref()
const rules: FormRules = {
  name: { required: true, message: '请输入租户名称', trigger: 'blur' },
}
const message = useMessage()
const planOptions = [{label:'Free',value:'free'},{label:'Pro',value:'pro'},{label:'Team',value:'team'}]

onMounted(loadData)
async function loadData() {
  loading.value = true
  try { const { data } = await api.get<TenantListResponse>('/admin/tenants', { params: { q: searchQ.value, page_size:50 } }); tenants.value = data.items; total.value = data.total }
  catch (e) { message.error('加载租户列表失败：' + ((e as any)?.response?.data?.detail || '请重试')) }
  finally { loading.value = false }
}
async function toggleStatus(row: Tenant) {
  try { await api.post(`/admin/tenants/${row.id}/toggle-status`); loadData() }
  catch (e) { message.error('操作失败：' + ((e as any)?.response?.data?.detail || '请重试')) }
}
async function editTenant(row: Tenant) {
  const { data } = await api.get<Tenant>(`/admin/tenants/${row.id}`)
  editing.value = data; showModal.value = true
}
async function saveTenant() {
  if (!editing.value) return
  try { await formRef.value?.validate() } catch { return }
  saving.value = true
  try { await api.put(`/admin/tenants/${editing.value.id}`, { plan_type: editing.value.plan_type, status: editing.value.status, name: editing.value.name }); showModal.value = false; loadData() }
  catch (e) { message.error('保存失败：' + ((e as any)?.response?.data?.detail || '请重试')) }
  finally { saving.value = false }
}

const cols = [
  { title: '名称', key: 'name', width: 200, ellipsis: true },
  { title: 'Slug', key: 'slug', width: 150, ellipsis: true },
  { title: '医院', key: 'hospital_name', width: 120 },
  { title: '方案', key: 'plan_type', width: 80, render: (r: Tenant) => h(NTag, { size:'tiny', type: r.plan_type==='team'?'success':'default' }, r.plan_type||'free') },
  { title: '状态', key: 'status', width: 80, render: (r: Tenant) => h(NTag, { size:'tiny', type: r.status==='active'?'success':'error' }, r.status) },
  { title: '创建时间', key: 'created_at', width: 120, render: (r: Tenant) => toBeijingDate(r.created_at) },
  { title: '操作', key: 'actions', width: 160, render: (r: Tenant) => h(NSpace, { size:'small' }, [
    h(NButton, { size:'tiny', onClick: () => editTenant(r) }, '编辑'),
    h(NPopconfirm, { onPositiveClick: () => toggleStatus(r) }, {
      trigger: () => h(NButton, { size:'tiny', secondary: true }, r.status==='active'?'停用':'启用'),
    }),
  ]) },
]
const scrollX = 910
</script>

<template>
  <div>
    <div style="display:flex;justify-content:space-between;margin-bottom:16px">
      <h2>🏢 租户管理 ({{ total }})</h2>
      <NSpace><NInput v-model:value="searchQ" placeholder="搜索..." size="small" @keyup.enter="loadData"/><NButton size="small" @click="loadData" class="sky-btn"><template #icon><NIcon size="14"><SearchOutline /></NIcon></template>搜索</NButton></NSpace>
    </div>
    <NDataTable :columns="cols" :data="tenants" :loading="loading" size="small" :paginate="{ pageSize: 20 }" :scroll-x="scrollX" />

    <NModal v-model:show="showModal" title="编辑租户" v-if="editing">
      <NCard style="width:500px">
        <NForm ref="formRef" :model="editing" :rules="rules" label-placement="left" label-width="80">
          <NFormItem path="name" label="名称"><NInput v-model:value="editing.name" /></NFormItem>
          <NFormItem label="方案"><NSelect v-model:value="editing.plan_type" :options="planOptions" /></NFormItem>
          <NFormItem label="状态"><NSelect v-model:value="editing.status" :options="[{label:'启用',value:'active'},{label:'停用',value:'suspended'}]" /></NFormItem>
          <NFormItem label="成员">{{ editing.member_count || 0 }}</NFormItem>
          <NButton type="primary" :loading="saving" @click="saveTenant" class="sky-btn"><template #icon><NIcon size="14"><SaveOutline /></NIcon></template>保存</NButton>
        </NForm>
      </NCard>
    </NModal>
  </div>
</template>
