<template>
  <v-table>
    <thead>
      <tr>
        <th class="text-left">ID</th>
        <th class="text-left">Character</th>
        <th class="text-left">Role</th>
        <th class="text-left">Player</th>
        <th class="text-left">Status</th>
        <th class="text-left">Last Game</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="character in characters">
        <td>
          <a v-bind:href="`/#/characters/${character.id}`">{{ character.id }}</a>
        </td>
        <td>
          <a v-bind:href="`/#/characters/${character.id}`">{{ character.characterName }}</a>
        </td>
        <td>{{ character.role }}</td>
        <td>{{ character.playerName }}</td>
        <td>{{ character.status }}</td>
        <td>{{ character.lastGame }}</td>
        <td>0</td>
      </tr>
    </tbody>
  </v-table>
  <v-pagination
    :model-value="page"
    :length="pageCount"
    @update:modelValue="setPage($event)"
  ></v-pagination>
</template>

<style type="text/css"></style>

<script setup lang="ts">
import { onMounted, onCreated, ref } from 'vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

const characters = ref({})
const pageCount = ref(1)
const page = ref(1)

let count = 10

async function loadData() {
  const response = await axios.post('/api/character', {
    page: `${page.value-1}`,
    count: `${count}`,
    orderBy: 'id'
  })

  characters.value = response.data.characterData
  pageCount.value = response.data.pageCount
}

function setPage(targetPage: number) {
  console.log(targetPage)
  router.replace({query: {page: targetPage}})
}

watch(route, (newValue, oldValue) => {
  page.value = Number(route.query.page)
  loadData()
})

onMounted(async () => {
  if(!route.query.page){
    router.replace({query: {page: 1}})
  }
  page.value = Number(route.query.page)
  loadData()
})
</script>
