<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 './knowledge-type'
import KnowledgeChuckItem from './components/knowledge-chuck-item.vue'
import {
  fetchAddKnowledgeChunk,
  fetchDeleteKnowledgeChunk,
  fetchGetKnowledgeChunkList,
  fetchGetKnowledgeDocumentListByKdIds,
  fetchOpenKnowledgeChunk,
  fetchUpdateKnowledgeChunk,
} from '@/apis/knowledge'
import CustomPagination, { PaginationInfo } from '@/components/custom-pagination/custom-pagination.vue'
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 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 pagingInfo = ref<PaginationInfo>({
  pageNo: 1,
  pageSize: 10,
  totalPages: 0,
  totalRows: 0,
})

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}.png`
})

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

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

    scrollBarRef.value?.scrollTo({ top: 0 })
  }
}

function handleBackKnowledgeDocumentList() {
  router.back()
}

async function handleGetKnowledgeChunkListUpdatePageNo(pageNo: number) {
  pagingInfo.value.pageNo = pageNo
  await handleGetKnowledgeChunkList()
}

async function handleGetKnowledgeChunkListUpdatePageSize(pageSize: number) {
  pagingInfo.value.pageNo = 1
  pagingInfo.value.pageSize = pageSize
  await handleGetKnowledgeChunkList()
}

async function handleSearchKnowledgeChunkList() {
  pagingInfo.value.pageNo = 1
  await handleGetKnowledgeChunkList()
}

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) {
  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) {
    await handleGetKnowledgeChunkList()
  }
}
</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">
      <n-scrollbar
        v-if="!knowledgeChunkListLoading && knowledgeChunkList.length"
        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
        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] bg-contain"
            :class="
              isSearchEmptyList
                ? `bg-[url('@/assets/images/search-empty-list.png')]`
                : `bg-[url('@/assets/images/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="pagingInfo"
        @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>
