<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useMainStore } from "@/stores/store";
import { useI18n } from "vue-i18n";
import axios from "axios";
import CourseCard from "@/components/CourseCard.vue";

const { t } = useI18n();
const store = useMainStore();

onMounted(() => {
  store.getFavoriteClass();
});

let pinkoiCourse = ref(null);
let pinkoi = reactive({
  classes: [],
});

let loading = ref(false);
let pageNum = ref(1); // 頁數
let totalPages = ref(1); // 總頁數
let pageAmount = ref(12); // 每頁顯示筆數

watch(pageNum, () => {
  getClasses();
});

// 取得清單
async function getClasses() {
  loading.value = true;
  try {
    const response = await axios.get(
      `${store.apiUrl}/api/get_class_name?group_id=2&group_sort=pinkoi&page_num=${pageNum.value}&page_amount=${pageAmount.value}`
    );
    totalPages.value = store.getTotalPages(
      response.data.total_num,
      pageAmount.value
    );
    pinkoi.classes = response.data.classes;
    setTimeout(() => {
      pinkoiCourse.value.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 300);
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error(error);
  }
}

getClasses();
</script>

<template>
  <div
    class="d-flex flex-column flex-sm-row align-center justify-space-between pb-10"
    ref="pinkoiCourse"
  >
    <h3 class="mb-0 sub-title">手作體驗課程</h3>
    <div class="search">
      <span>
        <input
          v-model="searchInput"
          type="text"
          @keyup.enter="search()"
          :placeholder="t('keyword_search')"
        />
        <button @click="search()">
          <img
            src="@/assets/img/news/news-search-icon.png"
            alt="臺灣工藝學習平台"
          />
        </button>
      </span>
      <div
        v-if="searchError"
        class="d-flex justify-center align-center error me-4"
      >
        <v-icon color="primary" icon="mdi-alert" class="me-2"></v-icon>
        {{ t("no_found") }}
      </div>
    </div>
  </div>

  <div class="d-flex justify-center" v-if="loading">
    <v-progress-circular
      color="grey-lighten-4"
      indeterminate
    ></v-progress-circular>
  </div>

  <v-row>
    <v-col
      sm="6"
      md="4"
      cols="12"
      v-for="(item, index) in pinkoi.classes"
      :key="index"
      class="pa-5"
    >
      <CourseCard :data="item" />
    </v-col>
    <v-col cols="12">
      <v-pagination
        v-model="pageNum"
        :length="totalPages"
        rounded="circle"
        class="mt-16"
      ></v-pagination>
    </v-col>
  </v-row>
</template>
