<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { DataTableInst } from 'naive-ui'
import { Search } from '@icon-park/vue-next'
import { createKnowledgeColumn } from './columns.tsx'
import { KnowledgeItem } from './types.d'
import CustomPagination from '@/components/custom-pagination/custom-pagination.vue'
import useTableScrollY from '@/composables/useTableScrollY.ts'
import { usePagination } from '@/composables/usePagination.ts'
import { fetchDelKnowledgeById, fetchEnableKnowledgeInfo, fetchGetKnowledgeList } from '@/apis/knowledge.ts'

const { t } = useI18n()

const router = useRouter()

const knowledgeListTableRef = useTemplateRef<DataTableInst>('knowledgeListTableRef')

const { pageContentWrapRef, tableContentY } = useTableScrollY(48 + 32 + 16 + 16 + 28)
const { paginationData, handlePageNoChange, handlePageSizeChange } = usePagination()

const knowledgeColumns = createKnowledgeColumn(handleClickKnowledgeTableAction)

const knowledgeListTableLoading = ref(false)
const knowledgeList = ref<KnowledgeItem[]>([])

const searchKnowledgeInputValue = ref('')
const isSearchEmptyList = ref(false)

const isLoadingPagination = computed(() => {
  return tableContentY.value > 0
})

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

watch([() => paginationData.pageNo, () => paginationData.pageSize], () => {
  handleGetKnowledgeList()
  knowledgeListTableRef.value?.scrollTo({ top: 0, behavior: 'smooth' })
})

onMounted(async () => {
  await handleGetKnowledgeList()
})

async function handleGetKnowledgeList() {
  knowledgeListTableLoading.value = true

  const res = await fetchGetKnowledgeList<KnowledgeItem[]>('', searchKnowledgeInputValue.value, {
    pagingInfo: paginationData,
  })

  if (res.code === 0) {
    knowledgeList.value = res.data
    paginationData.totalRows = res.pagingInfo?.totalRows || 0
    paginationData.totalPages = res.pagingInfo?.totalPages || 0
    knowledgeListTableLoading.value = false
    isSearchEmptyList.value = !!searchKnowledgeInputValue.value && paginationData.totalRows === 0
  }
}

function handleClickKnowledgeTableAction(actionType: string, knowledgeId: number, knowledgeItem?: KnowledgeItem) {
  switch (actionType) {
    case 'updateOpen':
      handleUpdateKnowledgeOpen(knowledgeId, knowledgeItem!)
      break
    case 'view':
      handleViewDocumentList(knowledgeId)
      break
    case 'delete':
      handleDeleteKnowledge(knowledgeId)
      break
  }
}

async function handleUpdateKnowledgeOpen(knowledgeId: number, knowledgeItem: KnowledgeItem) {
  const isOpen = knowledgeItem.isOpen === 'Y' ? 'N' : 'Y'
  const res = await fetchEnableKnowledgeInfo(knowledgeId, isOpen)

  if (res.code === 0) {
    knowledgeItem.isOpen = isOpen
  }
}

function handleViewDocumentList(knowledgeId: number) {
  router.push({
    name: 'KnowledgeDocument',
    params: { id: knowledgeId },
  })
}

async function handleDeleteKnowledge(knowledgeId: number) {
  window.$message
    .ctWarning('', t('personal_space_module.knowledge_module.delete_knowledge_dialog_content'))
    .then(async () => {
      const res = await fetchDelKnowledgeById(knowledgeId)
      if (res.code === 0) {
        window.$message.success(t('common_module.delete_success_message'))
        await handleGetKnowledgeList()
      }
    })
}

function handleSearchKnowledge() {
  paginationData.pageNo = 1
  handleGetKnowledgeList()
  knowledgeListTableRef.value?.scrollTo({ top: 0, behavior: 'smooth' })
}
</script>

<template>
  <div ref="pageContentWrapRef" class="h-full">
    <div class="mb-4 flex justify-end">
      <NInput
        v-model:value="searchKnowledgeInputValue"
        :placeholder="t('personal_space_module.knowledge_module.search_knowledge_placeholder')"
        class="w-[256px]!"
        @keyup.enter="handleSearchKnowledge"
      >
        <template #suffix>
          <Search theme="outline" size="16" fill="#999" class="cursor-pointer" @click="handleSearchKnowledge" />
        </template>
      </NInput>
    </div>

    <div class="mb-4" :style="{ height: tableContentY + 48 + 'px' }">
      <NDataTable
        ref="knowledgeListTableRef"
        :loading="knowledgeListTableLoading"
        :bordered="true"
        :bottom-bordered="true"
        :single-line="false"
        :data="knowledgeList"
        :columns="knowledgeColumns"
        :max-height="tableContentY"
        :scroll-x="1100"
      >
        <template #empty>
          <div :style="{ height: tableContentY + 'px' }" class="flex 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">{{ emptyTableDataText }}</p>
            </div>
          </div>
        </template>
      </NDataTable>
    </div>

    <footer v-show="isLoadingPagination" class="flex justify-end">
      <CustomPagination
        :paging-info="paginationData"
        @update-page-no="handlePageNoChange"
        @update-page-size="handlePageSizeChange"
      />
    </footer>
  </div>
</template>
