<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { ScrollbarInst } from 'naive-ui'
import { Left, Search } from '@icon-park/vue-next'
import { KnowledgeChunkItem, KnowledgeDocumentItem } from '../../types'
import KnowledgeChuckItem from './components/knowledge-chuck-item.vue'
import {
  fetchAddKnowledgeChunk,
  fetchDeleteKnowledgeChunk,
  fetchGetKnowledgeChunkList,
  fetchOpenKnowledgeChunk,
  fetchUpdateKnowledgeChunk,
} from '@/apis/knowledge'
import CustomPagination from '@/components/custom-pagination/custom-pagination.vue'
import { usePagination } from '@/composables/usePagination.ts'
import EditKnowledgeChunkModal from './components/edit-knowledge-chunk-modal.vue'
import AddKnowledgeChunkModal from './components/add-knowledge-chunk-modal.vue'

interface Props {
  kdId: number
  knowledgeDocument: Pick<KnowledgeDocumentItem, 'documentUrl' | 'documentName' | 'segmentationConfig'>
}

const props = defineProps<Props>()

const emit = defineEmits<{
  backList: []
}>()

const { t } = useI18n()

const { paginationData } = usePagination()

const scrollBarRef = ref<ScrollbarInst | null>(null)

const searchKnowledgeChunkValue = ref('')
const isSearchEmptyList = ref(false)
const totalChunk = ref(0)
const knowledgeChunkList = ref<KnowledgeChunkItem[]>([])
const knowledgeChunkListLoading = ref(false)

const defaultKnowledgeChunkData: KnowledgeChunkItem = {
  knowledgeId: '',
  chunkContent: '',
  chunkRelationId: '',
  chunkSort: 0,
  isOpen: 'Y',
}

const isShowEditKnowledgeChunkModal = ref(false)
const updateKnowledgeChunkBtnLoading = ref(false)
const isShowAddKnowledgeChunkModal = ref(false)
const addKnowledgeChunkBtnLoading = ref(false)
const currentKnowledgeChunkInfo = ref<KnowledgeChunkItem>({ ...defaultKnowledgeChunkData })

const documentIcon = computed(() => (documentUrl: string) => {
  const type = documentUrl.substring(documentUrl.lastIndexOf('.') + 1)

  return `https://gsst-poe-sit.gz.bcebos.com/icon/${type}.svg`
})

const emptyKnowledgeChunkListText = computed(() => {
  return isSearchEmptyList.value ? t('common_module.search_empty_data') : t('common_module.empty_data')
})

onMounted(async () => {
  props.kdId && (await handleGetKnowledgeChunkList())
})

async function handleGetKnowledgeChunkList() {
  knowledgeChunkListLoading.value = true

  const res = await fetchGetKnowledgeChunkList<{ totalChunk: number; chunkInfos: KnowledgeChunkItem[] }>(
    searchKnowledgeChunkValue.value,
    props.kdId,
    {
      pagingInfo: paginationData,
    },
  )

  if (res.code === 0) {
    totalChunk.value = res.data.totalChunk
    knowledgeChunkList.value = res.data.chunkInfos || []
    paginationData.totalRows = res.pagingInfo?.totalRows || 0
    paginationData.totalPages = res.pagingInfo?.totalPages || 0
    knowledgeChunkListLoading.value = false
    isSearchEmptyList.value = !!searchKnowledgeChunkValue.value && paginationData.totalRows === 0
  }
}

function handleBackKnowledgeDocumentList() {
  emit('backList')
}

async function handleSearchKnowledgeChunkList() {
  paginationData.pageNo = 1
  await handleGetKnowledgeChunkList()
  scrollBarRef.value?.scrollTo({ top: 0 })
}

function handleEditKnowledgeChunkModal(chunkItem: KnowledgeChunkItem) {
  isShowEditKnowledgeChunkModal.value = true
  currentKnowledgeChunkInfo.value = chunkItem
}

async function handleUpdateKnowledgeChunk(chunkRelationId: string, chunkContent: string) {
  updateKnowledgeChunkBtnLoading.value = true

  const res = await fetchUpdateKnowledgeChunk({
    kdId: props.kdId,
    chunkRelationId,
    chunkContent,
  }).finally(() => (updateKnowledgeChunkBtnLoading.value = false))

  if (res.code === 0) {
    window.$message.success(t('common_module.edit_success_message'))
    isShowEditKnowledgeChunkModal.value = false
    await handleGetKnowledgeChunkList()
  }
}

function handleShowUpAddChunkModal(chunkSort: number) {
  isShowAddKnowledgeChunkModal.value = true
  currentKnowledgeChunkInfo.value = { ...defaultKnowledgeChunkData, chunkSort }
}

function handleShowDownAddChunkModal(chunkSort: number) {
  isShowAddKnowledgeChunkModal.value = true
  currentKnowledgeChunkInfo.value = { ...defaultKnowledgeChunkData, chunkSort }
}

async function handleAddKnowledgeChunk(chunkContent: string, chunkSort: number) {
  addKnowledgeChunkBtnLoading.value = true

  const res = await fetchAddKnowledgeChunk({
    kdId: props.kdId,
    chunkContent,
    chunkSort,
  }).finally(() => {
    addKnowledgeChunkBtnLoading.value = false
  })

  if (res.code === 0) {
    window.$message.success(t('common_module.add_success_message'))
    isShowAddKnowledgeChunkModal.value = false
    await handleGetKnowledgeChunkList()
  }
}

async function handleDeleteKnowledgeChunk(chunkRelationId: string) {
  window.$message
    .ctWarning('', t('personal_space_module.knowledge_module.delete_knowledge_chunk_content_message'))
    .then(async () => {
      const res = await fetchDeleteKnowledgeChunk({
        kdId: props.kdId,
        chunkRelationId,
      })

      if (res.code === 0) {
        window.$message.success(t('common_module.delete_success_message'))
        await handleGetKnowledgeChunkList()
      }
    })
}

async function handleUpdateOpenKnowledgeChunk(chunkItem: KnowledgeChunkItem) {
  const { chunkRelationId, isOpen } = chunkItem

  const res = await fetchOpenKnowledgeChunk({
    chunkRelationId,
    isOpen: isOpen === 'Y' ? 'N' : 'Y',
    kdId: props.kdId,
  })

  if (res.code === 0) {
    chunkItem.isOpen = isOpen === 'Y' ? 'N' : 'Y'
  }
}

async function handleGetKnowledgeChunkListUpdatePageNo(pageNo: number) {
  paginationData.pageNo = pageNo
  await handleGetKnowledgeChunkList()
  scrollBarRef.value?.scrollTo({ top: 0 })
}

async function handleGetKnowledgeChunkListUpdatePageSize(pageSize: number) {
  paginationData.pageNo = 1
  paginationData.pageSize = pageSize
  await handleGetKnowledgeChunkList()
  scrollBarRef.value?.scrollTo({ top: 0 })
}
</script>

<template>
  <div class="flex h-full w-full flex-col overflow-hidden">
    <div class="mb-4.5 gap-4.5 mt-6 flex items-center">
      <div class="flex h-9 items-center">
        <Left theme="outline" size="20" fill="#333" class="cursor-pointer" @click="handleBackKnowledgeDocumentList" />
        <img :src="documentIcon(knowledgeDocument.documentUrl)" class="ml-[2px] h-9 w-9" />
        <span class="text-font-color ml-[5px] line-clamp-1 select-none break-all text-lg">
          {{ knowledgeDocument.documentName }}
        </span>
      </div>

      <ul class="flex flex-shrink-0 gap-2">
        <li class="border-inactive-border-color select-none rounded-full border px-4 py-1 leading-[18px]">
          {{ totalChunk }}
          {{ t('personal_space_module.knowledge_module.segment') }}
        </li>
        <li class="border-inactive-border-color select-none rounded-full border px-4 py-1 leading-[18px]">
          {{
            knowledgeDocument.segmentationConfig.segmentationType === 'DEFAULT'
              ? t('personal_space_module.knowledge_module.auto_segment')
              : t('personal_space_module.knowledge_module.custom_segment')
          }}
        </li>
      </ul>
    </div>

    <div class="mb-[18px] flex justify-end">
      <n-input
        v-model:value="searchKnowledgeChunkValue"
        :placeholder="t('personal_space_module.knowledge_module.search_knowledge_chunk_placeholder')"
        class="w-[214px]!"
        @keyup.enter="handleSearchKnowledgeChunkList"
      >
        <template #suffix>
          <Search
            theme="outline"
            size="16"
            fill="#999"
            class="cursor-pointer"
            @click="handleSearchKnowledgeChunkList"
          />
        </template>
      </n-input>
    </div>

    <n-spin :show="knowledgeChunkListLoading" class="w-full flex-1 overflow-hidden" content-class="flex w-full h-full">
      <div v-if="knowledgeChunkList.length" class="flex flex-1">
        <div v-show="!knowledgeChunkListLoading" class="flex flex-1">
          <n-scrollbar ref="scrollBarRef" class="grid w-full flex-1 overflow-hidden">
            <div class="grid gap-5">
              <KnowledgeChuckItem
                v-for="chunkItem in knowledgeChunkList"
                :key="chunkItem.chunkRelationId"
                :chunk-item="chunkItem"
                :total-chunk="totalChunk"
                @edit="handleEditKnowledgeChunkModal"
                @up-add-chunk="handleShowUpAddChunkModal"
                @down-add-chunk="handleShowDownAddChunkModal"
                @delete="handleDeleteKnowledgeChunk"
                @update-open="handleUpdateOpenKnowledgeChunk"
              />
            </div>
          </n-scrollbar>
        </div>
      </div>

      <div
        v-show="!knowledgeChunkListLoading && knowledgeChunkList.length === 0"
        class="flex flex-1 items-center justify-center"
      >
        <div class="flex flex-col items-center justify-center">
          <div
            class="mb-5 h-[68px] w-[68px]"
            :class="isSearchEmptyList ? 'bg-px-search_empty_list-png' : 'bg-px-empty_list-png'"
          />
          <p class="text-gray-font-color select-none">{{ emptyKnowledgeChunkListText }}</p>
        </div>
      </div>
    </n-spin>

    <div class="mt-4 flex justify-end">
      <CustomPagination
        :paging-info="paginationData"
        @update-page-no="handleGetKnowledgeChunkListUpdatePageNo"
        @update-page-size="handleGetKnowledgeChunkListUpdatePageSize"
      />
    </div>

    <EditKnowledgeChunkModal
      v-model:is-show-modal="isShowEditKnowledgeChunkModal"
      :chunk-item="currentKnowledgeChunkInfo"
      :total-chunk="totalChunk"
      :btn-loading="updateKnowledgeChunkBtnLoading"
      @confirm="handleUpdateKnowledgeChunk"
    />

    <AddKnowledgeChunkModal
      v-model:is-show-modal="isShowAddKnowledgeChunkModal"
      :chunk-item="currentKnowledgeChunkInfo"
      :total-chunk="totalChunk"
      :btn-loading="addKnowledgeChunkBtnLoading"
      @confirm="handleAddKnowledgeChunk"
    />
  </div>
</template>
