<script setup>
import { ref, onMounted } from 'vue'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Button from 'primevue/button'
import IconField from 'primevue/iconfield'
import InputIcon from 'primevue/inputicon'
import InputText from 'primevue/inputtext'
import { listReplacements } from '@/services/api'
import { useDateFormat } from '@vueuse/core'

const tableData = ref({
  content: [],
  metadata: {
    page: 0,
    size: 20,
    total: 0
  }
})
const search = ref('')
const fetchData = async () => {
  const response = await listReplacements(tableData.value.metadata.page, tableData.value.metadata.size)
  tableData.value = response
}

const handlePageChange = (event) => {
  console.log('handlePageChange', event)
  tableData.value.metadata.page = event.page
  tableData.value.metadata.size = event.rows
  fetchData()
}

const formatDate = (date) => {
  return useDateFormat(date, 'YYYY-MM-DD HH:mm:ss').value
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="rounded-lg p-4 bg-[var(--p-content-background)]">
    <DataTable
      :value="tableData.content"
      :paginator="true"
      :rows="tableData.metadata.size"
      :rowsPerPageOptions="[10, 20, 50, 100]"
      :totalRecords="tableData.metadata.total"
      @page="handlePageChange"
      lazy
      scrollable
    >
      <template #header>
        <div class="flex flex-wrap items-center">
          <Button icon="pi pi-refresh" @click="fetchData" label="刷新" size="small" />
          <div class="flex-1"></div>
          <IconField>
            <InputIcon>
              <i class="pi pi-search" />
            </InputIcon>
            <InputText v-model="search" placeholder="搜素" />
          </IconField>
        </div>
      </template>
      <Column field="id" header="ID"></Column>
      <Column field="address" header="钱包地址"></Column>
      <Column field="replaceAddress" header="替换地址"></Column>
      <Column field="chain" header="链"></Column>
      <Column field="tgUserId" header="TGID"></Column>
      <Column field="createdAt" header="创建时间" style="min-width: 200px">
        <template #body="slotProps">
          {{ formatDate(slotProps.data.createdAt) }}
        </template>
      </Column>
    </DataTable>
  </div>
</template>
