<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 race = store.assignRace; // 種族
let gender = store.assignGender; // 性別
let imgLoading = ref(false);
let parameter = ref([]);

onMounted(() => {
  getLandmark();
  getTargetImageList();
  // getParameters();
});

// 取得背景清單
async function getTargetImageList() {
  imgLoading.value = true;
  let url = `https://cmm.ai/postcard/fs/target-image-list/${gender}/${race}`;

  try {
    let response = await axios.get(url);
    console.log("取得背景清單", response);

    let imagePromises = response.data.map((item, index) => {
      let imageUrl = `https://cmm.ai/postcard/fs/target-image/${gender}/${race}/${item}`;
      return getTargetImage(imageUrl, index); // 取得種族圖片
    });

    await Promise.all(imagePromises);

    // 依照檔名進行排序 (0-9)
    parameter.value.sort((a, b) => {
      const aNum = parseInt(a.name);
      const bNum = parseInt(b.name);
      return aNum - bNum;
    });

    landmarkNames.value.map((item, index) => {
      if (item === "台中日月潭") {
        return (landmarkNames.value[index] = "南投日月潭");
      }
    });

    // 組合陣列
    parameter.value = parameter.value.map((item, index) => ({
      imgUrl: item.imgUrl,
      name: `${index}.jpg`,
      title: landmarkNames.value[index],
    }));

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

const landmarkNames = ref([]);

// 取得景點名稱
async function getLandmark() {
  let url = "https://cmm.ai/postcard/fslandmark-order";

  try {
    let response = await axios.get(url);
    landmarkNames.value = response.data;
  } catch (error) {
    console.log("error", error);
  }
}

// 取得背景圖片
async function getTargetImage(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, name: `${index}.jpg` });
  } catch (error) {
    console.log("error", error);
  }
}

function handleBgImg(item) {
  store.assignBgImg = item.name;
  store.assignBgImgUrl = item.imgUrl;
  store.assignBgImgTitle = item.title;
}

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 parameterList = ref([]);

// 背景清單
// let parameter = ref([
//   {
//     bg_img: "臺北陽明山-母親節.png",
//     title: "taipei_yangmingshan",
//     description: "taipei_yangmingshan_description",
//   },
//   {
//     bg_img: "台南孔廟.png",
//     title: "tainan_confucius_temple",
//     description: "tainan_confucius_temple_description",
//   },
//   {
//     bg_img: "臺北中正紀念堂-2.png",
//     title: "taipei_chiang_kai_shek_memorial_hall_2",
//     description: "taipei_chiang_kai_shek_memorial_hall_2_description",
//   },
//   {
//     bg_img: "台東嘉明湖.png",
//     title: "taitung_jiaming_lake",
//     description: "taitung_jiaming_lake_description",
//   },
//   {
//     bg_img: "中秋節.png",
//     title: "mid_autumn_festival",
//     description: "mid_autumn_festival_description",
//   },
//   {
//     bg_img: "新北野柳女王頭.png",
//     title: "new_taipei_yehliu_queen_head",
//     description: "new_taipei_yehliu_queen_head_description",
//   },
//   {
//     bg_img: "基隆和平島公園.png",
//     title: "keelung_heping_island_park",
//     description: "keelung_heping_island_park_description",
//   },
//   {
//     bg_img: "南投日月潭.png",
//     title: "taichung_sun_moon_lake",
//     description: "taichung_sun_moon_lake_description",
//   },
//   {
//     bg_img: "臺北中正紀念堂.png",
//     title: "taipei_chiang_kai_shek_memorial_hall",
//     description: "taipei_chiang_kai_shek_memorial_hall_description",
//   },
//   {
//     bg_img: "台南鹽田.png",
//     title: "tainan_salt_field",
//     description: "tainan_salt_field_description",
//   },
//   {
//     bg_img: "高雄美麗島.png",
//     title: "kaohsiung_formosa_boulevard_station",
//     description: "kaohsiung_formosa_boulevard_station_description",
//   },
//   {
//     bg_img: "新北十分瀑布.png",
//     title: "new_taipei_shifen_waterfall",
//     description: "new_taipei_shifen_waterfall_description",
//   },
//   {
//     bg_img: "臺北故宮.png",
//     title: "taipei_national_palace_museum",
//     description: "taipei_national_palace_museum_description",
//   },
//   {
//     bg_img: "臺北故宮-2.png",
//     title: "taipei_national_palace_museum_2",
//     description: "taipei_national_palace_museum_2_description",
//   },
//   {
//     bg_img: "台中歌劇院.png",
//     title: "national_taichung_theater",
//     description: "national_taichung_theater_description",
//   },
//   {
//     bg_img: "嘉義森林之歌.png",
//     title: "chiayi_song_of_forest",
//     description: "chiayi_song_of_forest_description",
//   },
//   {
//     bg_img: "基隆八斗子鐵路.png",
//     title: "keelung_baduzi_railway",
//     description: "keelung_baduzi_railway_description",
//   },
//   {
//     bg_img: "花蓮清水斷崖.png",
//     title: "hualien_qingshui_cliff",
//     description: "hualien_qingshui_cliff_description",
//   },
//   {
//     bg_img: "澎湖.png",
//     title: "penghu",
//     description: "penghu_description",
//   },
//   {
//     bg_img: "南投清境農場.png",
//     title: "nantou_qingjing_farm",
//     description: "nantou_qingjing_farm_description",
//   },
//   {
//     bg_img: "高雄流行音樂中心.png",
//     title: "kaohsiung_music_center",
//     description: "kaohsiung_music_center_description",
//   },
//   {
//     bg_img: "花蓮金針花山.png",
//     title: "hualien_daylily_mountain",
//     description: "hualien_daylily_mountain_description",
//   },
//   {
//     bg_img: "新北九份老街.png",
//     title: "new_taipei_jiufen_old_street",
//     description: "new_taipei_jiufen_old_street_description",
//   },
//   {
//     bg_img: "嘉義阿里山小火車.png",
//     title: "chiayi_alishan_forest_railways",
//     description: "chiayi_alishan_forest_railways_description",
//   },
//   {
//     bg_img: "台中高美濕地.png",
//     title: "taichung_gaomei_wetland",
//     description: "taichung_gaomei_wetland_description",
//   },
// ]);

// console.log("parameter", parameter.value);

async function getParameters() {
  let url = `${apiUrl}/sd/parameters`;

  try {
    let response = await axios.get(url);
    parameterList.value = response.data;
  } catch (error) {
    console.log("error", error);
  }
}

let alertShow = ref(false);

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

<template>
  <div class="content">
    <p class="title">{{ t("postcard.step2.text_2") }}</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)"
        v-for="item in currentPhotos"
        class="bg-img"
      >
        <!-- <v-img
          cover
          class="cover"
          :lazy-src="`https://cmm.ai/postcard/static/assets/img/bg/${item.bg_img}`"
          :src="`https://cmm.ai/postcard/static/assets/img/bg/${item.bg_img}`"
        >
          <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> -->

        <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>

        <!-- <p>{{ item.title }}</p> -->

        <img
          v-if="item.name === store.assignBgImg"
          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>

      <a @click="checkImg()" href="javascript:;" class="main-btn">
        {{ t("next_step") }}
      </a>

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

    <Footer url="/step3" />
  </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: 75vw;
      height: 50vw;
      object-fit: cover;
    }
  }

  p {
    margin-top: 0.5rem;
  }

  .icon {
    width: 3.5rem;
    position: absolute;
    top: 0.1rem;
    right: 0.1rem;
  }
}

.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;
  }
}

.alert-item {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  .v-alert {
    background-color: var(--sub-color);
  }

  .text-warning {
    color: var(--main-color) !important;
  }
}
</style>
