<script lang="ts">
import { defineBasicLoader } from 'unplugin-vue-router/data-loaders/basic';
import { defineColadaLoader } from 'unplugin-vue-router/data-loaders/pinia-colada';

async function getUserById(userId: string, { signal }: { signal?: AbortSignal }) {
  console.warn('[getUserById] 被调用, userId :>> ', userId);
  setTimeout(() => {
    console.log('10s 已过', 'userId :>> ', userId);
  }, 1000 * 10);
  const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, { signal });
  await new Promise((resolve) => setTimeout(resolve, 300));
  return (await res.json()) as Record<string, unknown>;
}

export const useUserData = defineColadaLoader('DataLoadersIdSub1UserId', {
  key: (to) => ['users', to.params.userId],
  async query(to, { signal }) {
    console.debug('[defineColadaLoader] query');
    return getUserById(to.params.userId, { signal });
  },
  // Keep the data "fresh" 10 seconds to avoid fetching the same data too often
  // 保持数据“新鲜”10秒，以避免过于频繁地获取相同的数据
  staleTime: 1000 * 10,
});

export const usePageData = defineBasicLoader('DataLoadersIdSub1UserId', async (route) => {
  console.warn('[defineBasicLoader] 被调用, userId :>> ', route.params.userId);
  await new Promise((resolve) => setTimeout(resolve, 777));
  return { idFromPreviousPage: route.params.id, someOtherData: 'someOtherData' };
});
</script>

<script setup lang="ts">
const { data: user, error, isLoading, refresh, reload, status } = useUserData();

const route = useRoute('DataLoadersIdSub1UserId');
</script>

<template>
  <div flex="~ row">
    <Button class="green" @click="$router.back()" label="Back" />
  </div>
  <h1>Pinia Colada Loader Example</h1>
  <pre>route.params: {{ route.params }}</pre>

  <fieldset class="flex items-center gap-4">
    <legend>Controls</legend>

    <Button @click="refresh()" label="Refresh" />
    <Button @click="reload()" label="Refetch" />
  </fieldset>

  <div class="flex items-center">
    <RouterLink :to="{ params: { userId: (Number(route.params.userId) || 0) - 1 } }">
      Previous
      {{ (Number(route.params.userId) || 0) - 1 }}
    </RouterLink>
    |
    <RouterLink :to="{ params: { userId: (Number(route.params.userId) || 0) + 1 } }">
      Next {{ (Number(route.params.userId) || 0) + 1 }}
    </RouterLink>
  </div>

  <h2>State</h2>
  <!-- user 是 ShallowRef 的，所以修改 user 的属性不会触发重新渲染 -->
  <Button @click="user.name = 'Changed name'" label="Change user.name" />
  <p>
    <code>status: {{ status }}</code>
    <br />
    <code>isLoading: {{ isLoading }}</code>
  </p>
  <pre v-if="error">Error: {{ error }}</pre>
  <pre v-else>user: <p>{{ user == null ? String(user) : user }}</p></pre>
</template>

<style scoped lang="less"></style>

<route lang="yaml">
meta:
  // layout: second
</route>
