<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import { useMainStore } from "@/stores/main";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const mainStore = useMainStore();
const valid = ref(true);
const file = ref();
const Form = ref();

let langOptions = reactive([
  {
    title: "中文",
    id: "zh-TW",
  },
  {
    title: "英文",
    id: "en",
  },
  {
    title: "印尼",
    id: "id",
  },
  {
    title: "越南",
    id: "vi",
  },
]);

let lang = ref("");
let loading = ref(false);
const zipFile = ref(); // 儲存 ZIP 檔案

async function submit() {
  console.log("lang", lang.value);
  console.log("file", file.value[0]);

  zipFile.value = null;
  loading.value = true;
  const response: any = await mainStore.zipTranslate(lang.value, file.value[0]);

  zipFile.value = new Blob([response[0].data], { type: "application/zip" });

  loading.value = false;

  console.log("response", response);
  console.log("zipFile.value", zipFile.value);
}

// ZIP 檔案下載
function downloadZipFile() {
  if (!zipFile.value) {
    console.error("沒有 ZIP 檔案可下載");
    return;
  }

  // 生成 Blob URL
  const url = URL.createObjectURL(zipFile.value);

  const link = document.createElement("a");
  link.href = url;
  link.download = "影片素材.zip"; // 設定下載檔名
  document.body.appendChild(link);

  link.click();
  document.body.removeChild(link);

  // 釋放 Blob URL
  URL.revokeObjectURL(url);
}
</script>

<template>
  <v-container fluid>
    <v-card class="ma-3 pa-3">
      <v-card-title primary-title>
        <h3 class="card-title mb-3">{{ t("zipTranslate") }}</h3>
      </v-card-title>
      <v-card-text>
        <v-form v-model="valid" ref="Form" class="d-flex">
          <v-file-input
            v-model="file"
            :rules="[(v) => v.length || 'select zip file.']"
            accept=".zip"
            :label="$t('fileInput')"
            prepend-icon="folder_zip"
          ></v-file-input>

          <v-select
            v-model="lang"
            label="語言"
            :items="langOptions"
            item-title="title"
            item-value="id"
            variant="solo"
            class="mx-5 lang-list"
            style="width: 100px"
            :rules="[(v) => v.length || '尚未選擇語言']"
          ></v-select>
        </v-form>
      </v-card-text>
    </v-card>

    <div class="ma-3 mt-5 pt-3">
      <v-btn
        @click="submit()"
        size="large"
        color="primary"
        variant="flat"
        class="w-100"
        :loading="loading"
        prepend-icon="translate_variant"
      >
        {{ t("translate") }}
      </v-btn>

      <v-btn
        v-if="zipFile"
        @click="downloadZipFile()"
        size="large"
        color="primary"
        variant="outlined"
        class="w-100 mt-5"
        prepend-icon="download"
      >
        {{ t("download") }}
      </v-btn>
    </div>
  </v-container>
</template>

<style lang="scss" scoped></style>
