<script setup>
import { ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { useMainStore } from "@/stores/store";
import axios from "axios";
import QrcodeVue from "qrcode.vue";
import Footer from "../components/Footer.vue";

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

// 使用者點擊分享時帶入的資訊
const shareData = {
  url: store.imgPath, // 要分享的 URL
  title: "101", // 標題
  text: "AI明信片", // 文字內容
};

const imageUrl = ref("");

// 儲存圖片
const downloadImage = async (url) => {
  try {
    const response = await axios({
      url: url,
      method: "GET",
      responseType: "blob",
    });

    imageUrl.value = URL.createObjectURL(new Blob([response.data]));

    saveImage();
  } catch (error) {
    console.error("Error downloading the image:", error);
  }
};

const saveImage = () => {
  const a = document.createElement("a");
  a.href = imageUrl.value;
  a.download = "101-AI-Postcard.jpg"; // 檔案名稱
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

async function share() {
  try {
    // 使用 Web Share API
    await navigator.share(shareData);
  } catch (err) {
    // 使用者拒絕分享或發生錯誤
    const { name, message } = err;
    if (name === "AbortError") {
      alert("您已取消分享此相片");
    } else {
      alert(err);
    }
  }
}

let dialog = ref(false);
let randomUrl = ref(""); // 館外店家連結
let randomStoreName = ref(""); // 館外店家名稱

// 取得隨機館外店家
async function getBrand() {
  let url =
    "https://cmm.ai:9101/find_brand?keyword=%E9%A4%A8%E5%A4%96&language=ch";

  try {
    let response = await axios.get(url);
    console.log("getBrand", response);

    const randomItem =
      response.data.data[Math.floor(Math.random() * response.data.data.length)];

    randomUrl.value = randomItem.info.url;
    randomStoreName.value = randomItem.info.name;

    setPostcardLog();
  } catch (error) {
    console.log("error", error);
  }
}

getBrand();

// 儲存 Log
async function setPostcardLog() {
  let url = `https://cmm.ai:9101/ai-postcard-log/`;

  const formData = new FormData();
  formData.append("url", randomUrl.value);
  formData.append("file", store.imgFile);
  formData.append("store_name", randomStoreName.value);

  try {
    let response = await axios.post(url, formData);
    console.log("setPostcardLog", response);
  } catch (error) {
    console.log("error", error);
  }
}

// 判斷語言更改圖片
const couponImgSrc = ref("../src/assets/img/coupon.png"); // 預設圖片

onMounted(() => {
  const lang = localStorage.getItem("lang");

  if (lang === "zh-tw") {
    couponImgSrc.value = "../src/assets/img/coupon_ch.png";
  } else if (lang === "en-us") {
    couponImgSrc.value = "../src/assets/img/coupon_en.png";
  } else if (lang === "ja-jp") {
    couponImgSrc.value = "../src/assets/img/coupon_jp.png";
  } else if (lang === "ko-kr") {
    couponImgSrc.value = "../src/assets/img/coupon_kr.png";
  }
});
</script>

<template>
  <div class="content main-bg">
    <v-container class="px-5 px-sm-15 d-flex flex-column align-center">
      <div id="result" class="mb-10 img-item">
        <img
          id="imageElement"
          ref="imageElement"
          class="w-100"
          :src="store.imgPath"
          alt=""
        />

        <!-- <p>{{ store.assignBgImgTitle }}</p> -->
      </div>

      <!-- <p
        class="text-start px-5 description"
        v-html="t(store.assignBgImg.description)"
      ></p> -->

      <!-- <button @click="share()" class="main-btn mt-15">分享相片</button> -->

      <div class="d-flex flex-column mt-10">
        <button @click="downloadImage(store.imgPath)" class="main-btn mb-7">
          {{ t("save_photo") }}
        </button>

        <!-- <a :href="randomUrl" target="_blank" class="main-btn">
          {{ t("get_coupon") }}
        </a> -->

        <button @click="dialog = true" class="main-btn">
          {{ t("get_coupon") }}
        </button>

        <v-dialog v-model="dialog" width="auto">
          <v-card max-width="400">
            <v-card-title class="pa-6">
              {{ randomStoreName }} <br />
              {{ t("5G_event") }}
            </v-card-title>

            <v-card-text class="pt-0">
              <div class="coupon">
                <img class="bg-img" :src="couponImgSrc" alt="" />
                <!-- <img class="bg-img" src="../assets/img/coupon.png" alt="" /> -->

                <img class="result-img" :src="store.imgPath" alt="" />

                <span class="qrcode">
                  <qrcode-vue :value="randomUrl" size="100" level="H" />
                </span>
              </div>
            </v-card-text>
            <template v-slot:actions>
              <v-btn
                class="ms-auto"
                text="關閉"
                @click="dialog = false"
              ></v-btn>
            </template>
          </v-card>
        </v-dialog>
      </div>

      <v-dialog v-if="store.assignBgImgTitle === '南投日月潭'" max-width="300">
        <template v-slot:activator="{ props: activatorProps }">
          <button v-bind="activatorProps" class="main-btn mt-7">
            {{ t("ticket_purchase") }}
          </button>
        </template>

        <template v-slot:default="{ isActive }">
          <v-card class="pa-2">
            <v-card-title class="pa-5">
              {{ t("purchase_link") }}
            </v-card-title>

            <v-card-text>
              <a
                href="https://nantou.welcometw.com/tour/kwOz"
                target="_blank"
                class="d-block mb-5"
              >
                1.【日月潭C好行款】<br />
                <small>南投日月潭來回車票(電子票證)+船+纜車+遊湖巴士</small>
              </a>

              <a href="https://nantou.welcometw.com/tour/KNez" target="_blank">
                2.【日月潭D暢遊款】<br />
                <small>南投日月潭來回車票(電子票證)+船+九族+遊湖巴士</small>
              </a>
            </v-card-text>

            <v-card-actions>
              <v-spacer></v-spacer>

              <v-btn text="Close" @click="isActive.value = false"></v-btn>
            </v-card-actions>
          </v-card>
        </template>
      </v-dialog>
    </v-container>
    <Footer url="/step6" />
  </div>
</template>

<style lang="scss" scoped>
.content {
  padding: 8rem 0 8rem;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .img-item {
    img {
      border: 8px solid transparent;
      border-image: linear-gradient(
          to right,
          rgba(138, 160, 172, 0.75),
          rgba(165, 142, 116, 0.75),
          rgba(128, 108, 87, 0.75)
        )
        1;
    }

    p {
      padding: 8px;
      margin-top: -5px;
      color: white;
      text-shadow: none;
      background-color: var(--main-color);
    }
  }
}

a {
  color: white;
  text-decoration: none;
}

.coupon {
  position: relative;
  .bg-img {
    width: 100%;
    position: relative;
    z-index: 100;
  }

  .result-img {
    width: 100%;
    position: absolute;
    left: 0;
  }

  .qrcode {
    position: absolute;
    right: 5vw;
    bottom: 5vw;
    z-index: 100;
  }
}

.v-card-title {
  letter-spacing: 1px;
}
</style>
