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

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

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

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

const categoryList = reactive([
  {
    id: 1256,
    title: "匠作之手",
    active: true,
  },
  {
    id: 1255,
    title: "手作學習",
    active: false,
  },
  {
    id: 1221,
    title: "工藝行旅",
    active: false,
  },
  {
    id: 1253,
    title: "檢測修復",
    active: false,
  },
]);

let loading = ref(false);
let pageNum = ref(1); // 頁數(預設第一頁)
let pageAmount = ref(18); // 每頁顯示筆數
let totalPages = ref(1); // 總頁數
let selectCategory = ref([]); // 選擇類別
let isFilter = ref(false); // 篩選狀態
let searchList = reactive([]); // 篩選條件
let totalNum = ref(0); // 資料總筆數

const courese = reactive({
  list: [],
});

async function getClass() {
  loading.value = true;
  let url = `${store.apiUrl}/api/get_online_courese?org=udemy&page_num=${pageNum.value}&page_amount=${pageAmount.value}`;

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

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

getClass();

const listLocation = ref(null);

watch(pageNum, () => {
  getClass();
  listLocation.value.scrollIntoView({ behavior: "smooth", block: "start" });
});

watch(selectCategory, (val) => {
  if (val.includes("全部")) {
    selectCategory.value = [];
    isFilter.value = false;
    pageNum.value = 1;
    getClass();
  } else {
    selectFilter("category", val);
  }
});

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

  if (type === "category") {
    searchList.push(`&category=${val}`);
  }

  getClass();
}

let activeCategory = ref(1256);

function setCategory(id, index) {
  activeCategory.value = id;
  // 移除 active
  categoryList.map((item) => {
    if (item.active) {
      item.active = false;
    }
  });
  categoryList[index].active = true;
  console.log("activeCategory.value", activeCategory.value);
  getImediaVideo();
}

const searchLocation = ref(null);
let imedia = reactive({
  list: [],
});
let imediaCurrentPage = ref(1); // 當前頁數(預設第一頁)
let imediaTotalPages = ref(1); // 總頁數

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

let videoLoading = ref(false);

async function getImediaVideo() {
  videoLoading.value = true;

  let url = `${store.apiUrl}/api/get_media_data?media_categories_id=${activeCategory.value}&page=${imediaCurrentPage.value}&page_size=8`;

  try {
    imedia.list = [];
    const response = await axios.post(url);
    const list = JSON.parse(response.data.data);
    list.data.map((item) => {
      if (item.video_link) {
        imedia.list.push(item);
      }
    });
    console.log("Imedia data", response.data);

    imediaTotalPages.value = store.getTotalPages(imedia.list.length, 8); // 計算頁數
    console.log("imediaTotalPages", imediaTotalPages.value);
    console.log("imedia list", imedia.list);

    videoLoading.value = false;
  } catch (error) {
    loading.value = false;
    console.error(error);
  }
}

getImediaVideo();
</script>

<template>
  <v-breadcrumbs :items="breadcrumbs" divider="/" class="mt-10 p-0">
    <template v-slot:title="{ item }">
      {{ t(item.title) }}
    </template>
  </v-breadcrumbs>

  <div
    class="d-flex flex-column flex-sm-row align-center justify-end my-16"
    ref="searchLocation"
  >
    <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>

  <v-row>
    <v-col sm="2" cols="12" class="px-0">
      <ul class="btn-list">
        <li v-for="(item, index) in categoryList" :key="index" class="mx-3">
          <v-btn
            @click="setCategory(item.id, index)"
            class="mb-5"
            :class="{ active: item.active }"
            variant="outlined"
          >
            {{ item.title }}
          </v-btn>
        </li>
      </ul>
    </v-col>
    <v-col sm="10" cols="12">
      <div class="d-flex justify-center mb-10" v-if="videoLoading">
        <v-progress-circular
          color="grey-lighten-4"
          indeterminate
        ></v-progress-circular>
      </div>

      <v-row class="video-list">
        <v-col
          cols="12"
          md="6"
          v-for="(item, index) in imedia.list"
          :key="index"
          class="mb-5 mb-md-0"
        >
          <v-dialog
            transition="dialog-top-transition"
            width="853"
            class="video-dialog"
          >
            <template v-slot:activator="{ props }">
              <div class="img-box">
                <v-img
                  v-bind="props"
                  class="mx-auto cover-img"
                  :lazy-src="item.image_m"
                  cover
                  :src="item.image_m"
                >
                  <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>
              <!-- <div class="img-box">
                <img v-bind="props" :src="item.image_m" alt="" />
              </div> -->
            </template>
            <template v-slot:default="{ isActive }">
              <v-card>
                <v-toolbar color="blue" class="ps-5 pe-7">
                  <div class="w-100 d-flex justify-space-between align-center">
                    <h3>{{ item.metadata[1].name }}</h3>
                    <div class="close-btn">
                      <v-icon
                        @click="isActive.value = false"
                        icon="mdi-close"
                      ></v-icon>
                    </div>
                  </div>
                </v-toolbar>
                <v-card-text class="pa-10">
                  <div class="video-box">
                    <video controls>
                      <source
                        :src="`${
                          item.video_link.video_source.mp4[3]
                            ? item.video_link.video_source.mp4[3]
                            : item.video_link.video_source.mp4[2]
                        }?api_access_key=08c9cdf9-a1d6-4997-943c-4f08f34ed2f7`"
                        type="video/mp4"
                      />
                      Your browser does not support the video tag.
                    </video>
                  </div>
                </v-card-text>
                <!-- <v-card-actions class="justify-end">
              <v-btn
                variant="text"
                @click="isActive.value = false"
              >Close</v-btn>
            </v-card-actions> -->
              </v-card>
            </template>
          </v-dialog>

          <!-- <img :src="item.image_m" alt="" /> -->
          <h3>{{ item.metadata[1].name }}</h3>
          <p>{{ item.metadata[1].desc }}</p>
          <div class="d-flex justify-end mt-3">
            <span class="text-gray"
              >{{
                moment(`${item.create_time}`).format("YYYY-MM-DD")
              }}｜點閱次數：{{ item.use_count }}</span
            >
          </div>
        </v-col>
      </v-row>

      <v-pagination
        v-model="imediaCurrentPage"
        class="mt-16"
        :length="imediaTotalPages"
      ></v-pagination>
    </v-col>
    <!-- <v-col sm="10" cols="12">
      <v-row class="video-list">
        <v-col
          cols="12"
          md="6"
          v-for="(item, index) in videoData"
          :key="index"
          class="mb-5 mb-md-0"
        >
          <video controls class="w-100">
            <source :src="item.video" type="video/mp4" />
            <a :href="item.video"></a>
          </video>
          <h3>{{ item.title }}</h3>
          <p>{{ item.introduction }}</p>
          <div class="d-flex justify-end mt-3">
            <span class="text-gray"
              >{{ item.date }}｜點閱次數：{{ item.ctr }}</span
            >
          </div>
        </v-col>
      </v-row>
    </v-col> -->
  </v-row>

  <div
    ref="listLocation"
    class="d-flex flex-column flex-sm-row align-center justify-space-between"
  >
    <h2 class="title">{{ t("online_experience_courses") }}</h2>
    <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>

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

          <!-- <div class="main-card">
            <a :href="item.video_url" target="_blank">
              <section class="card-title">
                <h3>{{ item.title }}</h3>
              </section>
            </a>

            <a :href="item.video_url" target="_blank">
              <div class="card-info">
                <ul>
                  <li class="d-flex align-center">
                    <p class="mb-0 ms-3">分類： {{ item.category }}</p>
                  </li>
                  <li class="d-flex align-center">
                    <p class="mb-0 ms-3">來源： {{ item.content }}</p>
                  </li>
                </ul>
              </div>
            </a>
          </div> -->
        </v-col>
      </v-row>
    </v-col>
  </v-row>

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

  <span class="text-gray total-item"
    >{{ t("total_count") }}：{{ totalNum }}</span
  >
</template>

<style lang="scss" scoped>
.v-input {
  @media (max-width: 600px) {
    max-width: 15.625em;
    margin: auto;
    margin-top: -1.25em;
  }
}

.btn-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(6.875em, max-content));
  justify-content: center;
  padding: initial;

  li {
    list-style-type: none;
  }

  .v-btn {
    width: 6.25em;
    color: var(--purple);
    border-color: var(--purple);
    @media (max-width: 600px) {
      width: 9.375em;
    }

    &:hover {
      color: #fff;
      background-color: var(--purple);
    }

    &:hover > .v-btn__overlay {
      opacity: 0;
    }
  }

  .active {
    color: #fff;
    background-color: var(--purple);
  }
}
.video-list {
  h3 {
    margin: 0.5em 0 0.3em;
    font-size: 1.125em;
    font-weight: 500;
  }
  p {
    // 超過兩行則省略
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    line-break: after-white-space;
  }
  h3,
  p,
  span {
    line-height: 1.5em;
    letter-spacing: 0.0625em;
  }
  span {
    font-size: 0.875em;
  }

  img {
    cursor: pointer;
  }

  .img-box {
    overflow: hidden;
    border-radius: 20px;
    .v-img {
      height: 225px;
      width: 100%;
      object-fit: cover;
      border-radius: 20px;
      transition: all 0.5s;
      cursor: pointer;

      @media (max-width: 1200px) {
        height: 160px;
      }

      @media (max-width: 960px) {
        height: 32vw;
      }

      @media (max-width: 600px) {
        height: 37vw;
      }

      &:hover {
        transform: scale(1.1);
      }
    }
  }
}

video {
  border-radius: 1.25em;
}

.video-dialog {
  h3 {
    font-size: 1.25em;
    font-weight: 500;
    letter-spacing: 1px;
  }

  .close-btn {
    .v-icon {
      transition: all 0.2s;

      &:hover {
        opacity: 0.5 !important;
      }
    }
  }

  .video-box {
    position: relative;
    padding-bottom: 56.5%;
    overflow: hidden;
    video {
      position: absolute;
      top: 0;
      left: 0;
      width: 100% !important;
      height: 100% !important;
    }
  }
}
</style>
