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

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const store = useMainStore();
const bookName = route.params.id; // 網址參數(pdf書名)
console.log("bookName", bookName);

onMounted(() => {
  if (bookName) {
    updatePDF(bookName);
  }
});

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

(async function getData() {
  try {
    const response = await axios.get(`${store.apiUrl}/api/get_news`);
    console.log("response", response.data.news);
    newsAll.list = response.data.news;
    newsData.list = response.data.news;
    totalPages.value = store.getTotalPages(response.data.news.length, 5); // 計算頁數
  } catch (error) {
    console.error(error);
  }
})();

// 搜尋
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;
      } else {
        searchError.value = true;
      }
    } catch (error) {
      console.error(error);
    }
  } else {
    newsData.list = newsAll.list;
  }
}

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: "article",
    disabled: true,
    href: "/article",
  },
]);

const tagList = reactive([
  {
    title: "工藝書單",
    url: "#bookList",
  },
  {
    title: "線上閱讀",
    url: "#readList",
  },
  {
    title: "國際專欄",
    url: "#articleList",
  },
  {
    title: "工藝中心圖書館",
    url: "https://ntcrilib.blogspot.com/",
  },
  {
    title: "線上影音",
    url: "",
  },
]);

// const articleList = reactive([
//   {
//     title: "法國工藝中心雜誌",
//     depiction: "CMA, artisans of the new economy_Magazin",
//     img: store.getImageUrl("article/知識文章-14.webp"),
//     url: "https://www.artisanat.fr/magazine/actus",
//   },
//   {
//     title: "法國不同地區的工藝匠結合各地特色的作品",
//     depiction: "8 Skills of French Craftsmen",
//     img: store.getImageUrl("article/知識文章-15.webp"),
//     url: "https://www.france.fr/zh-Hant/%E6%97%85%E9%81%8A%E7%9B%AE%E7%9A%84%E5%9C%B0/%E6%B8%85%E5%96%AE/ateliers-savoir-faire-francais-%E6%B3%95%E5%9C%8B%E8%83%BD%E5%B7%A5%E5%B7%A7%E5%8C%A0%E7%9A%84-8-%E9%A0%85%E6%8A%80%E8%97%9D",
//   },
//   {
//     title: "從古至今的里昂絲綢工藝演變",
//     depiction: "Approaching Lyon's silk",
//     img: store.getImageUrl("article/知識文章-16.webp"),
//     url: "https://www.france.fr/zh-Hant/%E9%87%8C%E6%98%82/%E6%B8%85%E5%96%AE/experiences-soie-%E8%B5%B0%E8%BF%91%E9%87%8C%E6%98%82%E7%9A%84%E7%B5%B2%E7%B6%A2",
//   },
//   {
//     title: "義大利威尼斯琉璃工藝",
//     depiction: "Artisanat verrier vénitien",
//     img: store.getImageUrl("article/知識文章-17.webp"),
//     url: "https://www.sightseeinginitaly.com/fr/le-nord-est-de-litalie/region-venetie/artisanat-de-la-venetie/verre-de-murano-technique-verriere-artisanale/",
//   },
//   {
//     title: "日本北海道小樽玻璃工藝",
//     depiction: "小樽ガラスの特徴｜歴史ある有名工芸品の魅力を探る",
//     img: store.getImageUrl("article/知識文章-18.webp"),
//     url: "https://chiikihyaku-jp.translate.goog/goods/734.html?_x_tr_sl=ja&_x_tr_tl=zh-TW&_x_tr_hl=zh-TW&_x_tr_pto=sc",
//   },
//   {
//     title: "日本漆藝介紹",
//     depiction: "GALLERY JAPAN",
//     img: store.getImageUrl("article/知識文章-19.webp"),
//     url: "https://www-galleryjapan-com.translate.goog/locale/ja_JP/technique/urushiwork/?_x_tr_sl=ja&_x_tr_tl=zh-TW&_x_tr_hl=zh-TW&_x_tr_pto=sc",
//   },
//   {
//     title: "捷克木偶工藝",
//     depiction: "Puppetry",
//     img: store.getImageUrl("article/知識文章-20.webp"),
//     url: "https://www.visitczechrepublic.com/en-US/ff6094fa-b99b-4bb5-9643-2f4d2d375710/place/c-unesco-puppetry",
//   },
//   {
//     title: "美國印地安人傳統工藝品介紹",
//     depiction: "Southwestern Arts and Crafts",
//     img: store.getImageUrl("article/知識文章-21.webp"),
//     url: "https://www.desertusa.com/desert-people/indian-craft.html",
//   },
// ]);

// function getPDF(name) {
//   return `${store.imgUrl}/pdf/${name}.pdf`;
// }

let fileName = ref(""); // PDFViewer Props
const read = ref(null);
const viewer = ref(null);

function updatePDF(name) {
  // 更新 pdf 後移除網址參數
  router.replace({ path: "/article" });
  fileName.value = name;
  if (!store.isMobile) {
    setTimeout(() => {
      viewer.value.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 300);
  }
}

function isAnchorLink(url) {
  console.log("url", url, url.startsWith("#"));
  // 檢查 URL 是否為錨點
  return url.startsWith("#");
}
</script>

<template>
  <Navbar />
  <div class="bg-img">
    <v-container class="position-relative">
      <div class="article-content">
        <v-breadcrumbs :items="breadcrumbs" divider="/" class="my-5">
          <template v-slot:title="{ item }">
            {{ t(item.title) }}
          </template>
        </v-breadcrumbs>

        <v-row class="px-10 pb-3 tag-btn">
          <v-col
            v-for="(item, index) in tagList"
            :key="index"
            class="ma-2 item"
          >
            <a
              v-if="isAnchorLink(item.url)"
              :href="item.url"
              class="py-3 py-lg-6"
            >
              <!-- 錨點 -->
              {{ item.title }}
            </a>
            <a v-else :href="item.url" target="_blank" class="py-3 py-lg-6">
              <!-- 網址 -->
              {{ item.title }}
            </a>
          </v-col>
        </v-row>

        <h2 id="articleList">國際專欄</h2>

        <div class="search pt-5 my-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>

        <v-row class="list">
          <v-col
            cols="12"
            sm="6"
            v-for="(item, index) in articleList"
            :key="index"
          >
            <a :href="item.url" target="_blank">
              <img :src="item.img" alt="臺灣工藝學習平台" />
            </a>
            <section>
              <p>{{ item.depiction }}</p>
              <h3>{{ item.title }}</h3>
            </section>
          </v-col>
        </v-row>

        <h2 ref="read">線上閱讀</h2>

        <v-row class="justify-center mt-16 read-list">
          <v-col
            cols="12"
            sm="6"
            md="4"
            v-for="(item, index) in readList"
            :key="index"
            class="d-flex flex-column align-center px-10"
          >
            <a
              v-if="store.isMobile"
              :href="store.getPDF(item.fileName)"
              target="_blank"
            >
              <img :src="item.img" alt="臺灣工藝學習平台" />
            </a>

            <img
              v-else
              :src="item.img"
              alt="臺灣工藝學習平台"
              @click="updatePDF(item.fileName)"
            />

            <!-- <a :href="item.url" target="_blank">
              <img :src="item.img" alt="臺灣工藝學習平台" />
            </a> -->
            <section>
              <h3 v-html="item.title"></h3>
              <p>{{ item.depiction }}</p>
            </section>
          </v-col>
        </v-row>

        <div ref="viewer">
          <PDFViewer :file="fileName" />
        </div>

        <h2 id="bookList">工藝書單</h2>

        <div class="search pt-5 my-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>

        <v-row class="justify-center book-list">
          <v-col
            cols="12"
            sm="10"
            md="6"
            v-for="(item, index) in bookList"
            :key="index"
            class="position-relative mt-10 mb-16 pb-16"
          >
            <a :href="$router.resolve(`/article-detail/${index}`).href">
              <div class="overflow-hidden">
                <v-img
                  class="mx-auto cover-img"
                  :lazy-src="item.img"
                  :src="item.img"
                  cover
                  alt="臺灣工藝學習平台"
                >
                  <template v-slot:placeholder>
                    <div class="d-flex align-center justify-center fill-height">
                      <v-progress-circular
                        color="grey-lighten-4"
                        indeterminate
                      ></v-progress-circular>
                    </div>
                  </template>
                </v-img>
              </div>
            </a>

            <!-- <a :href="item.url" target="_blank">
              <img :src="item.img" alt="臺灣工藝學習平台" />
            </a> -->
            <section class="info">
              <p v-html="item.content"></p>
              <span>{{ item.category }}</span>
            </section>
          </v-col>
        </v-row>

        <!-- <v-pagination
          v-model="currentPage"
          class="my-4"
          :length="totalPages"
        ></v-pagination> -->
      </div>
    </v-container>
  </div>
</template>

<style lang="scss" scoped>
h2 {
  padding-top: 6.25em;
  font-size: 1.875em;
  font-weight: 500;
  text-align: center;
}

.bg-img {
  background-image: url("@/assets/img/crafts/background.png");
  background-size: cover;
  background-position: top;
  @media (max-width: 960px) {
    background-size: contain;
    background-repeat: repeat;
  }
}

.list,
.read-list,
.book-list {
  p {
    margin-bottom: 0.625em;
  }
  h3,
  p {
    font-weight: 500;
    text-align: center;
    line-height: 1.875em;
  }
}

.read-list {
  img {
    width: 100%;
    height: 28.125em;
    object-fit: cover;
    cursor: pointer;

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

  p {
    width: 18.125em;
  }
}

.book-list {
  margin-bottom: 18.75em;
  .info {
    width: 26.875em;
    padding: 0.625em 1.25em;
    position: absolute;
    right: -2.5em;
    bottom: -3.75em;
    z-index: 1;
    background: rgba(255, 255, 255, 0.8);
    border: 0.125em solid #c8cbcc;

    @media (max-width: 1280px) {
      width: 25em;
    }

    @media (max-width: 600px) {
      width: 20.625em;
      right: -0.1875em;
      bottom: -5em;
    }

    p {
      width: 18.75em;
      margin-bottom: 0;
      text-align: start;
    }
    span {
      display: block;
      margin-top: auto;
      position: absolute;
      bottom: 0.9375em;
      right: 0.9375em;
    }
  }
}
</style>
