<script lang="ts" setup>
import type {
  DefaultModel,
  ModelListItem,
  ProviderListItem,
  ProviderType,
} from '#/api/ai-platform/ai-platform';

import { computed, ref } from 'vue';

import {
  Bot,
  Check,
  ChevronDown,
  ChevronUp,
  Database,
  Edit,
  Layers,
  MessageSquare,
  MoreHorizontal,
  Play,
  Plus,
  RefreshCw,
  Search,
  Server,
  Trash2,
} from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCheckbox,
  ElCheckboxButton,
  ElCheckboxGroup,
  ElDialog,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElEmpty,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElSelect,
  ElSwitch,
  ElTag,
} from 'element-plus';

import {
  batchCreateModelsApi,
  createModelApi,
  createProviderApi,
  deleteModelApi,
  deleteProviderApi,
  fetchProviderModelsApi,
  getModelListApi,
  getProviderDefaultModelsApi,
  getProviderListApi,
  getProviderTypesApi,
  testProviderApi,
  updateModelApi,
  updateProviderApi,
} from '#/api/ai-platform/ai-platform';

defineOptions({ name: 'ModelConfigForm' });

// 状态
const loading = ref(false);

// 提供商相关
const providerTypes = ref<ProviderType[]>([]);
const providers = ref<ProviderListItem[]>([]);
const selectedProviderId = ref(''); // 当前选中的提供商ID
const showProviderDialog = ref(false);
const providerDialogMode = ref<'add' | 'edit'>('add');
const providerForm = ref({
  id: '',
  name: '',
  provider_type: '',
  api_key: '',
  api_base: '',
  ollama_host: 'http://localhost:11434',
  description: '',
  is_active: true,
});

// 模型相关
const models = ref<ModelListItem[]>([]);
const showModelDialog = ref(false);
const modelDialogMode = ref<'add' | 'edit'>('add');
const modelForm = ref({
  id: '',
  provider_id: '',
  model_name: '',
  display_name: '',
  model_type: 'chat',
  max_tokens: 4096,
  context_window: 4096,
  default_temperature: 0.7,
  supports_vision: false,
  supports_function_call: false,
  is_active: true,
});

// 默认模型
const defaultModels = ref<DefaultModel[]>([]);
const showDefaultModelsDialog = ref(false);
const selectedDefaultModels = ref<string[]>([]);
const defaultModelsLoading = ref(false);
const showAvailableModels = ref(true);
const modelSource = ref<'' | 'api' | 'default'>('');
const filterModelTypes = ref<string[]>([]);
const filterModelSearch = ref('');

// 计算属性
const filteredModels = computed(() => {
  if (!selectedProviderId.value) return models.value;
  return models.value.filter((m) => m.provider_id === selectedProviderId.value);
});

// 初始化
async function init() {
  loading.value = true;
  try {
    const [typesRes, providersRes, modelsRes] = await Promise.all([
      getProviderTypesApi(),
      getProviderListApi({ pageSize: 100 }),
      getModelListApi({ pageSize: 100 }),
    ]);
    providerTypes.value = typesRes;
    providers.value = providersRes.items;
    models.value = modelsRes.items;

    // 自动选中第一个提供商
    if (providers.value.length > 0 && !selectedProviderId.value) {
      selectedProviderId.value = providers.value[0]?.id || '';
    }
  } catch (error) {
    console.error('加载数据失败:', error);
  } finally {
    loading.value = false;
  }
}

// 选择提供商
async function selectProvider(providerId: string) {
  selectedProviderId.value = providerId;
  await loadDefaultModelsForProvider(providerId);
}

// 自动加载当前提供商的模型列表（优先在线拉取，fallback 到默认列表）
async function loadDefaultModelsForProvider(providerId: string) {
  if (!providerId) {
    defaultModels.value = [];
    modelSource.value = '';
    return;
  }
  defaultModelsLoading.value = true;
  try {
    const res = await fetchProviderModelsApi(providerId);
    defaultModels.value = res.models || [];
    modelSource.value = (res.source as 'api' | 'default') || 'default';
  } catch {
    // 在线拉取失败，fallback 到默认列表
    try {
      defaultModels.value = await getProviderDefaultModelsApi(providerId);
      modelSource.value = 'default';
    } catch {
      defaultModels.value = [];
      modelSource.value = '';
    }
  } finally {
    defaultModelsLoading.value = false;
  }
}

// 强制刷新：重新在线拉取模型列表
async function handleRefreshModels() {
  if (!selectedProviderId.value) return;
  await loadDefaultModelsForProvider(selectedProviderId.value);
  if (modelSource.value === 'api') {
    ElMessage.success($t('ui-config.model.fetchFromApiSuccess'));
  } else {
    ElMessage.info($t('ui-config.model.fetchFromApiFallback'));
  }
}

// 判断默认模型是否已添加
function isModelAdded(modelName: string) {
  return filteredModels.value.some((m) => m.model_name === modelName);
}

// 可添加的默认模型（未添加的）
const availableDefaultModels = computed(() => {
  return defaultModels.value.filter((m) => !isModelAdded(m.model_name));
});

// 可选模型的类型列表（去重）
const availableModelTypes = computed(() => {
  const types = new Set(defaultModels.value.map((m) => m.model_type));
  return [...types];
});

// 过滤后的默认模型列表
const filteredDefaultModels = computed(() => {
  let list = defaultModels.value;
  if (filterModelTypes.value.length > 0) {
    list = list.filter((m) => filterModelTypes.value.includes(m.model_type));
  }
  if (filterModelSearch.value.trim()) {
    const kw = filterModelSearch.value.trim().toLowerCase();
    list = list.filter(
      (m) =>
        m.model_name.toLowerCase().includes(kw) ||
        m.display_name.toLowerCase().includes(kw),
    );
  }
  return list;
});

// 获取当前选中的提供商
const selectedProvider = computed(() => {
  return providers.value.find((p) => p.id === selectedProviderId.value);
});

init().then(() => {
  if (selectedProviderId.value) {
    loadDefaultModelsForProvider(selectedProviderId.value);
  }
});

// 提供商操作
function handleAddProvider() {
  providerDialogMode.value = 'add';
  providerForm.value = {
    id: '',
    name: '',
    provider_type: '',
    api_key: '',
    api_base: '',
    ollama_host: 'http://localhost:11434',
    description: '',
    is_active: true,
  };
  showProviderDialog.value = true;
}

function handleEditProvider(row: ProviderListItem) {
  providerDialogMode.value = 'edit';
  providerForm.value = {
    id: row.id,
    name: row.name,
    provider_type: row.provider_type,
    api_key: '',
    api_base: '',
    ollama_host: 'http://localhost:11434',
    description: row.description,
    is_active: row.is_active,
  };
  showProviderDialog.value = true;
}

async function handleSaveProvider() {
  try {
    if (providerDialogMode.value === 'add') {
      await createProviderApi(providerForm.value);
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    } else {
      await updateProviderApi(providerForm.value.id, providerForm.value);
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    }
    showProviderDialog.value = false;
    init();
  } catch (error: any) {
    ElMessage.error(error.message || $t('ui.actionMessage.operationFailed'));
  }
}

async function handleDeleteProvider(row: ProviderListItem) {
  try {
    await ElMessageBox.confirm(
      $t('ui.actionMessage.deleteConfirm', [row.name]),
      $t('ui.actionTitle.delete', [$t('ui-config.model.providerName')]),
      { type: 'warning' },
    );
    await deleteProviderApi(row.id);
    ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
    init();
  } catch {
    // 用户取消
  }
}

async function handleTestProvider(row: ProviderListItem) {
  try {
    const res = await testProviderApi(row.id);
    if (res.success) {
      ElMessage.success(res.message);
    } else {
      ElMessage.error($t('ui.actionMessage.operationFailed'));
    }
  } catch (error: any) {
    ElMessage.error(error.message || $t('ui.actionMessage.operationFailed'));
  }
}

// 加载默认模型（弹窗方式，保留兼容）
async function handleLoadDefaultModels(providerId: string) {
  try {
    defaultModels.value = await getProviderDefaultModelsApi(providerId);
    selectedDefaultModels.value = [];
    selectedProviderId.value = providerId;
    showDefaultModelsDialog.value = true;
  } catch (error: any) {
    ElMessage.error(error.message || $t('ui.actionMessage.operationFailed'));
  }
}

function toggleDefaultModelSelection(modelName: string) {
  const index = selectedDefaultModels.value.indexOf(modelName);
  if (index === -1) {
    selectedDefaultModels.value.push(modelName);
  } else {
    selectedDefaultModels.value.splice(index, 1);
  }
}

async function handleBatchAddModels() {
  if (selectedDefaultModels.value.length === 0) {
    ElMessage.warning($t('ui.placeholder.select'));
    return;
  }

  const modelsToAdd = defaultModels.value.filter((m) =>
    selectedDefaultModels.value.includes(m.model_name),
  );

  try {
    await batchCreateModelsApi(selectedProviderId.value, modelsToAdd);
    ElMessage.success($t('ui.actionMessage.operationSuccess'));
    showDefaultModelsDialog.value = false;
    await init();
    await loadDefaultModelsForProvider(selectedProviderId.value);
  } catch (error: any) {
    ElMessage.error(error.message || $t('ui.actionMessage.operationFailed'));
  }
}

// 一键添加单个默认模型
async function handleQuickAddModel(model: DefaultModel) {
  try {
    await batchCreateModelsApi(selectedProviderId.value, [model]);
    ElMessage.success($t('ui.actionMessage.operationSuccess'));
    await init();
    await loadDefaultModelsForProvider(selectedProviderId.value);
  } catch (error: any) {
    ElMessage.error(error.message || $t('ui.actionMessage.operationFailed'));
  }
}

// 一键添加所有未添加的默认模型
async function handleAddAllModels() {
  const modelsToAdd = availableDefaultModels.value;
  if (modelsToAdd.length === 0) return;
  try {
    await batchCreateModelsApi(selectedProviderId.value, modelsToAdd);
    ElMessage.success($t('ui.actionMessage.operationSuccess'));
    await init();
    await loadDefaultModelsForProvider(selectedProviderId.value);
  } catch (error: any) {
    ElMessage.error(error.message || $t('ui.actionMessage.operationFailed'));
  }
}

// 模型操作
function handleAddModel() {
  modelDialogMode.value = 'add';
  modelForm.value = {
    id: '',
    provider_id: selectedProviderId.value || '',
    model_name: '',
    display_name: '',
    model_type: 'chat',
    max_tokens: 4096,
    context_window: 4096,
    default_temperature: 0.7,
    supports_vision: false,
    supports_function_call: false,
    is_active: true,
  };
  showModelDialog.value = true;
}

function handleEditModel(row: ModelListItem) {
  modelDialogMode.value = 'edit';
  modelForm.value = {
    id: row.id,
    provider_id: row.provider_id,
    model_name: row.model_name,
    display_name: row.display_name,
    model_type: row.model_type,
    max_tokens: 4096,
    context_window: 4096,
    default_temperature: 0.7,
    supports_vision: false,
    supports_function_call: false,
    is_active: row.is_active,
  };
  showModelDialog.value = true;
}

async function handleSaveModel() {
  try {
    if (modelDialogMode.value === 'add') {
      await createModelApi(modelForm.value);
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    } else {
      await updateModelApi(modelForm.value.id, modelForm.value);
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    }
    showModelDialog.value = false;
    await init();
    await loadDefaultModelsForProvider(selectedProviderId.value);
  } catch (error: any) {
    ElMessage.error(error.message || $t('ui.actionMessage.operationFailed'));
  }
}

async function handleDeleteModel(row: ModelListItem) {
  try {
    await ElMessageBox.confirm(
      $t('ui.actionMessage.deleteConfirm', [row.display_name]),
      $t('ui.actionTitle.delete', [$t('ui-config.model.modelName')]),
      { type: 'warning' },
    );
    await deleteModelApi(row.id);
    ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.display_name]));
    await init();
    await loadDefaultModelsForProvider(selectedProviderId.value);
  } catch {
    // 用户取消
  }
}

// 获取提供商类型名称
function getProviderTypeName(type: string) {
  const found = providerTypes.value.find((t) => t.type === type);
  return found?.name || type;
}

// 获取模型类型文本
function getModelTypeText(type: string) {
  switch (type) {
    case 'chat': {
      return $t('ui-config.model.chat');
    }
    case 'embedding': {
      return $t('ui-config.model.embedding');
    }
    case 'rerank': {
      return $t('ui-config.model.rerank');
    }
    default: {
      return type;
    }
  }
}

function getModelTypeIcon(type: string) {
  switch (type) {
    case 'chat': {
      return MessageSquare;
    }
    case 'embedding': {
      return Database;
    }
    case 'rerank': {
      return Layers;
    }
    default: {
      return Bot;
    }
  }
}

function getModelTypeTagType(type: string) {
  switch (type) {
    case 'chat': {
      return 'primary';
    }
    case 'completion': {
      return 'success';
    }
    case 'embedding': {
      return 'info';
    }
    case 'rerank': {
      return 'warning';
    }
    default: {
      return 'info';
    }
  }
}

// 暴露重置方法
function reset() {
  init();
}

defineExpose({ reset });
</script>

<template>
  <div class="model-config-form flex h-full gap-3">
    <!-- 左侧：提供商列表 -->
    <div
      class="provider-section bg-background flex w-72 flex-col rounded-[8px] p-5"
      v-loading="loading"
    >
      <!-- 提供商 Header -->
      <div class="mb-3 flex items-center justify-between">
        <div class="">{{ $t('ui-config.model.providerManagement') }}</div>
        <ElButton
          size="small"
          type="primary"
          plain
          :icon="Plus"
          @click="handleAddProvider"
        >
          {{ $t('ui-config.model.addProvider') }}
        </ElButton>
      </div>

      <!-- 提供商列表 -->
      <div v-if="providers.length > 0" class="flex-1 space-y-2 overflow-y-auto">
        <div
          v-for="provider in providers"
          :key="provider.id"
          class="provider-item"
          :class="{ selected: selectedProviderId === provider.id }"
        >
          <div
            class="flex items-center gap-3"
            @click="selectProvider(provider.id)"
          >
            <div class="provider-icon-small">
              <Server class="h-4 w-4 text-white" />
            </div>
            <div class="flex-1">
              <div class="flex items-center gap-2">
                <span class="text-sm font-medium">{{ provider.name }}</span>
                <ElTag
                  size="small"
                  :type="provider.is_active ? 'success' : 'info'"
                >
                  {{
                    provider.is_active
                      ? $t('ui-config.model.enabled')
                      : $t('common.disabled')
                  }}
                </ElTag>
              </div>
              <div class="text-muted-foreground mt-0.5 text-xs">
                {{ getProviderTypeName(provider.provider_type) }}
              </div>
            </div>
          </div>
          <ElDropdown trigger="click" @click.stop>
            <ElButton link size="small" class="ml-2">
              <MoreHorizontal class="h-4 w-4" />
            </ElButton>
            <template #dropdown>
              <ElDropdownMenu>
                <ElDropdownItem @click="handleTestProvider(provider)">
                  <Play class="mr-1 h-4 w-4" />
                  {{ $t('ui-config.model.test') }}
                </ElDropdownItem>
                <ElDropdownItem @click="handleLoadDefaultModels(provider.id)">
                  <Plus class="mr-1 h-4 w-4" />
                  {{ $t('ui-config.model.addModel') }}
                </ElDropdownItem>
                <ElDropdownItem @click="handleEditProvider(provider)">
                  <Edit class="mr-1 h-4 w-4" />
                  {{ $t('ui-config.edit') }}
                </ElDropdownItem>
                <ElDropdownItem divided @click="handleDeleteProvider(provider)">
                  <Trash2 class="mr-1 h-4 w-4 text-red-500" />
                  <span class="text-red-500">{{ $t('common.delete') }}</span>
                </ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </div>
      </div>
      <ElEmpty v-else :description="$t('ui-config.model.noDefaultModels')" />
    </div>

    <!-- 右侧：模型列表 -->
    <div
      class="model-section bg-background flex flex-1 flex-col rounded-[8px] p-5"
      v-loading="loading"
    >
      <!-- 模型 Header -->
      <div class="mb-3 flex items-center justify-between">
        <h3 class="">{{ $t('ui-config.model.modelManagement') }}</h3>
        <ElButton
          type="primary"
          plain
          size="small"
          :icon="Plus"
          @click="handleAddModel"
        >
          {{ $t('ui-config.model.addModel') }}
        </ElButton>
      </div>

      <!-- 当前选中的提供商信息 -->
      <div
        v-if="selectedProvider"
        class="mb-4 flex items-center gap-3 rounded-lg border p-3"
      >
        <div class="provider-icon">
          <Server class="h-5 w-5 text-white" />
        </div>
        <div class="flex-1">
          <div class="flex items-center gap-2">
            <span class="font-medium">{{ selectedProvider.name }}</span>
            <ElTag size="small">
              {{ getProviderTypeName(selectedProvider.provider_type) }}
            </ElTag>
          </div>
          <div class="text-muted-foreground text-xs">
            {{
              selectedProvider.description ||
              $t('ui-config.descriptionPlaceholder')
            }}
          </div>
        </div>
      </div>

      <div class="flex-1 space-y-4 overflow-y-auto">
        <!-- 已添加的模型列表 -->
        <div v-if="filteredModels.length > 0" class="space-y-3">
          <div class="text-muted-foreground text-xs font-medium">
            {{ $t('ui-config.model.addedModels') }} ({{
              filteredModels.length
            }})
          </div>
          <div
            v-for="model in filteredModels"
            :key="model.id"
            class="model-card"
          >
            <div class="flex items-center gap-3">
              <div
                class="model-icon"
                :class="getModelTypeTagType(model.model_type)"
              >
                <component
                  :is="getModelTypeIcon(model.model_type)"
                  class="h-5 w-5 text-white"
                />
              </div>
              <div class="flex-1">
                <div class="flex items-center gap-2">
                  <span class="font-medium">{{ model.display_name }}</span>
                  <ElTag
                    size="small"
                    :type="getModelTypeTagType(model.model_type)"
                  >
                    {{ getModelTypeText(model.model_type) }}
                  </ElTag>
                  <ElTag
                    size="small"
                    :type="model.is_active ? 'success' : 'info'"
                  >
                    {{
                      model.is_active
                        ? $t('ui-config.model.enabled')
                        : $t('common.disabled')
                    }}
                  </ElTag>
                </div>
                <div class="text-muted-foreground mt-1 text-xs">
                  {{ model.model_name }}
                </div>
              </div>
              <div class="flex items-center gap-2">
                <ElButton
                  link
                  type="primary"
                  size="small"
                  @click="handleEditModel(model)"
                >
                  <Edit class="mr-1 h-4 w-4" />
                  {{ $t('ui-config.edit') }}
                </ElButton>
                <ElButton
                  link
                  type="danger"
                  size="small"
                  @click="handleDeleteModel(model)"
                >
                  <Trash2 class="mr-1 h-4 w-4" />
                  {{ $t('common.delete') }}
                </ElButton>
              </div>
            </div>
          </div>
        </div>

        <!-- 可选的默认模型列表 -->
        <div
          v-if="selectedProvider && defaultModels.length > 0"
          class="available-models-section"
        >
          <div class="mb-2 flex flex-wrap items-center justify-between gap-2">
            <div
              class="flex cursor-pointer items-center gap-2"
              @click="showAvailableModels = !showAvailableModels"
            >
              <component
                :is="showAvailableModels ? ChevronUp : ChevronDown"
                class="text-muted-foreground h-4 w-4"
              />
              <span class="text-muted-foreground text-xs font-medium">
                {{ $t('ui-config.model.availableModels') }} ({{
                  availableDefaultModels.length
                }})
              </span>
              <ElTag
                v-if="modelSource"
                size="small"
                :type="modelSource === 'api' ? 'success' : 'info'"
              >
                {{
                  modelSource === 'api'
                    ? $t('ui-config.model.sourceApi')
                    : $t('ui-config.model.sourceDefault')
                }}
              </ElTag>
            </div>
            <div class="flex flex-1 flex-wrap items-center justify-end gap-2">
              <ElCheckboxGroup v-model="filterModelTypes" size="small">
                <ElCheckboxButton
                  v-for="t in availableModelTypes"
                  :key="t"
                  :value="t"
                >
                  {{ getModelTypeText(t) }}
                </ElCheckboxButton>
              </ElCheckboxGroup>
              <ElInput
                v-model="filterModelSearch"
                size="small"
                :placeholder="$t('ui-config.model.searchModel')"
                clearable
                class="!w-40"
              >
                <template #prefix>
                  <Search class="h-3.5 w-3.5" />
                </template>
              </ElInput>
              <ElButton
                size="small"
                plain
                :loading="defaultModelsLoading"
                @click="handleRefreshModels"
              >
                <RefreshCw class="mr-1 h-3 w-3" />
                {{ $t('ui-config.model.refreshModels') }}
              </ElButton>
              <ElButton
                v-if="availableDefaultModels.length > 0"
                size="small"
                type="primary"
                plain
                @click="handleAddAllModels"
              >
                {{ $t('ui-config.model.addAll') }}
              </ElButton>
            </div>
          </div>
          <div
            v-show="showAvailableModels"
            v-loading="defaultModelsLoading"
            class="space-y-2"
          >
            <div
              v-for="dm in filteredDefaultModels"
              :key="dm.model_name"
              class="default-model-inline-item"
              :class="{ 'is-added': isModelAdded(dm.model_name) }"
            >
              <div class="flex flex-1 items-center gap-3">
                <div
                  class="default-model-icon"
                  :class="getModelTypeTagType(dm.model_type)"
                >
                  <component
                    :is="getModelTypeIcon(dm.model_type)"
                    class="h-4 w-4 text-white"
                  />
                </div>
                <div class="min-w-0 flex-1">
                  <div class="flex items-center gap-2">
                    <span class="truncate text-sm font-medium">{{
                      dm.display_name
                    }}</span>
                    <ElTag
                      size="small"
                      :type="getModelTypeTagType(dm.model_type)"
                    >
                      {{ getModelTypeText(dm.model_type) }}
                    </ElTag>
                  </div>
                  <div class="text-muted-foreground mt-0.5 truncate text-xs">
                    {{ dm.model_name }}
                    <span v-if="dm.context_window">
                      · {{ Math.round(dm.context_window / 1024) }}K ctx</span
                    >
                  </div>
                </div>
              </div>
              <div v-if="isModelAdded(dm.model_name)" class="added-badge">
                <Check class="h-4 w-4" />
                <span>{{ $t('ui-config.model.added') }}</span>
              </div>
              <ElButton
                v-else
                size="small"
                type="primary"
                plain
                @click="handleQuickAddModel(dm)"
              >
                <Plus class="mr-1 h-3 w-3" />
                {{ $t('ui-config.model.addModel') }}
              </ElButton>
            </div>
          </div>
        </div>

        <ElEmpty
          v-if="filteredModels.length === 0 && defaultModels.length === 0"
          :description="$t('ui-config.model.noDefaultModels')"
        />
      </div>
    </div>

    <!-- 提供商弹窗 -->
    <ElDialog
      v-model="showProviderDialog"
      :title="
        providerDialogMode === 'add'
          ? $t('ui-config.model.addProvider')
          : $t('ui-config.model.editProvider')
      "
      width="500px"
    >
      <ElForm :model="providerForm" label-width="100px">
        <ElFormItem :label="$t('ui-config.model.providerName')" required>
          <ElInput
            v-model="providerForm.name"
            :placeholder="$t('ui.placeholder.input')"
          />
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.providerType')" required>
          <ElSelect
            v-model="providerForm.provider_type"
            :placeholder="$t('ui.placeholder.select')"
            :disabled="providerDialogMode === 'edit'"
            style="width: 100%"
          >
            <ElOption
              v-for="t in providerTypes"
              :key="t.type"
              :label="t.name"
              :value="t.type"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem
          v-if="providerForm.provider_type !== 'ollama'"
          :label="$t('ui-config.model.apiKey')"
        >
          <ElInput
            v-model="providerForm.api_key"
            type="password"
            :placeholder="$t('ui.placeholder.input')"
            show-password
          />
        </ElFormItem>
        <ElFormItem
          v-if="providerForm.provider_type !== 'ollama'"
          :label="$t('ui-config.model.apiBase')"
        >
          <ElInput
            v-model="providerForm.api_base"
            :placeholder="$t('ui.placeholder.input')"
          />
        </ElFormItem>
        <ElFormItem
          v-if="providerForm.provider_type === 'ollama'"
          :label="$t('ui-config.model.ollamaHost')"
        >
          <ElInput
            v-model="providerForm.ollama_host"
            placeholder="http://localhost:11434"
          />
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.providerDescription')">
          <ElInput
            v-model="providerForm.description"
            type="textarea"
            :rows="3"
            :placeholder="$t('ui.placeholder.input')"
          />
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.enabled')">
          <ElSwitch v-model="providerForm.is_active" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="showProviderDialog = false">
          {{ $t('common.cancel') }}
        </ElButton>
        <ElButton type="primary" @click="handleSaveProvider">
          {{ $t('common.confirm') }}
        </ElButton>
      </template>
    </ElDialog>

    <!-- 模型弹窗 -->
    <ElDialog
      v-model="showModelDialog"
      :title="
        modelDialogMode === 'add'
          ? $t('ui-config.model.addModel')
          : $t('ui-config.model.editModel')
      "
      width="500px"
    >
      <ElForm :model="modelForm" label-width="100px">
        <ElFormItem :label="$t('ui-config.model.providerName')" required>
          <ElSelect
            v-model="modelForm.provider_id"
            :placeholder="$t('ui-config.model.selectProvider')"
            style="width: 100%"
          >
            <ElOption
              v-for="p in providers"
              :key="p.id"
              :label="p.name"
              :value="p.id"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.modelName')" required>
          <ElInput v-model="modelForm.model_name" placeholder="gpt-4o" />
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.displayName')" required>
          <ElInput v-model="modelForm.display_name" placeholder="GPT-4o" />
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.modelType')">
          <ElSelect v-model="modelForm.model_type" style="width: 100%">
            <ElOption :label="$t('ui-config.model.chatModel')" value="chat" />
            <ElOption
              :label="$t('ui-config.model.embeddingModel')"
              value="embedding"
            />
            <ElOption
              :label="$t('ui-config.model.completionModel')"
              value="completion"
            />
            <ElOption
              :label="$t('ui-config.model.rerankModel')"
              value="rerank"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.maxTokens')">
          <ElInputNumber
            v-model="modelForm.max_tokens"
            :min="1"
            :max="128000"
          />
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.supportsVision')">
          <ElSwitch v-model="modelForm.supports_vision" />
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.supportsFunction')">
          <ElSwitch v-model="modelForm.supports_function_call" />
        </ElFormItem>
        <ElFormItem :label="$t('ui-config.model.enabled')">
          <ElSwitch v-model="modelForm.is_active" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="showModelDialog = false">
          {{ $t('common.cancel') }}
        </ElButton>
        <ElButton type="primary" @click="handleSaveModel">
          {{ $t('common.confirm') }}
        </ElButton>
      </template>
    </ElDialog>

    <!-- 默认模型选择弹窗 -->
    <ElDialog
      v-model="showDefaultModelsDialog"
      :title="$t('ui-config.model.addDefaultModels')"
      width="600px"
    >
      <div v-if="defaultModels.length === 0" class="py-8">
        <ElEmpty :description="$t('ui-config.model.noDefaultModels')" />
      </div>
      <div v-else class="max-h-[400px] space-y-2 overflow-y-auto">
        <div
          v-for="model in defaultModels"
          :key="model.model_name"
          class="default-model-item"
          :class="{
            selected: selectedDefaultModels.includes(model.model_name),
          }"
          @click="toggleDefaultModelSelection(model.model_name)"
        >
          <ElCheckbox
            :model-value="selectedDefaultModels.includes(model.model_name)"
            @click.stop
            @change="toggleDefaultModelSelection(model.model_name)"
          />
          <div class="ml-3 flex-1">
            <div class="flex items-center gap-2">
              <span class="font-medium">{{ model.display_name }}</span>
              <ElTag size="small">{{ model.model_type }}</ElTag>
            </div>
            <div class="text-muted-foreground mt-1 text-xs">
              {{ model.model_name }} · Max {{ model.max_tokens }} tokens
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <ElButton @click="showDefaultModelsDialog = false">
          {{ $t('common.cancel') }}
        </ElButton>
        <ElButton type="primary" @click="handleBatchAddModels">
          {{ $t('ui-config.model.addSelected') }} ({{
            selectedDefaultModels.length
          }})
        </ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.model-config-form {
  height: calc(100vh - 110px);
}

.provider-section,
.model-section {
  min-height: 0;
}

.provider-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  transition: all 0.2s;
}

.provider-item:hover {
  background: var(--el-fill-color-light);
  border-color: var(--el-color-primary-light-5);
}

.provider-item.selected {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);
}

.provider-item > div:first-child {
  flex: 1;
  cursor: pointer;
}

.provider-icon-small {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: linear-gradient(
    135deg,
    var(--el-color-primary-light-3),
    var(--el-color-primary)
  );
  border-radius: 8px;
  flex-shrink: 0;
}

.provider-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: linear-gradient(
    135deg,
    var(--el-color-primary-light-3),
    var(--el-color-primary)
  );
  border-radius: 10px;
  flex-shrink: 0;
}

.model-card {
  padding: 12px 16px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  transition: all 0.2s;
}

.model-card:hover {
  border-color: var(--el-color-primary-light-5);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.model-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: linear-gradient(
    135deg,
    var(--el-color-info-light-3),
    var(--el-color-info)
  );
  border-radius: 10px;
  flex-shrink: 0;
}

.model-icon.primary {
  background: linear-gradient(
    135deg,
    var(--el-color-primary-light-3),
    var(--el-color-primary)
  );
}

.model-icon.info {
  background: linear-gradient(
    135deg,
    var(--el-color-info-light-3),
    var(--el-color-info)
  );
}

.model-icon.warning {
  background: linear-gradient(
    135deg,
    var(--el-color-warning-light-3),
    var(--el-color-warning)
  );
}

.model-icon.success {
  background: linear-gradient(
    135deg,
    var(--el-color-success-light-3),
    var(--el-color-success)
  );
}

.default-model-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  transition: all 0.2s;
}

.default-model-item:hover {
  background: var(--el-fill-color-light);
}

.default-model-item.selected {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-5);
}

.available-models-section {
  padding-top: 12px;
}

.default-model-inline-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  transition: all 0.2s;
}

.default-model-inline-item:hover {
  background: var(--el-fill-color-light);
}

.default-model-inline-item.is-added {
  opacity: 0.7;
  background: var(--el-fill-color-lighter);
}

.default-model-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  flex-shrink: 0;
}

.default-model-icon.primary {
  background: linear-gradient(
    135deg,
    var(--el-color-primary-light-3),
    var(--el-color-primary)
  );
}

.default-model-icon.info {
  background: linear-gradient(
    135deg,
    var(--el-color-info-light-3),
    var(--el-color-info)
  );
}

.default-model-icon.warning {
  background: linear-gradient(
    135deg,
    var(--el-color-warning-light-3),
    var(--el-color-warning)
  );
}

.default-model-icon.success {
  background: linear-gradient(
    135deg,
    var(--el-color-success-light-3),
    var(--el-color-success)
  );
}

.added-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-color-success);
  flex-shrink: 0;
}
</style>
