<script setup lang="ts">
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { http } from '../api/http';

const route = useRoute();
const id = route.params.id as string;
const detail = ref<any>({});
const balance = ref<any>({});
const members = ref<any[]>([]);
const projects = ref<any[]>([]);
const usage = ref<any>({ breakdown: [] });
const usageChart = ref<HTMLDivElement>();
const recharge = reactive({ amount: 0, note: '', externalRefId: '' });
const quota = reactive({ maxMembers: undefined, maxProjects: undefined, maxMonthlyCredits: undefined, maxConcurrentTasks: undefined, notes: '' } as any);

async function load() {
  detail.value = await http.get(`/tenants/${id}`);
  balance.value = await http.get(`/tenants/${id}/balance`);
  members.value = await http.get(`/tenants/${id}/members`);
  projects.value = await http.get(`/tenants/${id}/projects`);
  quota.maxMembers = detail.value.quota?.maxMembers;
  quota.maxProjects = detail.value.quota?.maxProjects;
  quota.maxMonthlyCredits = detail.value.quota?.maxMonthlyCredits;
  quota.maxConcurrentTasks = detail.value.quota?.maxConcurrentTasks;
  quota.notes = detail.value.quota?.notes;
  await loadUsage('model');
}

async function loadUsage(groupBy: string) {
  usage.value = await http.get(`/tenants/${id}/usage-detail`, { params: { groupBy } });
  if (usageChart.value) {
    echarts.init(usageChart.value).setOption({
      tooltip: { trigger: 'item' },
      series: [{ type: 'pie', radius: ['40%', '70%'], data: usage.value.breakdown.map((x: any) => ({ name: x.label, value: x.totalCredits })) }],
    });
  }
}

async function rechargeTenant() {
  await http.post(`/tenants/${id}/recharge`, recharge);
  await load();
}

async function updateQuota() {
  await http.put(`/tenants/${id}/quota`, quota);
  await load();
}

async function suspendTenant() {
  await http.post(`/tenants/${id}/suspend`, { reason: '运营后台暂停' });
  await load();
}

async function resumeTenant() {
  await http.post(`/tenants/${id}/resume`);
  await load();
}

async function impersonate() {
  const res = await http.post<any>(`/tenants/${id}/impersonate`, {});
  ElMessage.success(`已生成客户端 token：${res.token}`);
}

onMounted(load);
</script>

<template>
  <div>
    <div class="page-head">
      <div><h1>{{ detail.tenant?.name || '租户详情' }}</h1><p>{{ detail.tenant?.slug }}</p></div>
      <div>
        <el-button type="warning" plain @click="suspendTenant">暂停</el-button>
        <el-button type="success" plain @click="resumeTenant">恢复</el-button>
        <el-button type="primary" @click="impersonate">模拟登录</el-button>
      </div>
    </div>
    <el-tabs class="panel">
      <el-tab-pane label="基本信息">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="ID">{{ detail.tenant?.id }}</el-descriptions-item>
          <el-descriptions-item label="套餐">{{ detail.tenant?.plan }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ detail.tenant?.status === 1 ? '正常' : '暂停' }}</el-descriptions-item>
          <el-descriptions-item label="成员">{{ detail.memberCount }}</el-descriptions-item>
          <el-descriptions-item label="项目">{{ detail.projectCount }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ detail.tenant?.notes }}</el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane label="余额概览">
        <div class="metric-grid" style="grid-template-columns: repeat(3, 1fr)">
          <div class="metric"><span>余额</span><strong>{{ balance.balance?.balance || 0 }}</strong></div>
          <div class="metric"><span>累计充值</span><strong>{{ balance.balance?.totalRecharged || 0 }}</strong></div>
          <div class="metric"><span>累计消费</span><strong>{{ balance.balance?.totalSpent || 0 }}</strong></div>
        </div>
        <div class="toolbar" style="margin-top: 18px">
          <el-input-number v-model="recharge.amount" :min="0" />
          <el-input v-model="recharge.note" placeholder="备注" style="width: 220px" />
          <el-button type="primary" @click="rechargeTenant">充值</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="成员列表">
        <el-table :data="members">
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="role" label="角色" />
          <el-table-column prop="status" label="状态" />
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="项目列表">
        <el-table :data="projects">
          <el-table-column prop="name" label="项目" />
          <el-table-column prop="status" label="状态" />
          <el-table-column prop="createdAt" label="创建时间" />
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="积分明细">
        <div class="toolbar">
          <el-button @click="loadUsage('model')">按模型</el-button>
          <el-button @click="loadUsage('modality')">按模态</el-button>
          <el-button @click="loadUsage('user')">按用户</el-button>
          <el-button @click="loadUsage('day')">按天</el-button>
        </div>
        <div class="panel-grid">
          <div ref="usageChart" class="chart-box" />
          <el-table :data="usage.breakdown">
            <el-table-column prop="label" label="维度" />
            <el-table-column prop="totalCredits" label="积分" />
            <el-table-column prop="count" label="次数" />
            <el-table-column prop="percent" label="占比" />
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="配额">
        <div class="toolbar">
          <el-input-number v-model="quota.maxMembers" placeholder="成员" />
          <el-input-number v-model="quota.maxProjects" placeholder="项目" />
          <el-input-number v-model="quota.maxMonthlyCredits" placeholder="月积分" />
          <el-input-number v-model="quota.maxConcurrentTasks" placeholder="并发任务" />
          <el-button type="primary" @click="updateQuota">保存</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
