<script lang="ts" setup>
/**
 * AI 平台详情抽屉（二级页）
 * Tabs：概览 | Key消耗 | 模型消耗 | 请求记录 | Key管理 | 模型管理
 */
import { computed, ref } from 'vue';

import { useVbenDrawer, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Card,
  Col,
  Popconfirm,
  Row,
  Spin,
  Table,
  Tabs,
  Tag,
  message,
} from 'ant-design-vue';

import KeyModal from '../../api-key/components/modal.vue';
import {
  deleteAiApiKey,
  setAiApiKeyDefault,
} from '../../api-key/api';
import { getAiGenerationList } from '../../generation/api';
import { getAiPlatformDetailBoard, setAiPlatformActive } from '../api';
import { deleteAiModel, setAiModelDefault } from '../api/model';
import ModelModal from './model-modal.vue';

defineOptions({ name: 'AiPlatformDetail' });

interface ModelCard {
  id: number;
  platform_id: number;
  code: string;
  name: string;
  description: string;
  is_default: number;
  status: number;
}

interface KeyCard {
  id: number;
  platform_id: number;
  name: string;
  remark: string;
  is_default: number;
  status: number;
  api_key_mask: string;
}

const activeTab = ref('overview');
const loading = ref(false);
const platformId = ref(0);
const onChanged = ref<null | (() => void)>(null);
const platform = ref<Record<string, any>>({});
const overview = ref<Record<string, any>>({});
const usageByKey = ref<any[]>([]);
const usageByModel = ref<any[]>([]);
const recentGenerations = ref<any[]>([]);
const keys = ref<KeyCard[]>([]);
const models = ref<ModelCard[]>([]);
const requestRows = ref<any[]>([]);
const requestLoading = ref(false);
const requestTotal = ref(0);
const requestPage = ref(1);

const [Drawer, drawerApi] = useVbenDrawer({
  title: '平台详情',
  class: 'w-[960px]',
  footer: false,
  contentClass: '!flex !flex-col !overflow-hidden',
  async onOpenChange(isOpen) {
    if (!isOpen) {
      reset();
      return;
    }
    const data = drawerApi.getData<{
      platformId: number;
      onChanged?: () => void;
    }>();
    platformId.value = Number(data?.platformId || 0);
    onChanged.value = data?.onChanged || null;
    activeTab.value = 'overview';
    await loadDetail();
  },
});

const [ModelModalComp, modelModalApi] = useVbenModal({
  connectedComponent: ModelModal,
});
const [KeyModalComp, keyModalApi] = useVbenModal({
  connectedComponent: KeyModal,
});

const drawerTitle = computed(
  () => `平台详情 · ${platform.value?.name || platform.value?.code || ''}`,
);

function reset() {
  platformId.value = 0;
  platform.value = {};
  overview.value = {};
  usageByKey.value = [];
  usageByModel.value = [];
  recentGenerations.value = [];
  keys.value = [];
  models.value = [];
  requestRows.value = [];
  requestTotal.value = 0;
  requestPage.value = 1;
}

async function loadDetail() {
  if (!platformId.value) return;
  loading.value = true;
  try {
    const res = await getAiPlatformDetailBoard(platformId.value);
    const data = res?.data || res || {};
    platform.value = data.platform || {};
    overview.value = data.overview || {};
    usageByKey.value = Array.isArray(data.usage_by_key) ? data.usage_by_key : [];
    usageByModel.value = Array.isArray(data.usage_by_model)
      ? data.usage_by_model
      : [];
    recentGenerations.value = Array.isArray(data.recent_generations)
      ? data.recent_generations
      : [];
    keys.value = Array.isArray(data.keys) ? data.keys : [];
    models.value = Array.isArray(data.models) ? data.models : [];
    drawerApi.setState({ title: drawerTitle.value });
  } finally {
    loading.value = false;
  }
}

function notifyParent() {
  onChanged.value?.();
}

async function reloadAll() {
  await loadDetail();
  notifyParent();
  if (activeTab.value === 'requests') {
    await loadRequests();
  }
}

async function loadRequests(page = requestPage.value) {
  if (!platformId.value) return;
  requestLoading.value = true;
  requestPage.value = page;
  try {
    const res = await getAiGenerationList({
      platform_id: platformId.value,
      page,
      pageSize: 10,
    });
    const data = res?.data || res || {};
    requestRows.value = Array.isArray(data.items) ? data.items : [];
    requestTotal.value = Number(data.total || 0);
  } finally {
    requestLoading.value = false;
  }
}

function onTabChange(key: string | number) {
  activeTab.value = String(key);
  if (String(key) === 'requests' && !requestRows.value.length) {
    void loadRequests(1);
  }
}

function formatDuration(ms: number) {
  const n = Number(ms || 0);
  if (n <= 0) return '—';
  if (n < 1000) return `${n} ms`;
  return `${(n / 1000).toFixed(1)} s`;
}

function openModelModal(row?: ModelCard) {
  modelModalApi.setData({
    values: row || {},
    update: !!row?.id,
    platform_id: platformId.value,
    onSuccess: reloadAll,
  });
  modelModalApi.open();
}

function openKeyModal(row?: KeyCard) {
  keyModalApi.setData({
    values: row || { platform_id: platformId.value },
    update: !!row?.id,
    platform_id: platformId.value,
    lockPlatformId: true,
    onSuccess: reloadAll,
  });
  keyModalApi.open();
}

async function handleSetActive() {
  await setAiPlatformActive({ id: platformId.value });
  message.success('已设为当前选用平台');
  await reloadAll();
}

async function handleDeleteModel(id: number) {
  await deleteAiModel({ ids: [id] });
  message.success('已删除模型');
  await reloadAll();
}

async function handleDeleteKey(id: number) {
  await deleteAiApiKey({ ids: [id] });
  message.success('已删除密钥');
  await reloadAll();
}

async function handleSetDefaultModel(id: number) {
  await setAiModelDefault({ id });
  message.success('已设为默认模型');
  await reloadAll();
}

async function handleSetDefaultKey(id: number) {
  await setAiApiKeyDefault({ id });
  message.success('已设为默认密钥');
  await reloadAll();
}

const usageKeyColumns = [
  { title: '密钥', dataIndex: 'api_key_name', key: 'api_key_name' },
  { title: '请求数', dataIndex: 'request_count', key: 'request_count', width: 90 },
  { title: 'Tokens', dataIndex: 'total_tokens', key: 'total_tokens', width: 110 },
  {
    title: '平均耗时',
    dataIndex: 'avg_duration_ms',
    key: 'avg_duration_ms',
    width: 100,
    customRender: ({ text }: any) => formatDuration(Number(text || 0)),
  },
];

const usageModelColumns = [
  { title: '模型', dataIndex: 'model', key: 'model' },
  { title: '请求数', dataIndex: 'request_count', key: 'request_count', width: 90 },
  { title: 'Tokens', dataIndex: 'total_tokens', key: 'total_tokens', width: 110 },
  {
    title: '平均耗时',
    dataIndex: 'avg_duration_ms',
    key: 'avg_duration_ms',
    width: 100,
    customRender: ({ text }: any) => formatDuration(Number(text || 0)),
  },
];

const requestColumns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 70 },
  { title: '场景', dataIndex: 'scene_txt', key: 'scene_txt', width: 80 },
  { title: '名称', dataIndex: 'name', key: 'name', ellipsis: true },
  { title: '状态', dataIndex: 'status_txt', key: 'status_txt', width: 80 },
  { title: '模型', dataIndex: 'model', key: 'model', width: 120, ellipsis: true },
  { title: 'Tokens', dataIndex: 'total_tokens', key: 'total_tokens', width: 90 },
  {
    title: '耗时',
    dataIndex: 'duration_ms',
    key: 'duration_ms',
    width: 90,
    customRender: ({ text }: any) => formatDuration(Number(text || 0)),
  },
  { title: '时间', dataIndex: 'created_at', key: 'created_at', width: 160 },
];
</script>

<template>
  <Drawer>
    <ModelModalComp />
    <KeyModalComp />
    <Spin :spinning="loading">
      <div class="flex min-h-0 flex-1 flex-col overflow-hidden p-1">
        <div class="mb-3 flex flex-wrap items-center gap-2">
          <Tag v-if="platform.is_active === 1" color="processing">当前选用</Tag>
          <Tag :color="platform.status === 1 ? 'success' : 'default'">
            {{ platform.status === 1 ? '启用' : '禁用' }}
          </Tag>
          <span class="text-xs text-[hsl(var(--muted-foreground))]">
            {{ platform.code }} · {{ platform.api_url || '—' }}
          </span>
          <div class="ml-auto flex gap-2">
            <Button
              v-if="platform.is_active !== 1"
              size="small"
              type="primary"
              ghost
              @click="handleSetActive"
            >
              设为当前
            </Button>
            <Button size="small" @click="reloadAll">刷新</Button>
          </div>
        </div>

        <Tabs :active-key="activeTab" class="ai-plat-tabs min-h-0 flex-1" @change="onTabChange">
          <Tabs.TabPane key="overview" tab="概览">
            <Row :gutter="12">
              <Col :span="8">
                <Card size="small">
                  <div class="text-xs text-[hsl(var(--muted-foreground))]">密钥数</div>
                  <div class="mt-1 text-lg font-semibold">{{ overview.key_count || 0 }}</div>
                </Card>
              </Col>
              <Col :span="8">
                <Card size="small">
                  <div class="text-xs text-[hsl(var(--muted-foreground))]">模型数</div>
                  <div class="mt-1 text-lg font-semibold">{{ overview.model_count || 0 }}</div>
                </Card>
              </Col>
              <Col :span="8">
                <Card size="small">
                  <div class="text-xs text-[hsl(var(--muted-foreground))]">默认模型</div>
                  <div class="mt-1 truncate text-lg font-semibold">
                    {{ platform.default_model || '—' }}
                  </div>
                </Card>
              </Col>
              <Col :span="8" class="mt-3">
                <Card size="small">
                  <div class="text-xs text-[hsl(var(--muted-foreground))]">总 Tokens</div>
                  <div class="mt-1 text-lg font-semibold">{{ overview.total_tokens || 0 }}</div>
                </Card>
              </Col>
              <Col :span="8" class="mt-3">
                <Card size="small">
                  <div class="text-xs text-[hsl(var(--muted-foreground))]">成功/失败</div>
                  <div class="mt-1 text-lg font-semibold">
                    {{ overview.success_count || 0 }}/{{ overview.fail_count || 0 }}
                  </div>
                </Card>
              </Col>
              <Col :span="8" class="mt-3">
                <Card size="small">
                  <div class="text-xs text-[hsl(var(--muted-foreground))]">平均耗时</div>
                  <div class="mt-1 text-lg font-semibold">
                    {{ formatDuration(Number(overview.avg_duration_ms || 0)) }}
                  </div>
                </Card>
              </Col>
            </Row>
            <div class="mt-4 text-sm font-medium">近期请求</div>
            <Table
              class="mt-2"
              size="small"
              :pagination="false"
              :columns="requestColumns"
              :data-source="recentGenerations"
              :row-key="(r: any) => r.id"
            />
          </Tabs.TabPane>

          <Tabs.TabPane key="key-usage" tab="Key消耗">
            <Table
              size="small"
              :pagination="false"
              :columns="usageKeyColumns"
              :data-source="usageByKey"
              :row-key="(r: any) => r.api_key_id"
            />
          </Tabs.TabPane>

          <Tabs.TabPane key="model-usage" tab="模型消耗">
            <Table
              size="small"
              :pagination="false"
              :columns="usageModelColumns"
              :data-source="usageByModel"
              :row-key="(r: any) => r.model"
            />
          </Tabs.TabPane>

          <Tabs.TabPane key="requests" tab="请求记录">
            <Table
              size="small"
              :loading="requestLoading"
              :columns="requestColumns"
              :data-source="requestRows"
              :row-key="(r: any) => r.id"
              :pagination="{
                current: requestPage,
                pageSize: 10,
                total: requestTotal,
                onChange: (p: number) => loadRequests(p),
              }"
            />
          </Tabs.TabPane>

          <Tabs.TabPane key="keys" tab="Key管理">
            <div class="mb-2 flex justify-end">
              <Button type="primary" size="small" @click="openKeyModal()">新增密钥</Button>
            </div>
            <div
              v-if="!keys.length"
              class="rounded-lg border border-dashed border-[hsl(var(--border))] p-4 text-sm text-[hsl(var(--muted-foreground))]"
            >
              暂无密钥
            </div>
            <div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2">
              <div
                v-for="k in keys"
                :key="k.id"
                class="rounded-lg border border-[hsl(var(--border))] p-3"
              >
                <div class="flex flex-wrap items-center gap-2">
                  <span class="font-medium">{{ k.name }}</span>
                  <Tag v-if="k.is_default === 1" color="gold">默认</Tag>
                  <Tag :color="k.status === 1 ? 'success' : 'default'">
                    {{ k.status === 1 ? '启用' : '禁用' }}
                  </Tag>
                </div>
                <div class="mt-1 font-mono text-xs text-[hsl(var(--muted-foreground))]">
                  {{ k.api_key_mask || '—' }}
                </div>
                <div class="mt-3 flex flex-wrap gap-2">
                  <Button
                    v-if="k.is_default !== 1"
                    size="small"
                    type="primary"
                    ghost
                    @click="handleSetDefaultKey(k.id)"
                  >
                    设为默认
                  </Button>
                  <Button size="small" @click="openKeyModal(k)">编辑</Button>
                  <Popconfirm title="确认删除该密钥？" @confirm="handleDeleteKey(k.id)">
                    <Button size="small" danger>删除</Button>
                  </Popconfirm>
                </div>
              </div>
            </div>
          </Tabs.TabPane>

          <Tabs.TabPane key="models" tab="模型管理">
            <div class="mb-2 flex justify-end">
              <Button type="primary" size="small" @click="openModelModal()">新增模型</Button>
            </div>
            <div
              v-if="!models.length"
              class="rounded-lg border border-dashed border-[hsl(var(--border))] p-4 text-sm text-[hsl(var(--muted-foreground))]"
            >
              暂无模型
            </div>
            <div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2">
              <div
                v-for="m in models"
                :key="m.id"
                class="rounded-lg border border-[hsl(var(--border))] p-3"
              >
                <div class="flex flex-wrap items-center gap-2">
                  <span class="font-medium">{{ m.name }}</span>
                  <Tag v-if="m.is_default === 1" color="gold">默认</Tag>
                  <Tag :color="m.status === 1 ? 'success' : 'default'">
                    {{ m.status === 1 ? '启用' : '禁用' }}
                  </Tag>
                </div>
                <div class="mt-1 text-xs text-[hsl(var(--muted-foreground))]">{{ m.code }}</div>
                <div class="mt-3 flex flex-wrap gap-2">
                  <Button
                    v-if="m.is_default !== 1"
                    size="small"
                    type="primary"
                    ghost
                    @click="handleSetDefaultModel(m.id)"
                  >
                    设为默认
                  </Button>
                  <Button size="small" @click="openModelModal(m)">编辑</Button>
                  <Popconfirm title="确认删除该模型？" @confirm="handleDeleteModel(m.id)">
                    <Button size="small" danger>删除</Button>
                  </Popconfirm>
                </div>
              </div>
            </div>
          </Tabs.TabPane>
        </Tabs>
      </div>
    </Spin>
  </Drawer>
</template>

<style scoped>
.ai-plat-tabs :deep(.ant-tabs-content) {
  height: 100%;
  overflow: auto;
}
</style>
