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

const { t } = useI18n();
const store = useMainStore();
const vlogVideo = ref(null);
const canvas = ref(null);
const photo = ref(null);
let showVideo = ref(true);

const emit = defineEmits(["closeDialog"]);

// 關閉父組件的 funFilterDialog
function closeDialog() {
  emit("closeDialog");
}

onMounted(() => {
  // 請求使用者的攝影機
  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then((stream) => {
      vlogVideo.value.srcObject = stream;
    })
    .catch((error) => {
      console.error("無法開啟攝影機", error);
    });
});

let loading = ref(false);
let havePhoto = ref(false); // 拍照完成
let isCompleted = ref(false); // 照片確認
let countdown = ref(0);

// 倒數五秒拍攝
function startCountdown() {
  countdown.value = 5;
  loading.value = true;

  const interval = setInterval(() => {
    countdown.value -= 1;
    if (countdown.value === 0) {
      clearInterval(interval);
      takePhoto();
    }
  }, 1000);
}

startCountdown();

let photoFile = ref(null);

// 拍攝照片
const takePhoto = () => {
  const context = canvas.value.getContext("2d");
  canvas.value.width = vlogVideo.value.videoWidth;
  canvas.value.height = vlogVideo.value.videoHeight;
  context.drawImage(
    vlogVideo.value,
    0,
    0,
    vlogVideo.value.videoWidth,
    vlogVideo.value.videoHeight
  );

  // 將畫布轉換成 base64 格式的 JPG 照片，不調整畫質
  photo.value = canvas.value.toDataURL("image/jpeg"); // 不設置壓縮品質

  if (photo.value) {
    showVideo.value = false;

    // 將 base64 轉換成 Blob
    const photoBlob = dataURLtoBlob(photo.value);

    // 將 Blob 轉換成 File
    photoFile.value = blobToFile(photoBlob, "photo.jpg"); // 設定檔案名稱為 JPG 格式

    havePhoto.value = true;
    loading.value = false;
  }
};

// 重新拍攝
function reshoot() {
  // 清空照片和檔案資料
  photo.value = null;
  photoFile.value = null;

  // 顯示影片重新準備拍攝
  showVideo.value = true;
  havePhoto.value = false;
  loading.value = false;

  startCountdown();

  console.log("重新拍攝，重設狀態");
}

// base64 轉 Blob
function dataURLtoBlob(dataURL) {
  const byteString = atob(dataURL.split(",")[1]);
  const mimeString = dataURL.split(",")[0].split(":")[1].split(";")[0];
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
}

// Blob 轉 File
function blobToFile(blob, fileName) {
  return new File([blob], fileName, { type: blob.type });
}

let swapVideo = ref(null);
let swapVideoSrc = ref(null);
let form = ref(false);
let email = ref(null);
let formLoading = ref(false);
let showAlert = ref(false);
const required = (v) => {
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailPattern.test(v) || "請輸入有效的 email 格式";
};

async function onSubmit() {
  formLoading.value = true;

  let url = `https://cmm.ai/postcard/fs/swap-face-video/${store.assignGender}?email_to=${email.value}`;

  const formData = new FormData();
  formData.append("file", photoFile.value);

  console.log("url", url);
  try {
    const response = await axios.post(url, formData);
    console.log("換臉影片 response", response);

    if (response.data === "OK") {
      showAlert.value = true;

      setTimeout(() => {
        showAlert.value = false;
        closeDialog();
      }, 3000);
    }

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

let isUploading = ref(false);
let imageUrl = ref(null); // 圖片網址

// 上傳
async function upload() {
  isUploading.value = true;
  let url = `https://cmm.ai/postcard/fs/swap-face-capture/${store.assignGender}`;

  const formData = new FormData();
  formData.append("file", photoFile.value);

  console.log("url", url);
  try {
    const response = await axios.post(url, formData);
    console.log("換臉影片 response", response);

    if (response.status === 200) {
      isUploading.value = false;
      isCompleted.value = true;

      console.log("response.data", response.data);

      const filePath = response.data;
      const fileName = filePath.match(/results\/(.+)$/)[1];
      console.log("fileName", fileName);

      imageUrl.value = `https://cmm.ai/postcard/fs/result-image/${fileName}`;
    }
  } catch (error) {
    console.log("error", error);
  }
}
</script>

<template>
  <div
    v-if="store.funFilterDialog"
    class="d-flex flex-column align-center justify-center"
  >
    <video v-show="showVideo" ref="vlogVideo" autoplay playsinline></video>

    <div
      v-if="photo && !isCompleted && !isUploading"
      class="w-100 d-flex flex-column align-center"
    >
      <img :src="photo" alt="captured image" class="captured-img" />

      <p class="prompt-text">
        {{ t("remove_mask_result") }}
      </p>

      <div class="d-flex mt-10">
        <v-btn variant="tonal" @click="reshoot()" class="me-5">
          {{ t("retake") }}
        </v-btn>
        <v-btn
          @click="upload()"
          color="primary"
          variant="elevated"
          :loading="isUploading"
        >
          {{ t("confirm") }}
        </v-btn>
      </div>
    </div>

    <video v-show="swapVideoSrc" ref="swapVideo" preload playsinline>
      <source :src="swapVideoSrc" type="video/mp4" />
    </video>

    <!-- 倒數計時動畫 -->
    <div v-if="countdown > 0" class="countdown">{{ countdown }}</div>

    <v-progress-circular
      v-else-if="loading"
      :size="50"
      color="primary"
      indeterminate
    ></v-progress-circular>

    <div
      class="d-flex flex-column align-center justify-center"
      v-if="isUploading"
    >
      <v-progress-circular
        :size="100"
        color="primary"
        indeterminate
        class="my-10"
      ></v-progress-circular>

      <p class="mb-10 text-center">{{ t("postcard_being_created") }}</p>
    </div>

    <div
      v-if="isCompleted && imageUrl"
      class="my-10 d-flex flex-column align-center justify-center"
    >
      <img :src="imageUrl" alt="" class="w-100" style="object-fit: contain" />
      <p class="mt-5 font-weight-bold">
        {{ t("qrcode_save_image") }}
      </p>
    </div>

    <canvas ref="canvas" style="display: none"></canvas>
  </div>
</template>

<style lang="scss" scoped>
.captured-img {
  width: 65vw;
  max-height: 220px;
  margin: 1rem auto;
  object-fit: contain;
}

video {
  width: 100%;
  height: auto;
  margin: 1rem auto;
  object-fit: cover;
}

button {
  margin: auto;
  padding: 1.2rem 2rem;
  display: flex;
  justify-content: center;
  border-radius: 5px;
  letter-spacing: 3px;
  font-size: 1rem;
}

.countdown {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 4em;
  font-weight: bold;
  color: #fff;
}

.result {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 50%;
  }
}

.form-content {
  width: 100%;
  max-width: 500px;
  margin-bottom: 1.5rem;

  p {
    line-height: 2;
    letter-spacing: 1px;
  }
}

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

  .v-alert {
    width: 500px;
    padding: 1rem;

    .v-alert-title {
      margin-bottom: 0.5rem;
    }
  }
}

.prompt-text {
  color: #939393;
}
</style>
