<template>
  <van-search v-model="search" placeholder="请输入搜索关键词" />

  <van-back-top bottom="80" />

  <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" offset="100" @load="loadData">
    <van-card v-for="item in items" :key="item" :desc="item.title" :thumb="item.poster" @click="play(item)">
      <template #title>
        <span>{{ item.title }}</span>
      </template>
      <template #price>
        <template v-if="item.discount == 100"> 价格：{{ item.price }} 点 </template>

        <template v-else>
          <del>{{ item.price }}</del>
          <span>{{ (item.price * item.discount) / 100 }}</span>
        </template>
      </template>

      <template #tags>
        <van-space>
          <van-tag v-for="resource in item.resources" plain type="primary">
            <template v-if="resource == 'video'">视频</template>
            <template v-if="resource == 'audio'">音频</template>
          </van-tag>
        </van-space>
      </template>
    </van-card>
  </van-list>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import request from "@/utils/request";

const router = useRouter();

const search = ref("");
const items = ref([]);
const loading = ref(false);
const finished = ref(false);
const pageLimit = ref(10);

const offset = ref("");

const play = (item) => {
  // vue router goto play view
  console.log("play -", item);
  router.push({ name: "play", params: { id: item } });
};

const loadData = () => {
  // request /v1/medias
  const data = {
    offset: offset.value,
    limit: pageLimit.value,
    action: 0,
    bought: true,
  };
  console.log("loadData, data: ", data);

  loading.value = true;
  request
    .post("/medias", data)
    .then((res) => {
      loading.value = false;

      console.log("response: ", res);
      if (offset.value == "") {
        items.value = res.data;
      } else {
        items.value = items.value.concat(res.data);
      }

      if (res.data.length < pageLimit.value) {
        console.log("finished");
        finished.value = true;
        loading.value = false;
      }

      offset.value = res.data[res.data.length - 1].hash;
    })
    .catch((err) => {
      console.error(err);
    })
    .finally(() => {
      // finished.value = true;
    });
};

onMounted(() => {
  // loadData();
});
</script>
