<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);
// let imgUrl = ref(null); // 明信片圖
// const required = (v) => !!v || "請輸入您的 email";
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;

  // isCompleted.value = true;
  if (!photoFile.value) {
    return;
  }

  store.imgPath = "";
  loading.value = true;

  let url = `https://cmm.ai/postcard/fs/swap-face/${store.assignGender}/${store.assignRace}/${store.assignBgImg}`;

  // 人物圖
  const formData = new FormData();
  formData.append("file", photoFile.value);

  try {
    let response = await axios.post(url, formData);
    console.log("runImg", response);

    if (response.status === 200) {
      isUploading.value = false;
      isCompleted.value = true;
      // store.imgPath = response.data[0].path;

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

      imageUrl.value = `https://cmm.ai/postcard/fs/result-image/${fileName}`;

      // 圖檔轉網址
      // let blob = new Blob([response.data], { type: "image/png" }); // 創建 blob
      // let imageUrl = URL.createObjectURL(blob); // 創建圖片 URL
      // store.imgFile = blob; // 圖片檔案
      // store.imgPath = imageUrl; // 圖片網址
      // loading.value = false;
      // alert("完成");
      // router.push("/step7");
    }
  } catch (error) {
    console.log("error", error);
  }
}

let vlogEmail = ref("");
let vlogLoading = ref(false);
let showVlogAlert = ref(false);
let emailError = ref(false);

// 取得 vlog
async function getVlog() {
  console.log("getVlog");
  console.log("vlogEmail", vlogEmail.value);

  vlogLoading.value = true;

  // isCompleted.value = true;
  // if (!photoFile.value) {
  //   return;
  // }

  // store.imgPath = "";
  // loading.value = true;

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

  // 人物圖
  const formData = new FormData();
  formData.append("file", photoFile.value);

  try {
    let response = await axios.post(url, formData);

    vlogLoading.value = false;
    console.log("取得 vlog", response);

    if (response.data === "OK") {
      alert(`${t("vlog.submit_success")}！${t("vlog.processing_message")}`);
      // showVlogAlert.value = true;

      // setTimeout(() => {
      //   showVlogAlert.value = false;
      // }, 5000);
    }
  } catch (error) {
    console.log("error", error);
  }
}

// 驗證 email 格式
function validateAndSubmit() {
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailPattern.test(vlogEmail.value)) {
    emailError.value = true;
    return;
  }
  emailError.value = false;

  getVlog();
}
</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 @click="reshoot()" class="me-5" variant="tonal">
          {{ t("retake") }}
        </v-btn>
        <v-btn @click="upload()" color="primary" variant="elevated">
          {{ 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>

    <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 position-relative">
      <div class="d-flex justify-center">
        <img :src="imageUrl" alt="" class="w-100" style="object-fit: contain" />

        <!-- <span class="ms-15 d-flex flex-column align-center justify-center">
          <p class="mb-10 text-h5 font-weight-bold">
            {{ t("qrcode_save_image") }}
          </p>

          <qrcode-vue :value="imageUrl" class="mb-2" size="300" level="H" />
        </span> -->
      </div>

      <div class="vlog-item">
        <h4>
          <span>{{ t("vlog.input_email") }}</span>
        </h4>
        <p>
          {{ t("vlog.description") }}
        </p>

        <v-text-field
          v-model="vlogEmail"
          :label="t('vlog.enter_email')"
          variant="solo"
          :error-messages="emailError ? [`${t('vlog.invalid_email')}`] : []"
        ></v-text-field>
        <v-btn
          @click="validateAndSubmit()"
          :loading="vlogLoading"
          color="primary"
          type="submit"
          variant="elevated"
          block
        >
          {{ t("submit") }}
        </v-btn>
      </div>

      <v-alert
        v-show="showVlogAlert"
        class="vlog-alert"
        :text="t('vlog.processing_message')"
        :title="t('vlog.submit_success')"
        type="success"
      ></v-alert>
    </div>

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

    <!-- <div v-if="isCompleted" class="form-content">
      <div
        v-if="loading"
        class="d-flex flex-column align-center justify-center py-15"
      >
        <v-progress-circular
          :size="70"
          :width="7"
          color="primary"
          indeterminate
        ></v-progress-circular>
      </div>

      <div v-else></div>

      <p class="mb-10 text-center">
        拍攝完成！<br />
        請提供您的電子郵件以取得影片
        <br />影片約 1-2 分鐘後將傳送至您的信箱<br />
      </p>

      <v-form v-model="form" @submit.prevent="onSubmit">
        <v-text-field
          v-model="email"
          :rules="[required]"
          variant="solo"
          class="mb-2"
          label="email"
          clearable
        ></v-text-field>

        <br />

        <v-btn
          :disabled="!form"
          :loading="formLoading"
          color="primary"
          size="large"
          type="submit"
          variant="elevated"
          block
        >
          送出
        </v-btn>
      </v-form>
    </div> -->

    <!-- <div v-if="showAlert" class="alert-item">
      <v-alert
        density="compact"
        text="您的 vlog 影片已為您寄送，如尚未收到請耐心等候"
        title="送出成功！"
        type="success"
      ></v-alert>
    </div> -->

    <!-- <div v-if="havePhoto" class="d-flex flex-column align-center">
      <p class="text-center">拍照完成！<br />請掃描以下 QR Code 取得影片</p>
      <img src="../assets/img/video-results.png" alt="" />
    </div> -->

    <!-- <button>
      <span v-if="countdown > 0">拍照倒數 {{ countdown }} 秒</span>
      <span v-else class="text-center"
        >製作影片中，請稍候…</span
      >
    </button> -->

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

<style lang="scss" scoped>
.captured-img {
  max-width: 100%;
  margin: 1rem auto;
}

video {
  width: 100%;
  max-width: 750px;
  height: auto;
  margin: 1rem auto;
}

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: 100%;
    padding: 1rem;

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

.prompt-text {
  color: #939393;
}

.vlog-item {
  .v-input {
    margin: 1.5rem auto 1rem;
  }

  h4 {
    position: relative;
    text-align: center;
    margin: 3rem auto 1rem;
    color: var(--main-color);
    letter-spacing: 2px;

    span {
      display: inline-block;
      font-weight: 600;
      font-size: 1rem;
      background-color: #fff;
    }
  }

  h4::before,
  h4::after {
    content: "";
    position: absolute;
    z-index: -1;
    top: 50%;
    width: 30%;
    height: 1px;
    background-color: var(--main-color);
  }

  h4::before {
    left: 0; /* 將左邊的線對齊到左側 */
  }

  h4::after {
    right: 0; /* 將右邊的線對齊到右側 */
  }
}

.vlog-alert {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
