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

import { computed, onMounted, ref, watch } from 'vue';

import { $t } from '@vben/locales';

import {
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElOption,
  ElSelect,
  ElSlider,
  ElSwitch,
  ElTag,
} from 'element-plus';

import {
  getActiveModelsApi,
  getKnowledgeBaseSimpleListApi,
} from '#/api/ai-platform/ai-platform';

import SmartInput from '../components/SmartInput.vue';

const props = defineProps<{ data: any; nodeId: string }>();
const emit = defineEmits(['update']);

const form = ref({
  label: $t('ai-platform.workflow.nodes.knowledge_retrieval'),
  knowledge_base_ids: [] as string[],
  query: '',
  top_k: 5,
  score_threshold: 0.5,
  retrieval_mode: '',
  rerank_enabled: false,
  rerank_model_id: '',
  ...props.data,
});

if (!form.value.knowledge_base_ids) form.value.knowledge_base_ids = [];

watch(
  form,
  (val) => {
    emit('update', val);
  },
  { deep: true },
);

// 知识库列表
const kbList = ref<KnowledgeBaseSimpleItem[]>([]);
const kbLoading = ref(false);

async function loadKnowledgeBases() {
  kbLoading.value = true;
  try {
    kbList.value = await getKnowledgeBaseSimpleListApi();
  } catch {
    // ignore
  } finally {
    kbLoading.value = false;
  }
}

// Rerank 模型列表
const allModels = ref<ModelListItem[]>([]);
const rerankModels = computed(() =>
  allModels.value.filter((m) => m.model_type === 'rerank'),
);

async function loadModels() {
  try {
    allModels.value = await getActiveModelsApi();
  } catch {
    // ignore
  }
}

onMounted(() => {
  loadKnowledgeBases();
  loadModels();
});
</script>

<template>
  <ElForm label-position="top" size="small" class="space-y-4">
    <ElFormItem :label="$t('ai-platform.workflow.nodeLabel')">
      <ElInput
        v-model="form.label"
        :placeholder="$t('ai-platform.workflow.nodes.knowledge_retrieval')"
      />
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.knowledge.title')">
      <ElSelect
        v-model="form.knowledge_base_ids"
        multiple
        filterable
        :loading="kbLoading"
        :placeholder="$t('ai-platform.knowledgeNode.selectKb')"
        style="width: 100%"
      >
        <ElOption
          v-for="kb in kbList"
          :key="kb.id"
          :label="kb.name"
          :value="kb.id"
        />
      </ElSelect>
      <div
        v-if="form.knowledge_base_ids.length > 0"
        class="mt-1.5 flex flex-wrap gap-1"
      >
        <ElTag
          v-for="id in form.knowledge_base_ids"
          :key="id"
          size="small"
          closable
          @close="
            form.knowledge_base_ids = form.knowledge_base_ids.filter(
              (i: string) => i !== id,
            )
          "
        >
          {{ kbList.find((k) => k.id === id)?.name || id }}
        </ElTag>
      </div>
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.knowledgeNode.queryText')">
      <SmartInput
        v-model="form.query"
        :current-node-id="nodeId"
        :placeholder="$t('ai-platform.knowledgeNode.queryPlaceholder')"
      />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.knowledgeNode.queryHint') }}
      </div>
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.knowledgeNode.retrievalMode')">
      <ElSelect
        v-model="form.retrieval_mode"
        clearable
        :placeholder="$t('ai-platform.knowledgeNode.useKbDefault')"
        style="width: 100%"
      >
        <ElOption
          value="vector"
          :label="$t('ai-platform.knowledgeNode.vector')"
        />
        <ElOption
          value="fulltext"
          :label="$t('ai-platform.knowledgeNode.fulltext')"
        />
        <ElOption
          value="hybrid"
          :label="$t('ai-platform.knowledgeNode.hybrid')"
        />
      </ElSelect>
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.knowledge.topK')">
      <ElInputNumber v-model="form.top_k" :min="1" :max="20" size="small" />
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.knowledge.scoreThreshold')">
      <ElSlider
        v-model="form.score_threshold"
        :min="0"
        :max="1"
        :step="0.05"
        show-input
        :show-input-controls="false"
        input-size="small"
      />
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.knowledgeNode.rerankEnabled')">
      <ElSwitch v-model="form.rerank_enabled" />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.knowledgeNode.rerankHint') }}
      </div>
    </ElFormItem>

    <ElFormItem
      v-if="form.rerank_enabled"
      :label="$t('ai-platform.knowledgeNode.rerankModel')"
    >
      <ElSelect
        v-model="form.rerank_model_id"
        clearable
        :placeholder="$t('ai-platform.knowledgeNode.useKbDefault')"
        style="width: 100%"
      >
        <ElOption
          v-for="m in rerankModels"
          :key="m.id"
          :label="m.display_name"
          :value="m.id"
        />
      </ElSelect>
      <div v-if="rerankModels.length === 0" class="text-warning mt-1 text-xs">
        {{ $t('ai-platform.knowledgeNode.noRerankModel') }}
      </div>
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.knowledgeNode.outputVariables')">
      <div class="bg-muted/50 space-y-2 rounded-md p-3 text-xs">
        <div class="flex items-start gap-2">
          <code
            class="bg-primary/10 text-primary rounded px-1.5 py-0.5 font-mono"
            >knowledge_results</code>
          <span class="text-muted-foreground flex-1">{{
            $t('ai-platform.knowledgeNode.resultsArrayDesc')
          }}</span>
        </div>
        <div class="flex items-start gap-2">
          <code
            class="bg-primary/10 text-primary rounded px-1.5 py-0.5 font-mono"
            >knowledge_context</code>
          <span class="text-muted-foreground flex-1">{{
            $t('ai-platform.knowledgeNode.contextTextDesc')
          }}</span>
        </div>
        <div class="flex items-start gap-2">
          <code
            class="bg-primary/10 text-primary rounded px-1.5 py-0.5 font-mono"
            >knowledge_results_total</code>
          <span class="text-muted-foreground flex-1">{{
            $t('ai-platform.knowledgeNode.totalCountDesc')
          }}</span>
        </div>
      </div>
    </ElFormItem>
  </ElForm>
</template>
