<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Left, Search } from '@icon-park/vue-next'
import { useElementSize } from '@vueuse/core'
import {
  fetchAddQAKnowledgeChunk,
  fetchBatchDeleteQAKnowledgeChunks,
  fetchDeleteQAKnowledgeChunk,
  fetchEditQAKnowledgeChunk,
  fetchOpenQAKnowledgeChunk,
  fetchQAKnowledgeChunkList,
  fetchQAKnowledgeChunkStruct,
  fetchUpdateQAKnowledgeStruct,
} from '@/apis/knowledge'
import CustomPagination from '@/components/custom-pagination/custom-pagination.vue'
import { usePagination } from '@/composables/usePagination'
import { useUserStore } from '@/store/modules/user'
import SettingKnowledgeChunkIndexModal from './components/setting-knowledge-chunk-index-modal.vue'
import AddQAKnowledgeChunkModal from './components/add-qa-knowledge-chunk-modal.vue'
import EditQAKnowledgeChunkModal from './components/edit-qa-knowledge-chunk-modal.vue'
import { createQAKnowledgeChunkColumn } from '../columns'
import {
  KnowledgeDocumentItem,
  QAKnowledgeChunkContentItem,
  QAKnowledgeChunkKeyItem,
  QAKnowledgeChunkInfoItem,
} from '../../types'

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

const props = defineProps<Props>()

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

const { t } = useI18n()

const userStore = useUserStore()

const { paginationData } = usePagination()

const knowledgeChunkListContainer = ref<HTMLDivElement | null>(null)
const { height } = useElementSize(knowledgeChunkListContainer)

const totalChunk = ref(0) // 总分片数
const currentChunkSort = ref(0) // 当前分片排序
const showAddKnowledgeChunkModal = ref(false)
const showEditKnowledgeChunkModal = ref(false)
const knowledgeChunkBtnLoading = ref(false)
const showSettingChunkIndexModal = ref(false)
const isSearchEmptyList = ref(false)
const searchKnowledgeChunkValue = ref('')
const chunkKeyList = ref<QAKnowledgeChunkKeyItem[]>([]) // QA知识库分片表头列表
const knowledgeChunkList = ref<QAKnowledgeChunkContentItem[]>([]) // QA知识库分片内容列表
const knowledgeChunkColumnTableLoading = ref(false)
const checkedChunkIdList = ref<string[]>([])
const currentChunkItem = ref<QAKnowledgeChunkContentItem>({
  chunkRelationId: '',
  chunkSort: 0,
  chunkInfo: [],
  isOpen: 'Y',
})

const knowledgeChunkColumn = computed(() => {
  return createQAKnowledgeChunkColumn(chunkKeyList.value, handleKnowledgeChunkTableAction)
})

const dataTableScrollX = computed(() => {
  return chunkKeyList.value.length * 246 + 40 + 92
})

const tableContentY = computed(() => {
  return height.value - 48
})

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

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

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

const isDisabledOperateBtn = computed(() => {
  return chunkKeyList.value.length <= 0
})

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

onMounted(async () => {
  if (props.kdId) {
    await handleGetQAKnowledgeChunkStruct()
    await handleQAKnowledgeChunkList()
  }
})

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

// 获取QA知识库分片结构
async function handleGetQAKnowledgeChunkStruct() {
  const res = await fetchQAKnowledgeChunkStruct<{ key: QAKnowledgeChunkKeyItem[] }>(props.kdId)

  if (res.code === 0) {
    chunkKeyList.value = res.data.key || []
  }
}

// 获取QA知识库分片列表
async function handleQAKnowledgeChunkList() {
  knowledgeChunkColumnTableLoading.value = true

  const res = await fetchQAKnowledgeChunkList<{
    chunk: QAKnowledgeChunkContentItem[]
    totalChunk: number
  }>(searchKnowledgeChunkValue.value, props.kdId, {
    pagingInfo: paginationData,
  })

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

// 搜索QA知识库分片列表
async function handleSearchKnowledgeChunkList() {
  paginationData.pageNo = 1
  await handleQAKnowledgeChunkList()
}

// 更新分页数获取分片列表
async function handleGetKnowledgeChunkListUpdatePageNo(pageNo: number) {
  paginationData.pageNo = pageNo
  await handleQAKnowledgeChunkList()
}

// 更新分页大小获取分片列表
async function handleGetKnowledgeChunkListUpdatePageSize(pageSize: number) {
  paginationData.pageNo = 1
  paginationData.pageSize = pageSize
  await handleQAKnowledgeChunkList()
}

// 更新知识库索引
async function handleUpdateKnowledgeChunkIndex(chunkKeyItem: QAKnowledgeChunkKeyItem) {
  const { structId, isIndex } = chunkKeyItem
  const payload = {
    kdId: props.kdId,
    structId,
    isIndex,
  }
  fetchUpdateQAKnowledgeStruct(payload).catch(() => {
    chunkKeyItem.isIndex = chunkKeyItem.isIndex === 'Y' ? 'N' : 'Y'
  })
}

// 关闭设置索引对话框
function handleCloseSettingChunkIndexModal() {
  showSettingChunkIndexModal.value = false
  handleGetQAKnowledgeChunkStruct()
}

// QA知识库分片列表操作
function handleKnowledgeChunkTableAction(
  actionType: string,
  chunkRelationId: string,
  chunkContentItem?: QAKnowledgeChunkContentItem,
) {
  switch (actionType) {
    case 'addUp': {
      const chunkSort = chunkContentItem?.chunkSort || 0
      handleShowAddQAKnowledgeChunk(chunkSort)
      break
    }
    case 'addDown': {
      const chunkSort = chunkContentItem?.chunkSort || 0
      handleShowAddQAKnowledgeChunk(chunkSort + 1)
      break
    }
    case 'edit':
      handleUpdateQAKnowledgeChunk(chunkContentItem!)
      break
    case 'delete':
      handleDeleteQAKnowledgeChunk(chunkRelationId)
      break
    case 'updateOpen':
      handleUpdateQAKnowledgeChunkOpen(chunkRelationId, chunkContentItem!)
      break
  }
}

// 更新选中的分片Id
function handleUpdateCheckedChunkId(chunkIdList: string[]) {
  checkedChunkIdList.value = chunkIdList
}

// 显示新增知识库分片对话框
function handleShowAddQAKnowledgeChunk(chunkSort: number) {
  showAddKnowledgeChunkModal.value = true
  currentChunkSort.value = chunkSort
}

// 执行添加QA知识库分片
async function handleAddQAKnowledgeChunk(chunkInfos: QAKnowledgeChunkInfoItem[]) {
  knowledgeChunkBtnLoading.value = true

  const payload = {
    kdId: props.kdId,
    chunkInfos,
    chunkSort: currentChunkSort.value,
  }

  const res = await fetchAddQAKnowledgeChunk(payload).finally(() => {
    knowledgeChunkBtnLoading.value = false
  })

  if (res.code === 0) {
    showAddKnowledgeChunkModal.value = false
    window.$message.success(t('common_module.add_success_message'))
    currentChunkSort.value === 0 && (paginationData.pageNo = 1)
    handleQAKnowledgeChunkList()
  }
}

// 显示编辑知识库分片对话框
function handleUpdateQAKnowledgeChunk(chunkContentItem: QAKnowledgeChunkContentItem) {
  showEditKnowledgeChunkModal.value = true
  currentChunkItem.value = JSON.parse(JSON.stringify(chunkContentItem || []))
}

// 执行编辑知识库分片
async function handleEditQAKnowledgeChunk(chunkRelationId: string, chunkInfos: QAKnowledgeChunkInfoItem[]) {
  knowledgeChunkBtnLoading.value = true

  const payload = {
    kdId: props.kdId,
    chunkRelationId,
    chunkInfos,
  }

  const res = await fetchEditQAKnowledgeChunk(payload).finally(() => {
    knowledgeChunkBtnLoading.value = false
  })

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

// 删除知识库分片
async function handleDeleteQAKnowledgeChunk(chunkRelationId: string) {
  window.$message
    .ctWarning('', t('personal_space_module.knowledge_module.delete_knowledge_chunk_content_message'))
    .then(async () => {
      knowledgeChunkColumnTableLoading.value = true

      const res = await fetchDeleteQAKnowledgeChunk({
        kdId: props.kdId,
        chunkRelationId,
      }).finally(() => {
        knowledgeChunkColumnTableLoading.value = false
      })

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

// 更新知识库是否开启
function handleUpdateQAKnowledgeChunkOpen(chunkRelationId: string, chunkContentItem: QAKnowledgeChunkContentItem) {
  chunkContentItem.isOpen = chunkContentItem.isOpen === 'Y' ? 'N' : 'Y'

  const payload = {
    kdId: props.kdId,
    chunkRelationId,
    isOpen: chunkContentItem.isOpen,
  }

  fetchOpenQAKnowledgeChunk(payload).catch(() => {
    chunkContentItem.isOpen = chunkContentItem.isOpen === 'Y' ? 'N' : 'Y'
  })
}

// 批量删除知识库分片
function handleBatchDeleteKnowledgeChunk() {
  window.$message
    .ctWarning('', t('personal_space_module.knowledge_module.delete_knowledge_dialog_content'))
    .then(async () => {
      knowledgeChunkColumnTableLoading.value = true

      const res = await fetchBatchDeleteQAKnowledgeChunks(props.kdId, checkedChunkIdList.value).finally(() => {
        knowledgeChunkColumnTableLoading.value = false
      })

      if (res.code === 0) {
        window.$message.success(t('common_module.delete_success_message'))
        checkedChunkIdList.value = []
        await userStore.fetchUpdateEquityInfo()
        await handleQAKnowledgeChunkList()
      }
    })
}
</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>
      </ul>
    </div>

    <div class="flex-center mb-4.5 justify-between">
      <div class="flex-center gap-2.5">
        <n-button type="primary" :disabled="isDisabledOperateBtn" @click="handleShowAddQAKnowledgeChunk(0)">
          {{ t('personal_space_module.knowledge_module.add_QA') }}
        </n-button>
        <n-button type="primary" :disabled="isDisabledOperateBtn" @click="showSettingChunkIndexModal = true">
          {{ t('personal_space_module.knowledge_module.setting_index') }}
        </n-button>
      </div>

      <div class="flex-center gap-2.5">
        <n-input
          v-model:value="searchKnowledgeChunkValue"
          :placeholder="t('common_module.search')"
          class="w-[214px]!"
          @keyup.enter="handleSearchKnowledgeChunkList"
        >
          <template #suffix>
            <Search
              theme="outline"
              size="16"
              fill="#999"
              class="cursor-pointer"
              @click="handleSearchKnowledgeChunkList"
            />
          </template>
        </n-input>

        <n-button type="info" :disabled="isDisabledBatchDelBtn" @click="handleBatchDeleteKnowledgeChunk">
          {{ t('personal_space_module.knowledge_module.batch_delete_knowledge_document_btn_text') }}
        </n-button>
      </div>
    </div>

    <div ref="knowledgeChunkListContainer" class="w-full flex-1 overflow-hidden rounded-[10px] bg-white p-6">
      <n-data-table
        :loading="knowledgeChunkColumnTableLoading"
        :columns="knowledgeChunkColumn"
        :data="knowledgeChunkList"
        :scroll-x="dataTableScrollX"
        :max-height="tableContentY"
        :row-key="(row: QAKnowledgeChunkContentItem) => row.chunkRelationId"
        :checked-row-keys="checkedChunkIdList"
        @update:checked-row-keys="handleUpdateCheckedChunkId"
      >
        <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>
      </n-data-table>
    </div>

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

    <SettingKnowledgeChunkIndexModal
      v-model:is-show="showSettingChunkIndexModal"
      :kd-id="kdId"
      :knowledge-chunk-key-list="chunkKeyList"
      @update-knowledge-chunk-index="handleUpdateKnowledgeChunkIndex"
      @confirm="handleCloseSettingChunkIndexModal"
    />

    <AddQAKnowledgeChunkModal
      v-model:is-show="showAddKnowledgeChunkModal"
      :btn-loading="knowledgeChunkBtnLoading"
      :knowledge-chunk-key-list="chunkKeyList"
      @confirm="handleAddQAKnowledgeChunk"
    />

    <EditQAKnowledgeChunkModal
      v-model:is-show="showEditKnowledgeChunkModal"
      :btn-loading="knowledgeChunkBtnLoading"
      :knowledge-chunk-key-list="chunkKeyList"
      :current-chunk-item="currentChunkItem"
      @confirm="handleEditQAKnowledgeChunk"
    />
  </div>
</template>

<style lang="scss" scoped>
:deep(.qa-knowledge-chunk-selection.n-data-table-td .n-checkbox) {
  margin-top: 46px;
}

:deep(.qa-knowledge-chunk-index.n-data-table-td) {
  padding-top: 56px;
}

:deep(.qa-knowledge-chunk-item.n-data-table-td) {
  padding-top: 56px;
  vertical-align: top;
}

:deep(.n-data-table-tr) {
  position: relative;
}
</style>
