<template>
  <q-card flat bordered class="col-12 row q-px-lg q-py-md">
    <HeaderTop
      v-model:edit="edit"
      header="เอกสารหลักฐาน"
      icon="mdi-file-document"
      :history="false"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :save="uploadData"
    />
    <div class="row col-12 q-pt-sm">
      <q-card bordered flat class="full-width">
        <q-list separator>
          <q-item v-for="file in files" :key="file.key" class="q-my-xs">
            <q-item-section>
              <q-item-label class="full-width ellipsis">
                {{ file.fileName }}
              </q-item-label>

              <q-item-label caption> </q-item-label>
            </q-item-section>
            <q-item-section top side>
              <div class="row col-12">
                <q-btn
                  class="gt-xs"
                  size="12px"
                  flat
                  dense
                  round
                  color="blue"
                  icon="mdi-download-outline"
                  @click="downloadData(file.file)"
                />
                <q-btn
                  class="gt-xs"
                  size="12px"
                  flat
                  dense
                  round
                  color="red"
                  icon="mdi-delete-outline"
                  v-show="edit"
                  @click="deleteData(file.id)"
                />
              </div>
            </q-item-section>
          </q-item>
        </q-list>
      </q-card>
      <q-input
        v-if="edit"
        class="q-mt-sm col-12 q-pb-xs"
        outlined
        dense
        lazy-rules
        v-model="name"
        hide-bottom-space
        :rules="[(val) => !!val || `${'กรุณากรอกชื่อเอกสาร'}`]"
        :label="`${'ชื่อเอกสาร'}`"
      />
      <q-uploader
        v-if="edit"
        color="gray"
        type="file"
        flat
        @factory="uploadData"
        ref="uploader"
        class="full-width"
        text-color="white"
        :max-size="10000000"
        accept=".jpg,.png,.pdf,.csv,.doc,.docx"
        bordered
        label="[ไฟล์ jpg,png,pdf,csv,doc,docx ขนาดไม่เกิน 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,docx ขนาดไม่เกิน 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>
</template>
<script setup lang="ts">
import { onMounted, computed, ref, watch } from "vue";
import { useQuasar, QForm } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useRoute } from "vue-router";

import HeaderTop from "@/components/information/top.vue";
import http from "@/plugins/http";
import config from "@/app.config";

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },

  notiNoEdit: {
    type: Function,
    default: () => console.log("not function"),
  },
});
const emit = defineEmits(["update:statusEdit"]);

const $q = useQuasar(); // show dialog
const mixin = useCounterMixin();
const route = useRoute();
const { success, messageError, showLoader, hideLoader } = mixin;
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const edit = ref<boolean>(false);
const uploader = ref<any>();
const files = ref<any>([]);
const file = ref<any>([]);
const name = ref<string>("");

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

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

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

const uploadData = async () => {
  if (profileId.value) {
    if (file.value.length > 0) {
      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("avatar", newFile);
      formData.append("moss", "newFile");
      showLoader();
      await http
        .post(config.API.profilePaperId(profileId.value), formData)
        .then((res) => {
          const data = res.data.result;
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          uploader.value.reset();
          name.value = "";
          edit.value = false;
          emit("update:statusEdit", false);
          await getData();
        });
    } else {
      // modalError(
      //   $q,
      //   "ไม่สามารถอัปโหลดไฟล์ได้",
      //   "กรุณาเลือกไฟล์ที่ต้องการอัปโหลด"
      // );
      getData();
    }
  }
};

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

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

const changeBtn = async () => {
  name.value = "";
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false;
      props.notiNoEdit();
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
};
</script>
