<script lang="ts" setup>
/**
 * AI API Key 新增/编辑
 * 所属平台用带 Logo 的卡片单选（与系统配置 AI 卡片一致），敏感字段 api_key 走传输加密
 */
import { ref } from 'vue';

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

import { Radio, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

import { getAiPlatformConfigOptions } from '../../platform/api';
import {
  createAiApiKey,
  getAiApiKeyDetail,
  updateAiApiKey,
} from '../api';
import { modalFormProps } from '../config/form';

interface PlatformCard {
  id: number;
  code: string;
  name: string;
  logo: string;
  description: string;
  default_model: string;
}

const isUpdate = ref(false);
const gridApi = ref();
const onSuccess = ref<null | (() => void)>(null);
const lockPlatformId = ref(false);
const platforms = ref<PlatformCard[]>([]);
const selectedPlatformId = ref<number | undefined>(undefined);

const [Form, formApi] = useVbenForm(modalFormProps);

/** 点选平台卡片：同步到隐藏字段 platform_id */
function onSelectPlatform(id: number) {
  if (lockPlatformId.value) return;
  selectedPlatformId.value = id;
  formApi.setValues({ platform_id: id });
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (!selectedPlatformId.value) {
      message.warning('请选择所属 AI 平台');
      return;
    }
    formApi.setValues({ platform_id: selectedPlatformId.value });
    const e = await formApi.validate();
    if (!e.valid) return;
    const values = await formApi.getValues();
    values.platform_id = selectedPlatformId.value;
    // 编辑时允许不改密钥：空串不传
    if (isUpdate.value && !String(values.api_key || '').trim()) {
      delete values.api_key;
    } else if (!isUpdate.value && !String(values.api_key || '').trim()) {
      message.warning('请填写 API Key');
      return;
    }
    modalApi.setState({ confirmLoading: true });
    try {
      const api = isUpdate.value ? updateAiApiKey : createAiApiKey;
      await api(values);
      message.success('保存成功');
      gridApi.value?.query?.();
      onSuccess.value?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    const openData = isOpen ? modalApi.getData<Record<string, any>>() || {} : {};
    gridApi.value = isOpen ? openData.gridApi : null;
    onSuccess.value = isOpen
      ? (typeof openData.onSuccess === 'function' ? openData.onSuccess : null)
      : null;
    lockPlatformId.value = isOpen ? !!openData.lockPlatformId : false;
    if (!isOpen) {
      formApi.resetForm();
      selectedPlatformId.value = undefined;
      platforms.value = [];
      return;
    }
    // 拉取启用中的平台卡片（含 logo）
    try {
      const res = await getAiPlatformConfigOptions();
      const data = res?.data || res || {};
      platforms.value = Array.isArray(data.platforms) ? data.platforms : [];
    } catch {
      platforms.value = [];
    }
    const { values, update } = openData;
    isUpdate.value = !!update;
    if (values && update && values.id) {
      try {
        const detail = await getAiApiKeyDetail(values.id);
        const row = detail?.data || detail || {};
        const pid = Number(row.platform_id || 0) || undefined;
        selectedPlatformId.value = pid;
        formApi.setValues({
          ...row,
          platform_id: pid,
          api_key: row.api_key || '',
        });
      } catch {
        const pid = Number(values.platform_id || 0) || undefined;
        selectedPlatformId.value = pid;
        formApi.setValues({ ...values, platform_id: pid, api_key: '' });
      }
    } else {
      formApi.resetForm();
      const presetPid = Number(openData.platform_id || values?.platform_id || 0) || undefined;
      const firstId = presetPid || platforms.value[0]?.id;
      selectedPlatformId.value = firstId;
      formApi.setValues({
        sort: 0,
        status: 1,
        api_key: '',
        platform_id: firstId,
        is_default: 0,
      });
    }
  },
});
</script>

<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}AI密钥`" class="w-[720px]">
    <div v-if="!lockPlatformId" class="ai-key-modal mb-4">
      <div class="mb-2 text-sm font-medium text-[hsl(var(--foreground))]">
        所属平台
      </div>
      <Radio.Group
        :value="selectedPlatformId"
        class="w-full"
        @update:value="(v: number) => onSelectPlatform(v)"
      >
        <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <label
            v-for="p in platforms"
            :key="p.id"
            class="ai-plat-card"
            :class="{ 'ai-plat-card--active': selectedPlatformId === p.id }"
            @click.prevent="onSelectPlatform(p.id)"
          >
            <Radio :value="p.id" class="!hidden" />
            <div class="flex items-start gap-3">
              <div class="ai-plat-logo">
                <img
                  v-if="p.logo"
                  :src="p.logo"
                  :alt="p.name"
                  class="h-full w-full object-contain"
                />
                <span v-else class="ai-plat-logo-fallback">
                  {{ (p.name || p.code || '?').slice(0, 1) }}
                </span>
              </div>
              <div class="min-w-0 flex-1">
                <div class="font-medium text-[hsl(var(--foreground))]">
                  {{ p.name }}
                </div>
                <div class="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 || '' }}
                </div>
              </div>
            </div>
          </label>
        </div>
      </Radio.Group>
      <div
        v-if="!platforms.length"
        class="mt-2 text-xs text-amber-600 dark:text-amber-400"
      >
        暂无启用中的 AI 平台，请先到「AI平台管理」添加
      </div>
    </div>
    <Form />
  </Modal>
</template>

<style scoped>
.ai-plat-card {
  display: block;
  cursor: pointer;
  border: 1px solid hsl(var(--border));
  border-radius: 10px;
  padding: 12px 14px;
  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-plat-card:hover {
  border-color: hsl(var(--primary) / 0.55);
}
.ai-plat-card--active {
  border-color: hsl(var(--primary));
  box-shadow: 0 0 0 2px hsl(var(--primary) / 0.22);
  background: hsl(var(--primary) / 0.1);
}
.ai-plat-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-plat-logo-fallback {
  font-size: 15px;
  font-weight: 600;
  color: hsl(var(--muted-foreground));
}
</style>
