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

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

let loading = ref(false);
let searchInput = ref("");
let searchError = ref(false);
let currentPage = ref(1); // 當前頁數(預設第一頁)
let itemsPerPage = ref(5); // 每頁顯示筆數
let totalPages = ref(1); // 總頁數
let newsAll = reactive({
  list: [],
});
let newsData = reactive({
  list: [],
});
let category = ref([]);
let categoryVal = ref("");

function filterCategory(item) {
  categoryVal.value = item;
  console.log("filterCategory", item);
  getData();
}

async function getData() {
  loading.value = true;
  let url = `${store.apiUrl}/api/get_news`;

  if (categoryVal.value !== "") {
    url += `?category=${categoryVal.value}`;
  }

  try {
    const response = await axios.get(url);
    console.log("response", response.data.news);
    newsAll.list = response.data.news;
    newsData.list = response.data.news;

    // 存 category
    const categories = response.data.news.map((item) => item.category);
    categories.forEach((item) => {
      if (!category.value.includes(item)) {
        category.value.push(item);
      }
    });
    console.log("category", category.value);

    totalPages.value = store.getTotalPages(response.data.news.length, 5); // 計算頁數
    loading.value = false;
  } catch (error) {
    console.error(error);
  }
}

getData();

// 搜尋
async function search() {
  searchError.value = false;
  let keyword = searchInput.value;
  if (keyword !== "") {
    try {
      const response = await axios.get(
        `${store.apiUrl}/api/search_news_like?keyword=${keyword}`
      );
      if (response.data.news.length !== 0) {
        newsData.list = response.data.news;
        totalPages.value = store.getTotalPages(response.data.news.length, 5);
        if (totalPages.value === 1) {
          currentPage.value = 1;
        }
      } else {
        searchError.value = true;
      }
    } catch (error) {
      console.error(error);
    }
  } else {
    newsData.list = newsAll.list;
    totalPages.value = store.getTotalPages(response.data.news.length, 5);
  }
}

const searchLocation = ref(null);

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

// 分頁顯示
const paginatedList = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage.value;
  const endIndex = startIndex + itemsPerPage.value;
  return newsData.list.slice(startIndex, endIndex);
});

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

const categoryList = reactive([
  {
    title: "總覽",
  },
  {
    title: "一日學徒",
  },
  {
    title: "工藝行旅",
  },
  {
    title: "希望工程",
  },
  {
    title: "展覽資訊",
  },
  {
    title: "補助計畫",
  },
  {
    title: "策展補助",
  },
]);
</script>

<template>
  <Navbar />
  <div class="position-relative">
    <img
      src="@/assets/img/news/news-01.png"
      alt="臺灣工藝學習平台"
      class="material-img"
    />
    <v-container>
      <!-- <img
        src="@/assets/img/news/news-banner.png"
        alt="臺灣工藝學習平台"
      /> -->

      <div class="content py-10 mt-16">
        <div class="bg-img">
          <img
            src="@/assets/img/news/news-bg.webp"
            alt="臺灣工藝學習平台"
          />
        </div>

        <v-breadcrumbs :items="breadcrumbs" divider="/" class="my-5">
          <template v-slot:title="{ item }">
            {{ t(item.title) }}
          </template>
        </v-breadcrumbs>

        <div class="search pt-5 mb-10 me-sm-16" ref="searchLocation">
          <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 class="category-btn pt-5 pb-10">
          <v-btn
            v-for="(item, index) in category"
            :key="index"
            rounded="xl"
            color="purple"
            variant="flat"
            :class="{ 'me-5': index !== category.length - 1 }"
            class="mb-5"
            @click="filterCategory(item)"
          >
            {{ item }}
          </v-btn>
        </div>

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

        <ul>
          <li v-for="(item, index) in paginatedList" :key="index" class="mb-16">
            <ArticleCard :data="item" type="news" />

            <!-- <section class="d-flex">
              <p class="category mb-5">
                <span></span>
                {{ item.category }}
              </p>
              <p class="ms-5">
                {{ moment(`${item.create_time}`).format("YYYY-MM-DD") }}
              </p>
            </section>
            <v-card
              variant="outlined"
              class="d-flex flex-md-row flex-column align-center pa-5"
            >
              <v-row class="align-center">
                <v-col cols="12" sm="4">
                  <router-link :to="`/news/${item.news_id}`" class="cover-img">
                    <img src="@/assets/img/img-01.jpg" alt="臺灣工藝學習平台" />
                  </router-link>
                </v-col>
                <v-col cols="12">
                  <router-link :to="`/news/${item.news_id}`" class="cover-img">
                    <section
                      class="d-flex flex-column pa-3"
                    >
                      <h2>{{ item.title }}</h2>
                      <p v-html="item.content"></p>
                    </section>
                  </router-link>
                </v-col>
              </v-row>
            </v-card> -->
          </li>
        </ul>

        <div class="pagination-item">
          <v-pagination
            v-model="currentPage"
            class="my-4"
            :length="totalPages"
          ></v-pagination>
        </div>
      </div>
    </v-container>
    <img
      src="@/assets/img/news/news-01.png"
      alt="臺灣工藝學習平台"
      class="material-img"
    />
  </div>
</template>

<style lang="scss" scoped>
.material-img {
  position: absolute;

  &:first-child {
    top: -15vw;
  }

  &:last-child {
    bottom: 0;
    z-index: -5;
    transform: scaleX(-1);

    @media (max-width: 600px) {
      bottom: 0.625em;
    }
  }
}

.category-btn {
  max-width: 1000px;
  margin: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;

  .v-btn {
    width: 8.125em;
    font-size: 1em;
  }
}

.content {
  position: relative;
  margin-bottom: 12.5em;

  @media (max-width: 960px) {
    margin-bottom: 6.25em;
  }

  .bg-img {
    display: flex;
    justify-content: center;
    position: absolute;
    z-index: -1;
    top: 0;
    right: 0;
    left: 0;
    bottom: -6.875em;

    @media (max-width: 960px) {
      bottom: -1.875em;
    }

    img {
      min-width: 105%;
    }
  }

  ul {
    padding: 0 5em;

    @media (max-width: 600px) {
      padding: 0 1.25em;
    }

    li {
      letter-spacing: 0.0625em;

      .v-card {
        background-color: #fff;

        section {
          h2 {
            margin-bottom: 1.25em;
            font-size: 1.625em;
            font-weight: 500;
            line-height: 2.25em;
            @media (max-width: 600px) {
              font-size: 1.375em;
              line-height: 1.875em;
            }
          }

          p {
            // 超過三行則省略
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            line-break: after-white-space;
            line-height: 1.375em;
          }
        }

        .cover-img {
          display: block;
          overflow: hidden;
          img {
            width: 100%;
            height: 12.5em;
            object-fit: cover;
            transition: all 0.5s;
            &:hover {
              transform: scale(1.1);
            }

            @media (max-width: 960px) {
              width: 100%;
              height: 18.75em;
            }

            @media (max-width: 600px) {
              min-width: auto;
              height: 50vw;
            }
          }
        }
      }

      .category {
        display: flex;
        align-items: center;

        span {
          display: block;
          width: 0.5em;
          height: 0.5em;
          margin-right: 0.625em;
          border-radius: 0.625em;
          background-color: #000;
        }
      }
    }
  }

  .pagination-item {
    margin: auto;
    max-width: 31.25em;
  }
}
</style>
