<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { Left, Search } from '@icon-park/vue-next'
import { useIntervalFn } from '@vueuse/core'
import { createKnowledgeDocumentColumn } from './columns'
import { KnowledgeDocumentItem, TrainStatus } from './types.d'
import {
  fetchBatchDelKnowledgeDocument,
  fetchDelKnowledgeDocument,
  fetchGetKnowledgeDetail,
  fetchGetKnowledgeDocumentList,
  fetchTrainKnowledge,
  fetchUpdateKnowledgeInfo,
} from '@/apis/knowledge'
import useTableScrollY from '@/composables/useTableScrollY'
import CustomPagination from '@/components/custom-pagination/custom-pagination.vue'
import EditKnowledgeModal, { KnowledgeFormDataInterface } from './components/edit-knowledge-modal.vue'
import { useUserStore } from '@/store/modules/user'
import { usePagination } from '@/composables/usePagination'

const { t } = useI18n()

const router = useRouter()

const userStore = useUserStore()

const { pageContentWrapRef, tableContentY } = useTableScrollY(48 + 48 + 24 + 28)

const knowledgeDocumentColumn = createKnowledgeDocumentColumn(handleClickKnowledgeDocumentTableAction)

const { paginationData, handlePageNoChange, handlePageSizeChange } = usePagination()

const knowledgeDocumentTableLoading = ref(false)
const knowledgeDocumentList = ref<KnowledgeDocumentItem[]>([])
const checkedKdIdList = ref<number[]>([])
const searchDocumentInputValue = ref('')
const currentKnowledgeId = ref(0)
const isSearchEmptyList = ref(false)

const isShowEditKnowledgeModal = ref(false)
const updateKnowledgeInfoBtnLoading = ref(false)
const currentKnowledgeData = ref<KnowledgeFormDataInterface>({
  knowledgeName: '',
  desc: '',
  knowledgeType: 'Base',
})

const isDisabledBatchDelBtn = computed(() => {
  return checkedKdIdList.value.length <= 0
})

const isKnowledgeDocumentFinish = computed(() => {
  return knowledgeDocumentList.value.every((documentItem) => {
    return [TrainStatus.FAIL, TrainStatus.COMPLETE].includes(documentItem.trainStatus)
  })
})

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

watch(
  () => isKnowledgeDocumentFinish.value,
  (newVal) => {
    newVal ? pauseIntervalFn() : resumeIntervalFn()
  },
  { deep: true },
)

const { pause: pauseIntervalFn, resume: resumeIntervalFn } = useIntervalFn(
  async () => {
    if (knowledgeDocumentTableLoading.value) return

    const res = await fetchGetKnowledgeDocumentList<KnowledgeDocumentItem[]>(
      currentKnowledgeId.value,
      searchDocumentInputValue.value,
      { pagingInfo: paginationData },
    )

    if (res.code === 0) {
      knowledgeDocumentList.value = res.data
      paginationData.totalRows = res.pagingInfo?.totalRows || 0
      paginationData.totalPages = res.pagingInfo?.totalPages || 0
      isSearchEmptyList.value = !!searchDocumentInputValue.value && res.data.length === 0
    }
  },
  2000,
  { immediateCallback: false, immediate: false },
)

watch([() => paginationData.pageNo, () => paginationData.pageSize], () => {
  handleGetKnowledgeDocumentList()
})

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

  currentKnowledgeId.value = Number(router.currentRoute.value.params.id)

  await handleGetKnowledgeDetail()
  await handleGetKnowledgeDocumentList()
})

async function handleGetKnowledgeDetail() {
  const res = await fetchGetKnowledgeDetail<KnowledgeFormDataInterface>(currentKnowledgeId.value)

  if (res.code === 0) {
    currentKnowledgeData.value = res.data
  }
}

async function handleGetKnowledgeDocumentList() {
  knowledgeDocumentTableLoading.value = true

  const res = await fetchGetKnowledgeDocumentList<KnowledgeDocumentItem[]>(
    currentKnowledgeId.value,
    searchDocumentInputValue.value,
    { pagingInfo: paginationData },
  )

  if (res.code === 0) {
    knowledgeDocumentList.value = res.data
    knowledgeDocumentTableLoading.value = false
    checkedKdIdList.value = []
    paginationData.totalRows = res.pagingInfo?.totalRows || 0
    paginationData.totalPages = res.pagingInfo?.totalPages || 0
    isSearchEmptyList.value = !!searchDocumentInputValue.value && res.data.length === 0
  }
}

async function handleSearchKnowledgeDocumentList() {
  paginationData.pageNo = 1
  await handleGetKnowledgeDocumentList()
}

function handleClickKnowledgeDocumentTableAction(actionType: string, knowledgeDocumentItem: KnowledgeDocumentItem) {
  switch (actionType) {
    case 'view':
      handleToViewDocumentDetail(knowledgeDocumentItem.kdId)
      break
    case 'delete':
      handleDeleteKnowledgeDocument(knowledgeDocumentItem.kdId)
      break
    case 'train':
      handleTrainKnowledgeDocument(knowledgeDocumentItem)
  }
}

function handleToViewDocumentDetail(kdId: number) {
  router.push({
    name: 'KnowledgeDocumentDetail',
    params: { kdId },
  })
}

async function handleDeleteKnowledgeDocument(kdId: number) {
  window.$message
    .ctWarning('', t('personal_space_module.knowledge_module.delete_knowledge_dialog_content'))
    .then(async () => {
      const res = await fetchDelKnowledgeDocument(currentKnowledgeId.value, kdId)

      if (res.code === 0) {
        window.$message.success(t('common_module.delete_success_message'))
        if (knowledgeDocumentList.value.length <= 1 && paginationData.pageNo === paginationData.totalPages) {
          paginationData.pageNo = paginationData.pageNo - 1 || 1
        }
        await userStore.fetchUpdateEquityInfo()
        await handleGetKnowledgeDocumentList()
      }
    })
}

async function handleTrainKnowledgeDocument(knowledgeDocumentItem: KnowledgeDocumentItem) {
  await fetchTrainKnowledge({
    knowledgeInfoId: currentKnowledgeId.value,
    kdIds: [knowledgeDocumentItem.kdId],
    segmentationConfig: knowledgeDocumentItem.segmentationConfig,
  })

  await handleGetKnowledgeDocumentList()
}

function handleShowEditKnowledgeModal() {
  isShowEditKnowledgeModal.value = true
}

async function handleUpdateKnowledgeInfo(knowledgeData: KnowledgeFormDataInterface) {
  updateKnowledgeInfoBtnLoading.value = true
  const res = await fetchUpdateKnowledgeInfo<KnowledgeFormDataInterface>({
    id: currentKnowledgeId.value,
    knowledgeName: knowledgeData.knowledgeName,
    desc: knowledgeData.desc,
  }).finally(() => (updateKnowledgeInfoBtnLoading.value = false))

  if (res.code === 0) {
    window.$message.success(t('common_module.save_success_message'))
    currentKnowledgeData.value = res.data
    isShowEditKnowledgeModal.value = false
  }
}

function handleUpdateCheckedKdId(kdIdList: number[]) {
  checkedKdIdList.value = kdIdList
}

async function handleBatchDelDocument() {
  window.$message
    .ctWarning('', t('personal_space_module.knowledge_module.delete_knowledge_dialog_content'))
    .then(async () => {
      const res = await fetchBatchDelKnowledgeDocument(currentKnowledgeId.value, checkedKdIdList.value)

      if (res.code === 0) {
        window.$message.success(t('common_module.delete_success_message'))
        if (
          knowledgeDocumentList.value.length <= checkedKdIdList.value.length &&
          paginationData.pageNo === paginationData.totalPages
        ) {
          paginationData.pageNo = paginationData.pageNo - 1 || 1
        }
        await userStore.fetchUpdateEquityInfo()
        await handleGetKnowledgeDocumentList()
      }
    })
}

function handleToUploadDocument() {
  const knowledgeType = currentKnowledgeData.value.knowledgeType || 'Base'

  router.push({
    name: 'UploadKnowledge',
    params: { id: router.currentRoute.value.params.id, type: `${knowledgeType}-local-document` },
  })
}

function handleBackKnowledgeList() {
  router.replace({ name: 'PersonalSpaceKnowledge' })
}
</script>

<template>
  <div class="flex h-full w-full flex-col overflow-hidden">
    <div class="my-3 flex h-8 items-center">
      <Left theme="outline" size="20" fill="#333" class="cursor-pointer" @click="handleBackKnowledgeList" />

      <div class="flex items-center">
        <span class="text-font-color ml-[2px] h-8 select-none text-lg leading-[30px]">
          {{ currentKnowledgeData.knowledgeName }}
        </span>
        <i
          class="iconfont icon-edit text-gray-font-color ml-[5px] cursor-pointer text-[15px] leading-none"
          @click="handleShowEditKnowledgeModal"
        />
      </div>
    </div>

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

      <NButton class="ml-[14px]!" type="info" :disabled="isDisabledBatchDelBtn" @click="handleBatchDelDocument">
        {{ t('personal_space_module.knowledge_module.batch_delete_knowledge_document_btn_text') }}
      </NButton>

      <NButton type="primary" :bordered="false" class="ml-[14px]!" @click="handleToUploadDocument">
        {{ t('personal_space_module.knowledge_module.upload_knowledge_document_btn_text') }}
      </NButton>
    </div>

    <div ref="pageContentWrapRef" class="flex-1 overflow-hidden rounded-[20px] bg-white p-6">
      <div :style="{ height: tableContentY + 48 + 'px' }">
        <NDataTable
          :loading="knowledgeDocumentTableLoading"
          :columns="knowledgeDocumentColumn"
          :bordered="false"
          :single-line="false"
          :data="knowledgeDocumentList"
          :row-key="(row: KnowledgeDocumentItem) => row.kdId"
          :max-height="tableContentY"
          :scroll-x="1558"
          :checked-row-keys="checkedKdIdList"
          @update:checked-row-keys="handleUpdateCheckedKdId"
        >
          <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_document_list-png'"
                />
                <p class="select-none text-[#84868c]">{{ emptyTableDataText }}</p>
              </div>
            </div>
          </template>
        </NDataTable>
      </div>

      <div class="mt-6 flex justify-end">
        <CustomPagination
          :paging-info="paginationData"
          @update-page-no="handlePageNoChange"
          @update-page-size="handlePageSizeChange"
        />
      </div>
    </div>

    <EditKnowledgeModal
      v-model:is-show-modal="isShowEditKnowledgeModal"
      :btn-loading="updateKnowledgeInfoBtnLoading"
      :knowledge-data="currentKnowledgeData"
      @confirm="handleUpdateKnowledgeInfo"
    />
  </div>
</template>
