<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { useQuasar } from "quasar";
import axios from "axios";

import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";
import http from "@/plugins/http";
import config from "@/app.config";

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader, success, dialogRemove } = mixin;

const group = defineModel<string>("group", { required: true });
const isCheckFile = defineModel<boolean>("isCheckFile", { required: true });
const round = defineModel<string>("round", { default: "" });
const passResult = defineModel<number>("passResult", { default: 0 });
const isDeleteFile = defineModel<boolean>("isDeleteFile", {
  required: false,
  default: false,
});

const checkRoutePermisson = defineModel<boolean>("checkRoutePermisson", {
  required: true,
});
const dataPermissions = defineModel<boolean>("dataPermissions", {
  required: true,
});

const assignId = ref<string>(route.params.form as string);
const file = ref<any>();
const dataDownload = ref<any>();

const isCanDeleteFile = computed(() => {
  return (
    isDeleteFile.value &&
    checkPermission(route)?.attrIsDelete &&
    dataPermissions.value &&
    !checkRoutePermisson.value
  );
});

function onUploadFiles() {
  showLoader();
  http
    .post(config.API.file("ทดลองงาน", group.value, assignId.value), {
      replace: true,
      fileList: [
        {
          fileName: file.value.name,
        },
      ],
    })
    .then(async (res) => {
      const foundKey: string | undefined = Object.keys(res.data).find(
        (key) =>
          res.data[key]?.fileName !== undefined &&
          res.data[key]?.fileName !== ""
      );
      foundKey && (await uploadFileURL(res.data[foundKey]?.uploadUrl));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function uploadFileURL(uploadUrl: string) {
  const Data = new FormData();
  Data.append("file", file.value);
  showLoader();
  await axios
    .put(uploadUrl, file.value, {
      headers: {
        "Content-Type": file.value.type,
      },
    })
    .then(async () => {
      if (round.value === "2") {
        await onUpdateStatusAssign();
      } else if (passResult.value === 2) {
        await onUpdateStatusAssign();
      }
      file.value = null;
      await success($q, "อัปโหลดไฟล์สำเร็จ");
      await fetchCheckfile();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เช็คไฟล์*/
async function fetchCheckfile() {
  isCheckFile.value = false;
  await http
    .get(config.API.file("ทดลองงาน", group.value, assignId.value))
    .then(async (res) => {
      if (res.data.length >= 1) {
        isCheckFile.value = true;
        dataDownload.value = res.data[0];
      }
    })
    .catch((e) => {
      messageError($q, e);
    });
}

async function onDownloadFile() {
  showLoader();
  http
    .get(config.API.filefullPath(`${dataDownload.value.pathname}`))
    .then(async (res) => {
      const data = res.data.downloadUrl;
      window.open(data, "_blank");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

async function onUpdateStatusAssign() {
  await http
    .patch(
      config.API.createformReport(assignId.value) +
        `&evaluate_no=${round.value}`
    )
    .catch((err) => {
      messageError($q, err);
    });
}

function onDeleteFile() {
  dialogRemove($q, async () => {
    const fileName = dataDownload.value.fileName; // ชื่อไฟล์ที่ต้องการลบ
    try {
      showLoader();
      await http.delete(
        config.API.fileByFile("ทดลองงาน", group.value, assignId.value, fileName)
      );

      await fetchCheckfile();
      success($q, `ลบไฟล์สำเร็จ`);
    } catch (e) {
      messageError($q, e);
    } finally {
      hideLoader();
    }
  });
}

onMounted(() => {
  fetchCheckfile();
});
</script>
<template>
  <div
    class="col-12"
    v-if="!checkRoutePermisson && dataPermissions && !isCheckFile"
  >
    <div class="col-12">
      <q-separator size="3px" color="grey-2" />
    </div>

    <div class="col-12 q-mt-md">
      <div class="col-12 row">
        <q-file
          class="col-12"
          outlined
          dense
          v-model="file"
          label="อัปโหลดเอกสาร"
          hide-bottom-space
        >
          <template v-slot:prepend>
            <q-icon name="attach_file" color="primary" />
          </template>
          <template v-slot:after>
            <q-btn
              v-if="file"
              size="14px"
              flat
              round
              dense
              color="primary"
              icon="mdi-upload"
              @click="onUploadFiles"
              ><q-tooltip>อัปโหลดเอกสาร</q-tooltip></q-btn
            >
          </template>
        </q-file>
      </div>
    </div>
  </div>

  <div class="col-12 q-gutter-sm" v-if="isCheckFile">
    <q-btn
      color="primary"
      icon="mdi-download"
      label="ดาวน์โหลดไฟล์"
      @click="onDownloadFile"
    />

    <q-btn
      v-if="isCanDeleteFile"
      color="red"
      icon="mdi-delete"
      @click="onDeleteFile"
    >
      <q-tooltip>ลบไฟล์</q-tooltip>
    </q-btn>
  </div>
</template>

<style scoped></style>
