<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { fetchGetKnowledgeDocumentListByKdIds } from '@/apis/knowledge'
import { KnowledgeDocumentItem } from '../types'
import BaseKnowledgeChunkDetail from './base-knowledge/base-knowledge-chunk-detail.vue'
import QAKnowledgeChunkDetail from './qa-knowledge/qa-knowledge-chunk-detail.vue'

const { t } = useI18n()

const router = useRouter()

const currentKdId = ref(0)

const currentKnowledgeDocument = ref<
  Pick<KnowledgeDocumentItem, 'documentUrl' | 'documentName' | 'segmentationConfig'>
>({
  documentName: '',
  documentUrl: '',
  segmentationConfig: {
    segmentationType: 'DEFAULT',
    chunkSize: 0,
    scrapSize: 0,
    repetitionRate: 0,
    relationInfo: [],
    regex: '',
    punctuations: [],
  },
})

const currentKnowledgeType = ref()

onMounted(async () => {
  if (!router.currentRoute.value.params.kdId) {
    window.$message.warning(t('personal_space_module.knowledge_module.not_find_knowledge_document_message'))
    router.replace({ name: 'PersonalSpaceKnowledge' })
    return
  }

  currentKdId.value = Number(router.currentRoute.value.params.kdId)
  await handleGetKnowledgeDocumentDetail()
})

function handleGetKnowledgeDocumentDetail() {
  fetchGetKnowledgeDocumentListByKdIds<KnowledgeDocumentItem[]>([currentKdId.value])
    .then((res) => {
      if (res.code === 0) {
        currentKnowledgeDocument.value = res.data?.[0]
        currentKnowledgeType.value = res.data?.[0]?.knowledgeType || 'Base'
      }
    })
    .catch(() => {
      window.$message.warning(t('personal_space_module.knowledge_module.not_find_knowledge_document_message'))
      router.replace({ name: 'PersonalSpaceKnowledge' })
    })
}

function handleBackKnowledgeDocumentList() {
  router.replace({ name: 'KnowledgeDocument', params: { id: router.currentRoute.value.params.id } })
}
</script>

<template>
  <div class="flex h-full flex-col overflow-hidden">
    <div v-if="currentKnowledgeType === 'Base'" class="flex h-full w-full">
      <BaseKnowledgeChunkDetail
        :kd-id="currentKdId"
        :knowledge-document="currentKnowledgeDocument"
        @back-list="handleBackKnowledgeDocumentList"
      />
    </div>

    <div v-if="currentKnowledgeType === 'QA'" class="flex h-full w-full">
      <QAKnowledgeChunkDetail
        :kd-id="currentKdId"
        :knowledge-document="currentKnowledgeDocument"
        @back-list="handleBackKnowledgeDocumentList"
      />
    </div>
  </div>
</template>
