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

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


  <van-list style="padding-bottom: 3em" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
    offset="100" @load="loadData">
    <list-item-card v-for="item in items" :key="item" :item="item" :bought="bought" />
  </van-list>
</template>

<script>
import request from "@/utils/request";
import { defineComponent, ref } from "vue";

export default defineComponent({
  props: {
    bought: Boolean,
  },
  setup(props) {
    const search = ref("");
    const items = ref([]);
    const loading = ref(false);
    const finished = ref(false);
    const pageLimit = ref(10);
    const offset = ref("");

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

      request
        .post("/medias", data)
        .then((res) => {
          console.log("response: ", res);
          if (res === undefined) {
            console.error("response error with undefined");
            return;
          }

          if (offset.value == "") {
            items.value = res.data;
          } else {
            items.value = items.value.concat(res.data);
          }
          offset.value = res.data[res.data.length - 1].hash;
          console.log("offset: ", offset.value);

          if (res.data.length < pageLimit.value) {
            console.log("finished");
            finished.value = true;
          }
        })
        .catch((err) => {
          console.error("ERROR", err);
        })
        .finally(() => {
          loading.value = false;
          console.log("finally: ", loading.value, finished.value);
        });
    };

    return {
      search,
      items,
      loading,
      finished,
      loadData,
    };
  },
});
</script>
