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

  <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"
      bordered
      label="[ไฟล์ขนาดไม่เกิน 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.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 } from "vue";
import HeaderTop from "@/modules/03_recruiting/components/top.vue";
import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";

import type { UploadType } from "@/modules/03_recruiting/interface/index/Main";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";

const props = defineProps({
  status: {
    type: String,
    required: true,
  },
});
const $q = useQuasar();
const route = useRoute();
const candidateId = ref<string>(route.params.candidateId.toString());
const uploader = ref<any>();

const edit = ref<boolean>(props.status == "checkRegister");
const name = ref<string>("");
const files = ref<UploadType[]>([]);
const file = ref<File[]>([]);
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader } = mixin;

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

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

const getData = async () => {
  showLoader();
  await http
    .get(config.API.candidateUpload(candidateId.value))
    .then((res) => {
      const data = res.data.result;
      files.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const deleteData = async (id: string) => {
  const params = {
    documentId: id,
  };
  showLoader();
  await http
    .delete(config.API.candidateUpload(candidateId.value), {
      params,
    })
    .then((res) => {
      const data = res.data.result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      await getData();
    });
};

const uploadData = async () => {
  const blob = file.value.slice(0, file.value[0].size);
  const newFile = new File(blob, name.value, {
    type: file.value[0].type,
  });
  const formData = new FormData();
  formData.append("", newFile);
  showLoader();
  await http
    .put(config.API.candidateUpload(candidateId.value), formData)
    .then((res) => {
      const data = res.data.result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      name.value = "";
      uploader.value.reset();
      await getData();
    });
};

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