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

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;

const isShowModal = ref(false);
const uploadInput = ref(null);
const pic = ref("");
const result = reactive({
  dataURL: "",
  // blobURL: "",
});

function selectFile(e) {
  pic.value = "";
  result.dataURL = "";
  // result.blobURL = "";

  // Get selected files
  const { files } = e.target;
  if (!files || !files.length) return;

  // Convert to dataURL and pass to the cropper component
  const file = files[0];
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    // Update the picture source of the `img` prop
    pic.value = String(reader.result);

    // Show the modal
    isShowModal.value = true;

    // Clear selected files of input element
    if (!uploadInput.value) return;
    uploadInput.value.value = "";
  };
}

async function getResult() {
  if (!cropper) return;
  const base64 = cropper.getDataURL();
  const blob = await cropper.getBlob();
  if (!blob) return;

  imgFile.value = await cropper.getFile({
    fileName: "fileName",
  });

  result.dataURL = base64;
  isShowModal.value = false;
}

// 清除
// function clear() {
//   if (!cropper) return;
//   cropper.clear();
// }

// 重置
function reset() {
  if (!cropper) return;
  cropper.reset();
}

// 重新上傳
function remove() {
  file.value = null;
  imgFile.value = null;
  // imageUrl.value = null;
  pic.value = "";
  result.dataURL = "";
}

let file = ref(null);
let imgFile = ref(null);
let imgLoading = ref(false);

let race = store.assignRace; // 種族
let gender = store.assignGender; // 性別
let bgImg = store.assignBgImg; // 背景

// 換臉
async function upload() {
  if (!imgFile.value) {
    return;
  }

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

  let url = `https://cmm.ai/postcard/fs/swap-face/${gender}/${race}/${bgImg}`;

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

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

    if (response.status === 200) {
      // store.imgPath = response.data[0].path;

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

const openUploadInput = () => {
  if (uploadInput.value) {
    uploadInput.value.click();
  }
};
</script>

<template>
  <div class="content main-bg">
    <v-container class="px-5 px-sm-15">
      <div
        v-if="imgLoading"
        class="d-flex flex-column align-center justify-center"
      >
        <p class="mb-15">
          {{ t("postcard.step5.text_1") }}<br />
          {{ t("postcard.step5.text_2") }}
        </p>

        <v-progress-circular
          :size="70"
          :width="7"
          color="white"
          indeterminate
        ></v-progress-circular>

        <p class="mt-15">{{ t("postcard.step5.text_3") }}</p>
      </div>

      <div v-else>
        <p class="title mb-5">{{ t("postcard.step5.text_4") }}</p>

        <div class="d-flex justify-center">
          <v-btn
            @click="openUploadInput"
            color="primary"
            variant="outlined"
            class="img-btn"
          >
            <span class="d-flex align-center">
              <v-icon icon="mdi-camera" class="me-3 pt-1"> </v-icon>
              <p>{{ t("postcard.step5.text_5") }}</p>
            </span>
          </v-btn>
        </div>

        <input
          class="d-none"
          ref="uploadInput"
          type="file"
          accept="image/jpg, image/jpeg, image/png"
          @change="selectFile"
        />

        <div v-if="isShowModal" class="mt-5">
          <!-- 尺寸 4:3 -->
          <VuePictureCropper
            :boxStyle="{
              width: '100%',
              height: '100%',
              backgroundColor: '#f8f8f8',
              margin: 'auto',
            }"
            :img="pic"
            :options="{
              viewMode: 1,
              dragMode: 'crop',
            }"
            :presetMode="{
              mode: 'fixedSize',
              width: 1920,
              height: 1080,
            }"
            @ready="ready"
          />

          <div class="mt-5 d-flex justify-end">
            <v-btn @click="reset" color="grey" variant="flat" class="me-3">
              {{ t("postcard.step5.text_6") }}
            </v-btn>

            <v-btn @click="getResult" color="primary" variant="flat">
              {{ t("postcard.step5.text_7") }}
            </v-btn>
          </div>
        </div>

        <!-- Crop result preview -->
        <section v-if="result.dataURL" class="section">
          <div
            class="preview-img mt-5"
            :style="`background-image: url('${result.dataURL}')`"
          >
            <!-- 圖片遮罩 -->
            <!-- <div
              class="mask"
              :style="`background-image: url('${result.dataURL}')`"
            ></div> -->
          </div>

          <!-- <p class="text-white mt-5">
            將人像放置於畫面右下角<br />會得到最好看的畫面唷！
          </p> -->
        </section>

        <!-- <v-file-input
          v-model="file"
          ref="fileInput"
          v-on:change="onFileChange()"
          label="選擇檔案"
          prepend-icon="mdi-camera"
          variant="filled"
          class="text-white"
        ></v-file-input>

        <div class="preview-img">
          <img class="w-100 mt-5" :src="imageUrl" alt="照片" v-if="imageUrl" />
        </div> -->

        <div class="btn-content">
          <button @click="remove()" class="main-btn">
            {{ t("postcard.step5.text_8") }}
          </button>
          <button @click="upload()" class="main-btn">{{ t("confirm") }}</button>
        </div>
      </div>

      <!-- <router-link to="/step6" class="main-btn">確定</router-link> -->
    </v-container>

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

<style lang="scss" scoped>
// .mdi-camera::before {
//   color: #fff !important;
// }

.img-btn {
  height: auto !important;
  padding: 10px 20px;
  font-size: 1rem;
  p {
    color: var(--btn-text-color);
  }
}

.preview-img {
  position: relative;
  width: 100%;
  height: 50vw;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: contain;

  // 隱藏遮罩
  // &::after {
  //   position: absolute;
  //   content: "";
  //   width: 100%;
  //   height: 100%;
  //   background-color: rgba(0, 0, 0, 0.7);
  //   z-index: 0;
  // }

  .mask {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 15;
    width: 100%;
    height: 50vw;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    -webkit-clip-path: inset(25% 0% 0% 45% round 0);
    clip-path: inset(25% 0% 0% 45% round 0);
    overflow: hidden; // safari
    filter: hue-rotate(0deg); // safari
    // clip-path: xywh(40% 25% 70% 75% round 0);
  }

  // img {
  //   width: 100%;
  //   height: 30vh;
  //   object-fit: cover;
  //   position: relative;
  // }
}

.content {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.btn-content {
  width: 100%;
  padding: 100px 10px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  // position: absolute;
  // left: 50%;
  // bottom: 20vw;
  // transform: translate(-50%, 0);

  .main-btn {
    margin: 10px;
  }
}

.test {
  width: 300px;
  height: 500px;
  object-fit: cover;
}

.cut {
  width: 500px;
  height: 500px;
  margin: 30px auto;
}
</style>
