<template>
  <div class="page-content">
    <div class="mb-5 flex items-center justify-between gap-4">
      <div>
        <h2 class="text-xl font-semibold">模型路由</h2>
        <p class="text-g-500 mt-1 text-sm">统一对外模型名，按优先级、条件和权重选择上游 Provider</p>
      </div>
      <ElButton type="primary" @click="openCreate">新建路由</ElButton>
    </div>

    <ElAlert class="mb-4" type="info" :closable="false" title="同一别名只使用匹配规则中的最高优先级组，再按权重稳定分流；显式 X-Gateway-Provider 会限制候选范围。" />
    <ElTable v-loading="loading" :data="routes" row-key="id">
      <ElTableColumn prop="name" label="名称" min-width="150" />
      <ElTableColumn prop="source_model" label="对外模型" min-width="180" />
      <ElTableColumn label="目标" min-width="250">
        <template #default="{ row }"><ElTag>{{ row.provider_code }}</ElTag><span class="ml-2">{{ row.target_model }}</span></template>
      </ElTableColumn>
      <ElTableColumn prop="priority" label="优先级" width="90" />
      <ElTableColumn prop="weight" label="权重" width="80" />
      <ElTableColumn label="条件" min-width="220">
        <template #default="{ row }">
          <span v-if="conditionCount(row.conditions) === 0" class="text-g-500">全部请求</span>
          <ElTag v-for="item in conditionLabels(row.conditions)" :key="item" class="mr-1" type="info">{{ item }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn label="状态" width="90"><template #default="{ row }"><ElTag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</ElTag></template></ElTableColumn>
      <ElTableColumn label="操作" width="140" fixed="right">
        <template #default="{ row }"><ElButton link type="primary" @click="openEdit(row)">编辑</ElButton><ElButton link type="danger" @click="remove(row)">删除</ElButton></template>
      </ElTableColumn>
    </ElTable>

    <ElDialog v-model="dialogVisible" :title="editingID ? '编辑模型路由' : '新建模型路由'" width="680px">
      <ElForm ref="formRef" :model="form" :rules="rules" label-width="110px">
        <ElFormItem label="名称" prop="name"><ElInput v-model="form.name" maxlength="128" /></ElFormItem>
        <ElFormItem label="对外模型" prop="sourceModel"><ElInput v-model="form.sourceModel" placeholder="例如 company-chat" /></ElFormItem>
        <ElFormItem label="Provider" prop="providerID"><ElSelect v-model="form.providerID" class="w-full"><ElOption v-for="provider in activeProviders" :key="provider.id" :label="provider.code" :value="provider.id" /></ElSelect></ElFormItem>
        <ElFormItem label="上游模型" prop="targetModel"><ElInput v-model="form.targetModel" placeholder="例如 gpt-5.2" /></ElFormItem>
        <ElFormItem label="优先级"><ElInputNumber v-model="form.priority" :min="-100000" :max="100000" class="w-full" /><div class="text-g-500 mt-1 text-xs">数值越大越优先；只有最高优先级的匹配规则参与权重选择。</div></ElFormItem>
        <ElFormItem label="权重"><ElInputNumber v-model="form.weight" :min="1" :max="10000" class="w-full" /></ElFormItem>
        <ElFormItem label="限定端点"><ElSelect v-model="form.endpoints" multiple clearable class="w-full"><ElOption v-for="endpoint in endpoints" :key="endpoint" :label="endpoint" :value="endpoint" /></ElSelect></ElFormItem>
        <ElFormItem label="API Key IDs"><ElInput v-model="form.apiKeyIDs" placeholder="可选，多个 UUID 用英文逗号分隔" /></ElFormItem>
        <ElFormItem label="Tenant IDs"><ElInput v-model="form.tenantIDs" placeholder="可选，多个 UUID 用英文逗号分隔" /></ElFormItem>
        <ElFormItem label="启用"><ElSwitch v-model="form.enabled" /></ElFormItem>
      </ElForm>
      <template #footer><ElButton @click="dialogVisible = false">取消</ElButton><ElButton type="primary" :loading="saving" @click="save">保存</ElButton></template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
  import { fetchProviders, ProviderRecord } from '@/api/providers'
  import { createModelRoute, deleteModelRoute, fetchModelRoutes, ModelRouteConditions, ModelRouteRecord, updateModelRoute } from '@/api/modelRoutes'

  const endpoints = ['/v1/chat/completions', '/v1/responses', '/v1/embeddings', '/v1/messages']
  const routes = ref<ModelRouteRecord[]>([])
  const providers = ref<ProviderRecord[]>([])
  const activeProviders = computed(() => providers.value.filter((item) => item.enabled))
  const loading = ref(false)
  const saving = ref(false)
  const dialogVisible = ref(false)
  const editingID = ref('')
  const formRef = ref<FormInstance>()
  const form = reactive({ name: '', sourceModel: '', targetModel: '', providerID: '', weight: 100, priority: 100, endpoints: [] as string[], apiKeyIDs: '', tenantIDs: '', enabled: true })
  const rules: FormRules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }], sourceModel: [{ required: true, message: '请输入对外模型', trigger: 'blur' }],
    targetModel: [{ required: true, message: '请输入上游模型', trigger: 'blur' }], providerID: [{ required: true, message: '请选择 Provider', trigger: 'change' }]
  }

  async function load() {
    loading.value = true
    try { [routes.value, providers.value] = await Promise.all([fetchModelRoutes(), fetchProviders()]) } finally { loading.value = false }
  }
  function reset() { Object.assign(form, { name: '', sourceModel: '', targetModel: '', providerID: activeProviders.value[0]?.id || '', weight: 100, priority: 100, endpoints: [], apiKeyIDs: '', tenantIDs: '', enabled: true }) }
  function openCreate() { editingID.value = ''; reset(); dialogVisible.value = true }
  function openEdit(row: ModelRouteRecord) {
    editingID.value = row.id
    Object.assign(form, { name: row.name, sourceModel: row.source_model, targetModel: row.target_model, providerID: row.provider_id, weight: row.weight, priority: row.priority, endpoints: [...(row.conditions.endpoints || [])], apiKeyIDs: (row.conditions.api_key_ids || []).join(', '), tenantIDs: (row.conditions.tenant_ids || []).join(', '), enabled: row.enabled })
    dialogVisible.value = true
  }
  function splitIDs(value: string) { return value.split(',').map((item) => item.trim()).filter(Boolean) }
  async function save() {
    if (!(await formRef.value?.validate())) return
    saving.value = true
    const input = { name: form.name.trim(), source_model: form.sourceModel.trim(), target_model: form.targetModel.trim(), provider_id: form.providerID, weight: form.weight, priority: form.priority, conditions: { endpoints: form.endpoints, api_key_ids: splitIDs(form.apiKeyIDs), tenant_ids: splitIDs(form.tenantIDs) }, enabled: form.enabled }
    try {
      if (editingID.value) await updateModelRoute(editingID.value, input); else await createModelRoute(input)
      dialogVisible.value = false; ElMessage.success('路由配置已生效'); await load()
    } finally { saving.value = false }
  }
  async function remove(row: ModelRouteRecord) { await ElMessageBox.confirm(`确认删除路由 ${row.name}？`, '删除模型路由', { type: 'warning' }); await deleteModelRoute(row.id); ElMessage.success('已删除'); await load() }
  function conditionCount(value: ModelRouteConditions) { return (value.endpoints?.length || 0) + (value.api_key_ids?.length || 0) + (value.tenant_ids?.length || 0) }
  function conditionLabels(value: ModelRouteConditions) { return [...(value.endpoints || []), ...(value.api_key_ids?.length ? [`API Key × ${value.api_key_ids.length}`] : []), ...(value.tenant_ids?.length ? [`Tenant × ${value.tenant_ids.length}`] : [])] }
  onMounted(load)
</script>
