<!-- card อัปโหลดเอกสาร -->
<template>
  <HeaderTop
    v-model:edit="edit"
    :header="
      $q.screen.gt.xs
        ? 'อัปโหลดเอกสาร(เช่น สำเนาบัตรประชาชน ทะเบียนบ้าน วุฒิการศึกษา)'
        : 'อัปโหลดเอกสาร'
    "
    icon="mdi-file-document"
    :addData="true"
    :editOnly="true"
    :editData="status == 'register' || status == 'rejectRegister'"
  />

  <div v-if="edit" class="row justify-center row col-12">
    <q-input
      class="q-mt-sm col-12 q-pb-xs"
      :outlined="edit"
      dense
      lazy-rules
      :readonly="!edit"
      :borderless="!edit"
      v-model="name"
      hide-bottom-space
      :rules="[(val) => !!val || `${'กรุณากรอกชื่อเอกสาร'}`]"
      :label="`${'ชื่อเอกสาร'}`"
    />
    <q-uploader
      color="gray"
      type="file"
      flat
      :factory="uploadData"
      ref="uploader"
      class="full-width"
      text-color="dark"
      :max-size="10000000"
      accept=".jpg,.png,.pdf,.csv,.doc"
      bordered
      label="[ไฟล์ jpg,png,pdf,csv,doc ขนาดไม่เกิน 10MB]"
      @added="fileAdd"
    >
      <template v-slot:header="scope">
        <div class="row no-wrap items-center q-pa-sm q-gutter-xs">
          <q-btn
            v-if="scope.queuedFiles.length > 0"
            icon="clear_all"
            @click="scope.removeQueuedFiles"
            round
            dense
            flat
          >
            <q-tooltip>ลบทั้งหมด</q-tooltip>
          </q-btn>
          <q-btn
            v-if="scope.uploadedFiles.length > 0"
            icon="done_all"
            @click="scope.removeUploadedFiles"
            round
            dense
            flat
          >
            <q-tooltip>ลบไฟล์ที่อัปโหลด</q-tooltip>
          </q-btn>
          <q-spinner v-if="scope.isUploading" class="q-uploader__spinner" />
          <div class="col">
            <div class="q-uploader__title">{{ '[ไฟล์ jpg,png,pdf,csv,doc ขนาดไม่เกิน 10MB]' }}</div>
            <div class="q-uploader__subtitle">
              {{ scope.uploadSizeLabel }} / {{ scope.uploadProgressLabel }}
            </div>
          </div>
          <q-btn
            v-if="scope.canAddFiles"
            type="a"
            icon="add_box"
            @click="scope.pickFiles"
            round
            dense
            flat
          >
            <q-uploader-add-trigger />
            <q-tooltip>เลือกไฟล์</q-tooltip>
          </q-btn>
          <q-btn
            v-if="scope.canUpload"
            icon="cloud_upload"
            label="อัพโหลดไฟล์"
            @click="scope.upload"
            round
            dense
            flat
          >
            <q-tooltip>อัพโหลดไฟล์</q-tooltip>
          </q-btn>

          <q-btn v-if="scope.isUploading" icon="clear" @click="scope.abort" round dense flat>
            <q-tooltip>ยกเลิกการอัปโหลด</q-tooltip>
          </q-btn>
        </div>
      </template>
    </q-uploader>
  </div>
  <q-card bordered flat class="full-width">
    <q-list separator>
      <q-item v-for="file in files" :key="file.id" class="q-my-xs">
        <q-item-section>
          <q-item-label class="full-width ellipsis">
            {{ file.fileName }}
          </q-item-label>

          <q-item-label caption> สถานะ: {{ file.fileType }} / {{ file.fileSize }} </q-item-label>
        </q-item-section>
        <q-item-section top side>
          <div class="q-gutter-sm">
            <q-btn
              size="12px"
              flat
              dense
              round
              color="blue"
              icon="mdi-download-outline"
              @click="downloadData(file.detail)"
            >
              <q-tooltip>ดาวน์โหลด</q-tooltip>
            </q-btn>
            <q-btn
              size="12px"
              flat
              dense
              round
              color="red"
              icon="mdi-delete-outline"
              v-if="edit"
              @click="deleteData(file.id)"
            >
              <q-tooltip>ลบไฟล์</q-tooltip>
            </q-btn>
          </div>
        </q-item-section>
      </q-item>
    </q-list>
  </q-card>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import HeaderTop from '@/components/top.vue'
import http from '@/plugins/http'
import config from '@/app.config'
import { useRoute } from 'vue-router'
import type { UploadType } from '@/modules/01_exam/interface/index/Main'

const props = defineProps({
  status: {
    type: String,
    required: true
  }
})
const route = useRoute()
const examId = ref<string>(route.params.id.toString())
const positionId = ref<string>(route.params.positionId.toString())
const uploader = ref<any>()
const loader = ref<boolean>(false)
const edit = ref<boolean>(props.status == 'register' || props.status == 'rejectRegister')
const name = ref<string>('')
const files = ref<UploadType[]>([])
const emit = defineEmits(['update:loader'])

onMounted(async () => {
  await getData()
})

const fileAdd = async (file: any) => {
  name.value = file[0].name
}

const getData = async () => {
  loader.value = true
  await http
    .get(config.API.candidateUpload(examId.value, positionId.value))
    .then((res) => {
      const data = res.data.result
      files.value = data
    })
    .catch(() => {})
    .finally(() => {
      loader.value = false
    })
}

const deleteData = async (id: string) => {
  loader.value = true
  const params = {
    documentId: id
  }
  await http
    .delete(config.API.candidateUpload(examId.value, positionId.value), {
      params
    })
    .then((res) => {
      const data = res.data.result
    })
    .catch(() => {})
    .finally(async () => {
      loader.value = false
      await getData()
    })
}

const uploadData = async (file: any) => {
  loader.value = true
  const blob = file.slice(0, file[0].size)
  const newFile = new File(blob, name.value, {
    type: file[0].type
  })
  const formData = new FormData()
  formData.append('', newFile)
  await http
    .put(config.API.candidateUpload(examId.value, positionId.value), formData)
    .then((res) => {
      const data = res.data.result
    })
    .catch(() => {})
    .finally(async () => {
      loader.value = false
      name.value = ''
      setTimeout(() => {
        uploader.value.reset()
      }, 100)
      await getData()
    })
}

const downloadData = async (path: string) => {
  window.open(path)
}
</script>
