<script setup>
import { ref, computed, onMounted } from "vue";
import { useMainStore } from "@/stores/store";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import "animate.css";
import axios from "axios";
import Footer from "../components/Footer.vue";

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

const apiUrl = import.meta.env.VITE_API_URL;
const imgUrl = import.meta.env.VITE_API_IMG_URL;

let parameter = ref([]);
let imgLoading = ref(false);

onMounted(() => {
  getIconImageList(store.assignGender);
});

// 取得種族清單
async function getIconImageList(gender) {
  imgLoading.value = true;
  let url = `https://cmm.ai/postcard/fs/icon-image-list/${gender}`;

  try {
    let response = await axios.get(url);
    let imagePromises = response.data.map((item, index) => {
      let imageUrl = `https://cmm.ai/postcard/fs/icon-image/${gender}/${item}`;
      return getIconImage(imageUrl, index); // 取得種族圖片
    });

    await Promise.all(imagePromises);

    imgLoading.value = false;
  } catch (error) {
    console.log("error", error);
  }
}

// 取得種族圖片
async function getIconImage(url, index) {
  try {
    // 設定 responseType 為 arraybuffer 以取得二進位數據
    let response = await axios.get(url, { responseType: "arraybuffer" });

    let blob = new Blob([response.data], { type: "image/png" }); // 創建 blob
    let imageUrl = URL.createObjectURL(blob); // 創建圖片 URL
    parameter.value.push({ imgUrl: imageUrl, race: `${index}` });
  } catch (error) {
    console.log("error", error);
  }
}

const currentPhotos = computed(() => {
  const start = currentIndex.value;
  const end = start + perPage.value;
  return parameter.value.slice(start, end);
});

let currentIndex = ref(0);
let perPage = ref(2);

function prev() {
  if (currentIndex.value > 0) {
    currentIndex.value -= perPage.value;
  }
}

function next() {
  if (currentIndex.value + perPage.value < parameter.value.length) {
    currentIndex.value += perPage.value;
  }
}

// 計算頁數
const totalPages = computed(() =>
  Math.ceil(parameter.value.length / perPage.value)
);

const currentPage = computed(
  () => Math.floor(currentIndex.value / perPage.value) + 1
);

let alertShow = ref(false);

function checkImg() {
  if (store.assignRace && store.assignRace !== "") {
    alertShow.value = false;
    router.push("/step4");
  } else {
    alertShow.value = true;
    setTimeout(() => {
      alertShow.value = false;
    }, 2000);
  }
}

function handleBgImg(race) {
  store.assignRace = race;
}
</script>

<template>
  <div class="content">
    <p class="title">{{ t("select_person") }}</p>

    <div
      v-if="imgLoading"
      class="d-flex flex-column align-center justify-center pt-15"
    >
      <v-progress-circular
        :size="70"
        :width="7"
        color="white"
        indeterminate
      ></v-progress-circular>
    </div>

    <div v-else class="img-content">
      <div class="slider-btn">
        <button class="prev" @click="prev">
          <img class="arrow" src="../assets/img/arrow_l.png" alt="" />
        </button>
        <button class="next" @click="next">
          <img class="arrow" src="../assets/img/arrow_r.png" alt="" />
        </button>
      </div>

      <div
        @click="handleBgImg(item.race)"
        v-for="item in currentPhotos"
        class="bg-img"
      >
        <v-img cover class="cover" :lazy-src="item.imgUrl" :src="item.imgUrl">
          <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>

        <img
          v-if="item.race === store.assignRace && store.assignRace !== ''"
          class="icon active"
          src="../assets/img/confirm-2.png"
          alt=""
        />
        <img v-else class="icon" src="../assets/img/confirm-solid.png" alt="" />
      </div>

      <span class="page-num">{{ currentPage }} ／ {{ totalPages }}</span>

      <button @click="checkImg()" class="main-btn">
        {{ t("next_step") }}
      </button>

      <div v-if="alertShow" class="alert-item">
        <v-alert border="top" type="warning" variant="outlined" class="mt-5">
          尚未選擇
        </v-alert>
      </div>
    </div>

    <Footer url="/step2" />
  </div>
</template>

<style lang="scss" scoped>
.img-content {
  // height: 80vh;
  padding: 0 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;

  @media (max-width: 600px) {
    height: 100%;
    padding: 0 4rem;
  }

  .bg-img {
    margin-bottom: 2rem;
    cursor: pointer;
    position: relative;

    .cover {
      max-width: 100%;
      width: 14rem;
      object-fit: cover;
    }
  }

  p {
    margin-top: 0.5rem;
  }

  .icon {
    width: 3.9rem;
    position: absolute;
    top: -1rem;
    right: -2.5rem;
  }
}

.slider-btn {
  width: 100%;
  position: absolute;
  z-index: 100;
  top: 50vh;

  img {
    width: 100px;
    transition: all 0.2s;

    @media (max-width: 600px) {
      width: 50px;
    }
  }

  .prev,
  .next {
    position: absolute;
    cursor: pointer;
    border: none;
    background-color: transparent;

    &:hover {
      img {
        opacity: 0.7;
      }
    }
  }

  .prev {
    left: 0;
  }

  .next {
    right: 0;
  }
}

.page-num {
  margin: auto auto 2.2rem;
  color: white;
  letter-spacing: 0.2rem;
}

.content {
  @media (max-width: 600px) {
    min-height: 100vh;
  }
}
</style>
