<template>
  <Dialog :visible="uploadModal" modal :style="{ width: '90vw', height: '90vh' }" :contentClass="contentClass" @update:visible="$emit('closeModal', $event)">
    <template #header>
      <div class="py-5">
      </div>
    </template>
    <label for="uploadFiles">
    <div class=" h-full flex flex-col justify-center items-center p-4 space-y-4 relative">
      <input id="uploadFiles" class=" absolute top-0 left-0 w-full h-full opacity-0 cursor-pointer" type="file" accept="text/csv" @change="upload($event)">
        <IconUploarding class="loader-arrow-upward"></IconUploarding>
        <p class="text-neutral-900">Click or drag a file here.</p>
        <p class="text-neutral-500">(Only <span class="text-primary">.csv</span> is supported)</p>
      </div>
    </label>
  </Dialog>
</template>
<script>
import IconUploarding from '../icons/IconUploarding.vue';
import { uploadFailedFirst } from '@/module/alertModal.js'
import { storeToRefs } from 'pinia';
import FilesStore from '@/stores/files.js';

export default {
  props: ['uploadModal'],
  setup() {
    const filesStore = FilesStore();
    const { uploadFileName } = storeToRefs(filesStore);

    return { filesStore, uploadFileName }
  },
  data() {
    return {
      contentClass: 'h-full',
    }
  },
  components: {
    IconUploarding,
  },
  methods: {
    /**
     * 上傳的行為
     * @param {event} event input 傳入的事件
     */
    async upload(event) {
      const fileInput = document.getElementById('uploadFiles');
      const target = event.target;
      const formData = new FormData();
      let uploadFile;

      // 判斷是否有檔案
      if(target && target.files) {
        uploadFile = target.files[0];
      }
      // 判斷檔案大小不可超過 90MB (90(MB)*1024(KB)*1024(Bytes)=94,371,840)
      if(uploadFile.size >= 94371840) {
        fileInput.value = '';
        return uploadFailedFirst('size');
      }
      // 將檔案加進 formData，欄位一定要「csv」
      formData.append('csv', uploadFile);
      // 呼叫第一階段上傳 API
      if(uploadFile) {
        await this.filesStore.upload(formData);
      }
      if (uploadFile.name.endsWith('.csv')) {
        this.uploadFileName = uploadFile.name.slice(0, -4);
      } else {
        // 處理錯誤或無效的文件格式
        this.uploadFileName = ''; // 或者其他適合的錯誤處理方式
      }
      // 清除選擇文件
      if(fileInput) {
        fileInput.value = '';
      }
    }
  },
  beforeUnmount() {
    this.$emit('closeModal', false);
  }
}
</script>
<style scoped>
.loader-arrow-upward {
  animation: bump 0.6s linear infinite alternate;
}
@keyframes bump {
  0% {
    transform: translate(0%, 5px);
  }
  100% {
    transform: translate(0%, -5px);
  }
}
</style>
