<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { useMainStore } from "@/stores/main";
import { required } from "@/utils";
import { useI18n } from "vue-i18n";
import type { ImageDownload } from "@/interfaces";
import Dialog from "@/components/Dialog.vue";
import { wsUrl } from "@/env";

const WS = new WebSocket(`${wsUrl}/api/v1/images/sr`);
const mainStore = useMainStore();
const { t } = useI18n();
const valid = ref(true);
const Form = ref();
let imgFiles = ref();
let imgList: any[] = reactive([]);
let loading = ref(false);
let imgInput = ref(true);

watch(imgFiles, (newVal, oldVal) => {
  if (newVal) {
    if (!newVal.length) {
      imgInput.value = true;
    } else {
      imgInput.value = false;
    }
  }
});

// props
let dialog = reactive({
  msg: "圖片處理需要幾秒鐘的時間，敬請耐心等候",
  state: "info",
  show: false,
});

async function Submit() {
  WS.send("subscribe");
  loading.value = true;
  setTimeout(() => {
    dialog.show = true;
  }, 500);
  await mainStore.uploadImage(imgFiles.value);
  (Form as any).value.reset();
  loading.value = false;
  for (let i = 0; i < mainStore.images.length; i++) {
    const element = mainStore.images[i];
    imgList = imgList.filter(
      (e) => e.stored_file_name === element.stored_file_name
    );
    imgList.push(element);
  }
}

onMounted(() => {
  // 存入 localStorage
  // if (imgList.length === 0) {
  //   let images: any | null = localStorage.getItem("imagesList");
  //   if (images) {
  //     images = JSON.parse(images);
  //     for (let i = 0; i < images.length; i++) {
  //       const item = images[i];
  //       imgList.push(item);
  //     }
  //   }
  // }

  // webSocket
  WS.onmessage = function (e) {
    setTimeout(() => {
      let image: ImageDownload = {
        file_name: "",
        stored_file_name: "",
      };

      mainStore.images.map((item) => {
        if (item.stored_file_name === e.data) {
          image.file_name = item.file_name;
          image.stored_file_name = item.stored_file_name;
          mainStore.finishImage(image);
        }
      });
      
    }, 1000);
  };
});

async function downloadImg(file_name: string, stored_file_name: string) {
  mainStore.images.map((item) => {
    if (item.stored_file_name === stored_file_name) {
      // 生成下載連結
      const href = URL.createObjectURL(item.link);
      const link = document.createElement("a");
      link.href = href;
      link.setAttribute("download", `${file_name}_hr.png`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(href);
    }
  });
  // const data: ImageDownload = {
  //   file_name: file_name.split(".")[0],
  //   stored_file_name: stored_file_name,
  // };

  // await mainStore.getImage(data);
}

const headers = [
  {
    title: "檔名",
    sortable: true,
    key: "file_name",
    align: "left",
  },
  {
    title: t("state"),
    sortable: true,
    key: "state",
    align: "left",
  },
  {
    title: t("download"),
    key: "stored_file_name",
  },
];
</script>

<template>
  <v-container fluid>
    <v-card class="ma-3 pa-3">
      <v-card-title primary-title>
        <h3 class="card-title mb-3">圖片優化</h3>
      </v-card-title>
      <v-card-text>
        <!-- <section class="d-flex flex-column form-title">
        <img src="@/assets/img/icon/add-image.png" alt="" class="mb-4" />
        <p>請點擊加入圖片並開始優化</p>
       </section> -->

        <v-form v-model="valid" ref="Form">
          <!-- <img src="@/assets/img/icon/add-image.png" alt="" class="mb-4" /> -->
          <!-- <input
            @change="upload()"
            ref="imgFiles"
            type="file"
            multiple
            class="file-input"
          /> -->

          <v-file-input
            v-model="imgFiles"
            multiple
            label="請選擇圖片"
            prepend-icon="add_photo_alternate"
            accept=".jpg, .png"
            :rules="[(imgFiles) => imgFiles.length || '']"
          ></v-file-input>

          <small class="d-block" style="margin: -15px 0 0 40px"
            >支援格式：JPEG、PNG</small
          >

          <!-- <p>請點擊加入圖片並開始優化</p> -->
        </v-form>
      </v-card-text>
      <v-card-actions class="justify-center">
        <v-btn
          variant="flat"
          size="large"
          color="primary"
          class="px-5"
          prepend-icon="file_upload"
          :loading="loading"
          :disabled="imgInput"
          @click="Submit()"
          >上傳</v-btn
        >
      </v-card-actions>
    </v-card>

    <v-card class="ma-3 pa-3 mt-6 img-progress">
      <v-card-title primary-title>
        <h3 class="card-title mb-3">上傳清單</h3>
      </v-card-title>

      <v-data-table :headers="headers" :items="mainStore.images">
        <template v-slot:item.state="{ item }">
          <span v-if="item.raw.state === 'completed'">
            <v-icon icon="check_circle" color="success" />
            完成
          </span>
          <span v-else>
            <v-progress-circular
              indeterminate
              color="info"
              style="width: 20px"
            ></v-progress-circular>
            處理中
          </span>
        </template>
        <template v-slot:item.stored_file_name="{ item }">
          <v-btn
            flat
            :disabled="item.raw.state !== 'completed'"
            @click="downloadImg(item.raw.file_name, item.raw.stored_file_name)"
          >
            <v-icon icon="crop_original" />
          </v-btn>
        </template>
      </v-data-table>
    </v-card>

    <Dialog
      :msg="dialog.msg"
      :state="dialog.state"
      :dialog="dialog.show"
      @close="dialog.show = false"
    ></Dialog>
  </v-container>
</template>

<style lang="scss">
.img-form {
  position: relative;
  top: 50%;
  left: 50%;
  margin-left: -250px;
  width: 500px;
  height: 200px;
  border: 2px dashed #b5b5b5;
  .file-input {
    position: absolute;
    z-index: 100;
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    outline: none;
    opacity: 0;
    cursor: pointer;
  }
  img {
    position: absolute;
    width: 50px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -80%);
  }
  p {
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 50px;
    font-size: 18px;
    font-weight: 600;
    letter-spacing: 1px;
  }
}

.img-progress {
  .v-data-table-footer {
    margin-top: 20px;
  }
}
</style>
