<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ScrollbarInst } from 'naive-ui'
import { Left, Search } from '@icon-park/vue-next'
import { KnowledgeChunkItem, KnowledgeDocumentItem } from './types.d'
import KnowledgeChuckItem from './components/knowledge-chuck-item.vue'
import {
  fetchAddKnowledgeChunk,
  fetchDeleteKnowledgeChunk,
  fetchGetKnowledgeChunkList,
  fetchGetKnowledgeDocumentListByKdIds,
  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'

const { t } = useI18n()

const router = useRouter()

const { paginationData } = usePagination()

const currentKdId = ref(0)
const currentKnowledgeDocumentName = ref('')
const currentKnowledgeDocumentUrl = ref('')

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 () => {
  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()
  await handleGetKnowledgeChunkList()
})

function handleGetKnowledgeDocumentDetail() {
  fetchGetKnowledgeDocumentListByKdIds<KnowledgeDocumentItem[]>([currentKdId.value])
    .then((res) => {
      if (res.code === 0) {
        currentKnowledgeDocumentName.value = res.data[0].documentName
        currentKnowledgeDocumentUrl.value = res.data[0].documentUrl
      }
    })
    .catch(() => {
      window.$message.warning(t('personal_space_module.knowledge_module.not_find_knowledge_document_message'))
      router.replace({ name: 'PersonalSpaceKnowledge' })
    })
}

async function handleGetKnowledgeChunkList() {
  knowledgeChunkListLoading.value = true

  const res = await fetchGetKnowledgeChunkList<{ totalChunk: number; chunkInfos: KnowledgeChunkItem[] }>(
    searchKnowledgeChunkValue.value,
    currentKdId.value,
    {
      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() {
  router.replace({ name: 'KnowledgeDocument', params: { id: router.currentRoute.value.params.id } })
}

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: currentKdId.value,
    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: currentKdId.value,
    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: currentKdId.value,
        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: currentKdId.value,
  })

  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 flex-col overflow-hidden">
    <div class="my-6">
      <div class="flex h-9 items-center">
        <Left theme="outline" size="20" fill="#333" class="cursor-pointer" @click="handleBackKnowledgeDocumentList" />
        <img :src="documentIcon(currentKnowledgeDocumentUrl)" class="ml-[2px] h-9 w-9" />
        <span class="text-font-color ml-[5px] line-clamp-1 select-none break-all text-lg">
          {{ currentKnowledgeDocumentName }}
        </span>
      </div>

      <div class="ml-[66px] mt-1">
        <ul class="flex 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]">
            {{ t('personal_space_module.knowledge_module.auto_segment') }}
          </li>
        </ul>
      </div>
    </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>
