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

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const dialog = 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 });
const pageSizes = [10, 20, 30];
const plans = ref<any[]>([]);
const form = reactive({
  name: '',
  slug: '',
  planCode: 'FREE',
  adminUsername: '',
  adminEmail: '',
  adminPassword: 'Dramix@123',
  initialCredits: 1000,
  notes: '',
});

async function load() {
  loading.value = true;
  try {
    const [tenantPage, planRows] = await Promise.all([
      http.get<PageResult<any>>('/tenants', { params: query }),
      plans.value.length ? Promise.resolve(plans.value) : http.get<any[]>('/plans'),
    ]);
    page.value = tenantPage;
    plans.value = planRows;
    if (!plans.value.some((plan) => String(plan.code || '').toUpperCase() === form.planCode)) {
      form.planCode = String(plans.value.find((plan) => Number(plan.isActive) === 1)?.code || 'FREE').toUpperCase();
    }
  } finally {
    loading.value = false;
  }
}

function applyRouteQuery() {
  query.keyword = String(route.query.keyword || '');
  query.status = route.query.status === undefined ? undefined : Number(route.query.status);
  query.page = 1;
}

function search() {
  query.page = 1;
  load();
}

async function createTenant() {
  await http.post('/tenants', form);
  ElMessage.success('企业已开户，管理员账号已创建');
  dialog.value = false;
  await load();
}

onMounted(() => {
  applyRouteQuery();
  load();
});
watch(() => route.query, () => {
  applyRouteQuery();
  load();
});
</script>

<template>
  <div>
    <div class="page-head">
      <div><h1>企业列表</h1><p>企业开户、状态管控、资源余量与服务到期追踪</p></div>
      <div class="page-actions">
        <el-button type="primary" :icon="Plus" @click="dialog = true">手动开户</el-button>
      </div>
    </div>
    <div class="toolbar">
      <el-input v-model="query.keyword" :prefix-icon="Search" placeholder="企业名称 / 租户标识" style="width: 240px" clearable />
      <el-select v-model="query.plan" placeholder="套餐" clearable style="width: 160px">
        <el-option v-for="plan in plans" :key="plan.code" :label="plan.name || plan.code" :value="String(plan.code).toLowerCase()" />
      </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="search">查询</el-button>
    </div>
    <div class="panel">
      <div class="panel-title">
        <div><b>企业租户列表</b><span>支持按名称、状态、套餐搜索与筛选</span></div>
      </div>
      <el-table :data="page.records" v-loading="loading" row-key="id" class="module-table">
        <el-table-column prop="name" label="租户" min-width="180" />
        <el-table-column prop="slug" label="租户标识" 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" align="center">
          <template #default="{ row }">
            <div class="row-actions"><el-button text type="primary" @click="router.push(`/tenants/${row.id}`)">详情</el-button></div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="query.page"
        v-model:page-size="query.size"
        layout="total, sizes, prev, pager, next"
        :page-sizes="pageSizes"
        :total="page.total"
        @current-change="load"
        @size-change="search"
      />
    </div>

    <el-dialog v-model="dialog" title="手动企业开户" width="620px">
      <el-form label-position="top">
        <div class="form-grid">
          <el-form-item label="企业名称"><el-input v-model="form.name" placeholder="例如：星火互动文化" /></el-form-item>
          <el-form-item label="租户标识"><el-input v-model="form.slug" placeholder="如 spark-media" /></el-form-item>
          <el-form-item label="套餐">
            <el-select v-model="form.planCode">
              <el-option
                v-for="plan in plans.filter((item) => Number(item.isActive) === 1)"
                :key="plan.code"
                :label="`${plan.name || plan.code}（${plan.monthlyCredits || 0} 积分 / ${plan.maxMembers || 0} 成员）`"
                :value="String(plan.code).toUpperCase()"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="初始积分"><el-input-number v-model="form.initialCredits" :min="0" /></el-form-item>
          <el-form-item label="管理员账号"><el-input v-model="form.adminUsername" placeholder="默认 slug_admin" /></el-form-item>
          <el-form-item label="管理员邮箱"><el-input v-model="form.adminEmail" placeholder="默认 slug@dramix.local" /></el-form-item>
          <el-form-item label="初始密码"><el-input v-model="form.adminPassword" show-password /></el-form-item>
          <el-form-item label="备注"><el-input v-model="form.notes" /></el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="dialog = false">取消</el-button>
        <el-button type="primary" @click="createTenant">创建企业</el-button>
      </template>
    </el-dialog>
  </div>
</template>
