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

const { t } = useI18n();
const store = useMainStore();
let pageNum = ref(1); // 頁數(預設第一頁)
let pageAmount = ref(18); // 每頁顯示筆數
let totalPages = ref(1); // 總頁數

let loading = ref(false);
let searchInput = ref("");
let searchError = ref(false);

const courseAll = reactive({
  classes: [],
});
const courseData = reactive({
  classes: [],
});

const listLocation = ref(null);
let isInternal = ref(false); // 是否選取學習時數課程(只顯示內課)
let isFilter = ref(false); // 篩選狀態
let searchList = reactive([]); // 篩選條件
let totalNum = ref(0); // 資料總筆數
let locationKeyword = ref(""); // 縣市搜尋關鍵字

// 切換分頁時回到列表上方
watch(pageNum, () => {
  getClass();
  listLocation.value.scrollIntoView({ behavior: "smooth", block: "start" });
});

async function getClass() {
  loading.value = true;
  let url = `${store.apiUrl}/api/get_class_name?is_check=1&page_num=${pageNum.value}&page_amount=${pageAmount.value}`;
  console.log("isFilter", isFilter.value);

  // 排除外部課程
  if (isInternal.value) {
    url += "&is_inner=1";
  }

  // 判斷篩選
  if (isFilter.value) {
    console.log("searchList", searchList);
    searchList.map((item) => {
      url += item;
    });

    // 地區搜尋
    if (locationKeyword.value !== "") {
      url += `&location_keyword=${locationKeyword.value}`;
    }
  }

  try {
    const response = await axios.get(url);
    totalPages.value = store.getTotalPages(response.data.total_num, 18);
    courseAll.classes = response.data.classes;
    courseData.classes = response.data.classes;
    totalNum.value = response.data.total_num;
    loading.value = false;
    console.log("getClass response", response);
  } catch (error) {
    loading.value = false;
    console.error(error);
  }
}

getClass();

// 搜尋
async function search() {
  console.log("search", searchInput.value);

  if (searchInput.value === "") {
    courseData.classes = courseAll.classes;
    return;
  }

  try {
    loading.value = true;
    const response = await axios.get(
      `${store.apiUrl}/api/search_class_like?keyword=${searchInput.value}`
    );
    totalPages.value = store.getTotalPages(response.data.total_num, 18);
    courseData.classes = response.data.classes;
    loading.value = false;
    console.log("搜尋 response", response);

    if (!response.data.total_num) {
      searchError.value = true;
    } else {
      searchError.value = false;
    }
  } catch (error) {
    loading.value = false;
    console.error(error);
  }
}

const breadcrumbs = reactive([
  {
    title: "home.title",
    disabled: false,
    href: "/",
  },
  {
    title: "navbar.craft_course",
    disabled: true,
  },
]);

let assignTag = ref("all");

watch(assignTag, (val) => {
  if (val === "all") {
    isInternal.value = false;
  } else {
    isInternal.value = true;
  }
  pageNum.value = 1;
  getClass();
});

function selectTag(btn) {
  if (btn === "all") {
    assignTag.value = "all";
  } else {
    assignTag.value = "hours";
  }
}

let selectSort = ref();
let selectLocation = ref();
let selectYear = ref();
let selectCategory = ref([]);

// 篩選課程
async function selectFilter(type, val) {
  isFilter.value = true;
  pageNum.value = 1; // 篩選時返回第一頁
  searchList.splice(0, searchList.length); // 清空陣列

  if (type === "category") {
    searchList.push(`&category=${val}`);
    console.log("searchList", searchList);
  } else if (type === "location") {
    locationKeyword.value = val;
  }

  getClass();
}

// // 取得全部課程
// function getAllClass() {
//   // selectCategory.value = [];
//     isFilter.value = false;
//     pageNum.value = 1;
//     getClass();
// }

// 地圖搜尋
let selectedCounty = ref(null); // 縣市
let selectedDistrict = ref(null); // 區域

// 縣市
let counties = reactive({
  list: [],
});

TwCities.map((e) => counties.list.push(e.name));

// 區域
let district = reactive({
  list: [],
});

// 選擇縣市後顯示對應區域
watch(selectedCounty, (newValue) => {
  district.list = [];
  selectedDistrict.value = null;
  TwCities.map((e) => {
    if (e.name === newValue) {
      e.districts.map((item) => district.list.push(item.name));
    }
  });
});

// 清除重填(取得全部課程)
function searchClear() {
  selectCategory.value = [];
  selectedCounty.value = null;
  selectedDistrict.value = null;
  isFilter.value = false;
  pageNum.value = 1;
  getClass();
}

async function searchClass() {
  isFilter.value = true;
  pageNum.value = 1; // 篩選時返回第一頁
  searchList.splice(0, searchList.length); // 清空陣列

  let categoryVal = selectCategory.value;
  if (categoryVal.length) {
    searchList.push(`&category=${categoryVal}`);
  }

  if (selectedCounty.value && selectedDistrict.value) {
    locationKeyword.value = `${selectedCounty.value}${selectedDistrict.value}`;
  } else if (selectedCounty.value && !selectedDistrict.value) {
    locationKeyword.value = `${selectedCounty.value}`;
  }

  getClass();
}

onMounted(() => {
  store.getFavoriteClass();
});
</script>

<template>
  <Navbar />
  <v-container fluid class="pb-16 px-0 college-content course-content">
    <v-row class="main-block">
      <v-col cols="12">
        <v-breadcrumbs :items="breadcrumbs" divider="/" class="mt-10 pa-0">
          <template v-slot:title="{ item }">
            {{ t(item.title) }}
          </template>
        </v-breadcrumbs>
      </v-col>
      <v-col cols="12" md="3" lg="2">
        <v-row class="filter-list">
          <v-col cols="12" sm="6" md="12" class="pb-0">
            <v-select
              v-model="selectCategory"
              :label="t('category')"
              :items="[
                '樹藝',
                '漆藝',
                '藍染',
                '蠟雕',
                '竹工藝',
                '金工/飾品',
                '蠟燭/香氛/調香',
                '植栽/花藝',
                '插畫/繪畫/寫字',
                '皮件/皮革',
                '木工/竹藝',
                '陶藝/玻璃',
                '編織/羊毛氈/縫紉',
              ]"
              multiple
              hide-details
            ></v-select>
          </v-col>

          <v-col cols="12" sm="6" md="12" class="pb-0">
            <v-select
              v-model="selectedCounty"
              :label="t('cities')"
              :items="counties.list"
              hide-details
            ></v-select>
          </v-col>

          <v-col
            cols="12"
            sm="6"
            md="12"
            class="pb-0"
            v-if="selectedCounty !== null"
          >
            <v-select
              v-model="selectedDistrict"
              :label="t('districts')"
              :items="district.list"
              hide-details
            ></v-select>
          </v-col>

          <v-col cols="12">
            <v-btn
              @click="searchClass()"
              variant="flat"
              color="purple"
              class="w-100"
            >
              {{ t("search") }}
            </v-btn>
            <v-btn
              @click="searchClear()"
              variant="outlined"
              color="gray"
              class="w-100 mt-5"
            >
              {{ t("reset") }}
            </v-btn>
          </v-col>
          <!-- <v-col cols="12">
            <v-btn class="w-100" variant="outlined" color="brown">
              清除重填
            </v-btn>
          </v-col> -->
        </v-row>
      </v-col>

      <v-col cols="12" md="9" lg="10">
        <div>
          <div
            class="d-flex flex-column flex-md-row align-center justify-space-between mb-14"
            ref="listLocation"
          >
            <div class="d-flex tab-btn mb-8 mb-md-0">
              <v-btn
                variant="text"
                @click="selectTag('all')"
                :class="{ active: assignTag === 'all' }"
              >
                {{ t("all_courses") }}
              </v-btn>
              <v-btn
                variant="text"
                @click="selectTag('hours')"
                :class="{ active: assignTag === 'hours' }"
              >
                {{ t("learning_hours_courses") }}
              </v-btn>
              <!-- <h2 class="me-5">課程清單</h2> -->
            </div>
            <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>
          </div>

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

          <v-row>
            <v-col
              sm="6"
              lg="4"
              cols="12"
              v-for="(item, index) in courseData.classes"
              :key="index"
              class="pa-5"
            >
              <CourseCard :data="item" />
            </v-col>
          </v-row>

          <div
            v-if="searchError"
            class="d-flex justify-center align-center pt-12 me-4"
          >
            <v-icon color="primary" icon="mdi-alert" class="me-2"></v-icon>
            {{ t("no_found") }}
          </div>

          <v-pagination
            v-if="!searchError"
            v-model="pageNum"
            :length="totalPages"
            rounded="circle"
            class="mt-16"
          ></v-pagination>

          <span class="text-gray total-item"
            >{{ t("total_count") }}：{{ totalNum }}</span
          >
        </div>
      </v-col>
      <v-col cols="12" class="my-16">
        <img
          src="@/assets/img/course/banner.webp"
          alt="臺灣工藝學習平台"
        />
      </v-col>
    </v-row>
  </v-container>
</template>

<style lang="scss">
.course-content {
  .banner {
    display: flex;
    justify-content: end;
    img {
      width: 75%;
    }
  }

  .main-block {
    margin-top: 0;
    padding: 0;
    @media (max-width: 1400px) {
      padding: 0 4.375em;
    }
    @media (max-width: 600px) {
      padding: 0 1.25em;
    }
    .title {
      padding: 0 0 5em;
    }
  }
  .filter-list {
    margin-top: 8.125em;
    @media (max-width: 960px) {
      margin: 1.25em 0;
    }
  }
}
</style>
