<script setup>
import { ref, reactive, watch } from "vue";
import { useMainStore } from "@/stores/store";
import axios from "axios";

const store = useMainStore();

let favorites = reactive({
  list: [],
});

let favoritesAll = reactive({
  list: [],
});

let token = store.token;

// 取得收藏課程
async function getFavoriteClass() {
  try {
    const response = await axios.get(
      `${store.apiUrl}/api/get_favorite_class?access_token=${token}`
    );
    console.log(
      "response.data.favorite_courses",
      response.data.favorite_courses
    );
    favorites.list = response.data.favorite_courses;
    favoritesAll.list = response.data.favorite_courses;
  } catch (error) {
    console.error(error);
  }
}

getFavoriteClass();

let progress = ref(false);
let timeoutId = null;
let searchError = ref(false);
const searchText = ref("");
const filtered = reactive({
  list: [],
});

watch(searchText, (val) => {
  if (val === "") {
    favorites.list = favoritesAll.list;
  }
});

// 延遲觸發
const handleInput = () => {
  clearTimeout(timeoutId);
  timeoutId = setTimeout(handleSearch, 500);
};

// 課程搜尋
const handleSearch = () => {
  filtered.list = favorites.list.filter((item) =>
    item.name.includes(searchText.value)
  );
  if (filtered.list.length) {
    favorites.list = filtered.list;
    searchError.value = false;
  } else {
    favorites.list = favoritesAll.list;
    searchError.value = true;
    setTimeout(() => {
      searchError.value = false;
    }, 2000);
  }
  console.log("filtered", filtered);
};
</script>

<template>
  <v-card class="h-100">
    <div class="title">
      <h4>帳戶設定</h4>
    </div>
  </v-card>
</template>

<style lang="scss" scoped>
.error {
  height: 1.5em;
}
</style>
