<script lang="ts" setup>
/**
 * AI 平台管理（一级仅平台卡片）
 * 点击平台打开详情抽屉（二级页）：概览 / 消耗 / 请求 / Key·模型管理
 */
import { onMounted, ref, watch } from 'vue';

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

import { Button, Input, Popconfirm, Spin, Tag, message } from 'ant-design-vue';

import {
  deleteAiPlatform,
  getAiPlatformManageBoard,
  setAiPlatformActive,
} from './api';
import FormModal from './components/modal.vue';
import PlatformDetail from './components/platform-detail.vue';

defineOptions({ name: 'AiPlatform' });

interface PlatformBoard {
  id: number;
  code: string;
  name: string;
  api_url: string;
  default_model: string;
  logo: string;
  description: string;
  status: number;
  is_active: number;
  models?: any[];
  keys?: any[];
}

const loading = ref(false);
const keyword = ref('');
const platforms = ref<PlatformBoard[]>([]);
const activeProvider = ref('');
let searchTimer: ReturnType<typeof setTimeout> | null = null;

async function loadBoard() {
  loading.value = true;
  try {
    const res = await getAiPlatformManageBoard({
      keyword: keyword.value.trim() || undefined,
    });
    const data = res?.data || res || {};
    platforms.value = Array.isArray(data.platforms) ? data.platforms : [];
    activeProvider.value = String(data.active?.provider || '');
  } finally {
    loading.value = false;
  }
}

/** 输入防抖后模糊搜索 */
function onKeywordChange() {
  if (searchTimer) clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    void loadBoard();
  }, 280);
}

watch(keyword, () => onKeywordChange());

const [PlatformModalComp, platformModalApi] = useVbenModal({
  connectedComponent: FormModal,
});

const [DetailDrawer, detailDrawerApi] = useVbenDrawer({
  connectedComponent: PlatformDetail,
});

function openPlatformModal(row?: PlatformBoard) {
  platformModalApi.setData({
    values: row || {},
    update: !!row?.id,
    onSuccess: loadBoard,
  });
  platformModalApi.open();
}

/** 打开平台详情抽屉（模拟二级页） */
function openPlatformDetail(p: PlatformBoard) {
  detailDrawerApi.setData({
    platformId: p.id,
    onChanged: loadBoard,
  });
  detailDrawerApi.open();
}

async function handleDeletePlatform(id: number) {
  await deleteAiPlatform({ ids: [id] });
  message.success('已删除平台');
  await loadBoard();
}

async function handleSetActivePlatform(id: number) {
  await setAiPlatformActive({ id });
  message.success('已设为当前选用平台');
  await loadBoard();
}

onMounted(() => {
  void loadBoard();
});
</script>

<template>
  <Page auto-content-height>
    <PlatformModalComp />
    <DetailDrawer />
    <Spin :spinning="loading">
      <div class="ai-board space-y-4 p-1">
        <div class="flex flex-wrap items-center gap-3">
          <Input
            v-model:value="keyword"
            allow-clear
            class="max-w-md"
            placeholder="模糊搜索平台 / 模型 / 密钥"
          />
          <Button type="primary" @click="openPlatformModal()">新增平台</Button>
          <Button @click="loadBoard">刷新</Button>
          <span class="text-xs text-[hsl(var(--muted-foreground))]">
            当前选用：{{ activeProvider || '—' }}
          </span>
        </div>

        <div>
          <div class="mb-2 font-medium text-[hsl(var(--foreground))]">平台</div>
          <div
            v-if="!platforms.length"
            class="rounded-lg border border-dashed border-[hsl(var(--border))] p-6 text-sm text-[hsl(var(--muted-foreground))]"
          >
            暂无平台，请先新增
          </div>
          <div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
            <div
              v-for="p in platforms"
              :key="p.id"
              class="ai-board-card"
              :class="{ 'ai-board-card--current': p.is_active === 1 }"
              @click="openPlatformDetail(p)"
            >
              <div class="flex items-start gap-3">
                <div class="ai-board-logo">
                  <img
                    v-if="p.logo"
                    :src="p.logo"
                    :alt="p.name"
                    class="h-full w-full object-contain"
                  />
                  <span v-else class="ai-board-logo-fallback">
                    {{ (p.name || p.code || '?').slice(0, 1) }}
                  </span>
                </div>
                <div class="min-w-0 flex-1">
                  <div class="flex flex-wrap items-center gap-2">
                    <span class="font-medium text-[hsl(var(--foreground))]">
                      {{ p.name }}
                    </span>
                    <Tag v-if="p.is_active === 1" color="processing">当前选用</Tag>
                    <Tag :color="p.status === 1 ? 'success' : 'default'">
                      {{ p.status === 1 ? '启用' : '禁用' }}
                    </Tag>
                  </div>
                  <div class="mt-1 text-xs text-[hsl(var(--muted-foreground))]">
                    {{ p.code }} · 默认 {{ p.default_model || '—' }}
                  </div>
                  <div class="mt-1 line-clamp-2 text-xs text-[hsl(var(--muted-foreground))]">
                    {{ p.description || p.api_url }}
                  </div>
                  <div class="mt-1 text-xs text-[hsl(var(--muted-foreground))]">
                    模型 {{ p.models?.length || 0 }} · 密钥 {{ p.keys?.length || 0 }}
                  </div>
                </div>
              </div>
              <div class="mt-3 flex flex-wrap gap-2" @click.stop>
                <Button
                  v-if="p.is_active !== 1"
                  size="small"
                  type="primary"
                  ghost
                  @click="handleSetActivePlatform(p.id)"
                >
                  设为当前
                </Button>
                <Button size="small" @click="openPlatformModal(p)">编辑</Button>
                <Button size="small" type="link" @click="openPlatformDetail(p)">
                  详情
                </Button>
                <Popconfirm title="确认删除该平台？" @confirm="handleDeletePlatform(p.id)">
                  <Button size="small" danger>删除</Button>
                </Popconfirm>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Spin>
  </Page>
</template>

<style scoped>
.ai-board-card {
  cursor: pointer;
  border: 1px solid hsl(var(--border));
  border-radius: 10px;
  padding: 14px 16px;
  background: hsl(var(--card));
  color: hsl(var(--foreground));
  transition:
    border-color 0.15s ease,
    box-shadow 0.15s ease,
    background-color 0.15s ease;
}
.ai-board-card:hover {
  border-color: hsl(var(--primary) / 0.55);
}
.ai-board-card--current {
  border-color: hsl(var(--primary) / 0.75);
}
.ai-board-logo {
  display: flex;
  height: 44px;
  width: 44px;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border-radius: 10px;
  border: 1px solid hsl(var(--border));
  background: hsl(var(--muted) / 0.55);
  padding: 5px;
}
.ai-board-logo-fallback {
  font-size: 15px;
  font-weight: 600;
  color: hsl(var(--muted-foreground));
}
</style>
