<script lang="ts" setup>
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { DataTableInst } from 'naive-ui'
import { createDatabaseTableDetailColumns } from './columns'
import CustomPagination from '@/components/custom-pagination/custom-pagination.vue'
import { type DefaultPaginationData, usePagination } from '@/composables/usePagination'
import useTableScrollY from '@/composables/useTableScrollY'
import { DBTableDataItemInterface } from './type'
import { fetchGetDBTableDataList } from '@/apis/database'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()

const dbTableDataRef = useTemplateRef<DataTableInst>('dbTableDataRef')
const { pageContentWrapRef, tableContentY } = useTableScrollY(37 + 44 + 48 + 44)
const { paginationData, handlePageNoChange, handlePageSizeChange } = usePagination()

const dbTableName = ref('')
const dbTableDataListLoading = ref(false)

const tableColumns = ref<string[]>([])

const dbTableDataList = ref<DBTableDataItemInterface[][]>([])

const dbTableColumns = computed(() => {
  return createDatabaseTableDetailColumns(tableColumns.value)
})

const dbTableScrollX = computed(() => {
  return tableColumns.value.length * 170
})

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

onMounted(() => {
  dbTableName.value = (route.params.tableName as string) || ''

  getDBTableDataList()
})

async function getDBTableDataList() {
  const payload = {
    id: route.params.databaseId as string,
    table: route.params.tableName as string,
    pagingInfo: paginationData,
  }
  dbTableDataListLoading.value = true
  const res = await fetchGetDBTableDataList<{
    column: string[]
    tableDatas: { type: string; value: any }[][]
    pageInfo: DefaultPaginationData
  }>(payload).finally(() => {
    dbTableDataListLoading.value = false
  })

  if (res.code === 0) {
    tableColumns.value = res.data.column
    dbTableDataList.value = res.data.tableDatas.map((tableDataItem) => {
      return tableDataItem.map((item, index) => {
        return { ...item, key: tableColumns.value?.[index] }
      })
    })
    paginationData.totalPages = res.data?.pageInfo?.totalPages || 0
    paginationData.totalRows = res.data?.pageInfo?.totalRows || 0
  }
}

function handleNavBack() {
  router.replace({
    name: 'PersonalSpaceDBTable',
    params: { id: route.params.databaseId as string },
  })
}
</script>

<template>
  <div ref="pageContentWrapRef" class="flex h-full w-full flex-col overflow-hidden">
    <div class="mb-4">
      <span class="cursor-pointer select-none text-[14px] hover:opacity-80" @click="handleNavBack">
        <i class="iconfont icon-left mr-[6px] text-[12px]"></i>
        <span>{{ dbTableName || '返回数据表列表' }}</span>
      </span>
    </div>

    <div class="flex h-full w-full flex-1 flex-col overflow-hidden rounded-[10px] bg-white p-[22px]">
      <div class="h-full w-full flex-1">
        <n-data-table
          ref="dbTableDataRef"
          :loading="dbTableDataListLoading"
          :columns="dbTableColumns"
          :data="dbTableDataList"
          :bordered="true"
          :bottom-bordered="true"
          :max-height="tableContentY"
          :scroll-x="dbTableScrollX"
        >
          <template #empty>
            <div :style="{ height: tableContentY + 'px' }" class="flex items-center justify-center">
              <div class="flex flex-col items-center justify-center">
                <div class="bg-px-empty_list-png mb-5 h-[68px] w-[68px]" />
                <p class="text-gray-font-color select-none">{{ t('common_module.empty_data') }}</p>
              </div>
            </div>
          </template>
        </n-data-table>
      </div>

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