<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";
import genReport from "@/plugins/genreport";

import TableDirector from "@/modules/06_evaluate/components/directorandmeet/Table.vue";
import { useEvaluateStore } from "@/modules/06_evaluate/store";

import { useCounterMixin } from "@/stores/mixin";

const store = useEvaluateStore();
const $q = useQuasar();
const mixin = useCounterMixin();
const route = useRoute();

const { showLoader, hideLoader, messageError, success, date2Thai } = mixin;

const evaluateId = ref<string>(route.params.id.toString());

const status = ref<string>("WAIT_CHECK_DOC_V2");
const tabMenu = ref<string>("director");

const fileEvaluationEdit = ref<any>();

const modalView = ref<boolean>(false);
const numOfPages = ref<number>(0);
const page = ref<number>(1);
const pdfSrc = ref<any>();

function onClickViewPDF(file: any) {
  pdfSrc.value = file.webkitRelativePath;
  modalView.value = true;
}

/** ไปหน้าต่อไปของรายงาน */
function nextPage() {
  if (page.value < numOfPages.value) {
    page.value++;
  }
}

/** กลับหน้าก่อนหน้าของรายงาน */
function backPage() {
  if (page.value !== 1) {
    page.value--;
  }
}

async function onClickDowloadFile(
  tp: string,
  templateName: string,
  fileName: string
) {
  const body = {
    template: tp,
    reportName: templateName,
    data: {},
  };
  await genReport(body, fileName);
}

const directorList = ref<any>();
const meetingList = ref<any>();

async function fetchDirector() {
  showLoader();
  evaluateId.value &&
    (await http
      .get(config.API.evaluationDirectorMeetring(evaluateId.value))
      .then((res) => {
        const directors = res.data.result.directors;
        const meetings = res.data.result.meetings;
        directorList.value = directors.map((e: any) => ({
          fullName: `${e.prefix}${e.firstName}   ${e.lastName}`,
          position: e.position ?? "-",
          email: e.email ?? "-",
          phone: e.phone ?? "-",
        }));
        meetingList.value = meetings.map((e: any) => ({
          fullName: `${e.Prefix}${e.FirstName}   ${e.LastName}`,
          dateMeeting: `${date2Thai(e.dateStart)} - ${date2Thai(e.dateEnd)}`,
          result: e.result ?? "-",
          duration: e.duration ?? "-",
        }));
      })
      .catch((err) => {})
      .finally(() => {
        hideLoader();
      }));
}

async function fetchPathUpload(
  volume: string,
  id: string | undefined,
  type: string,
  file: any
) {
  const body = {
    fileList: { fileName: type, metadata: {} },
  };
  if (id && file) {
    showLoader();
    await http
      .post(config.API.loadPathDocument(volume, id), body)
      .then((res) => {
        const foundKey: string | undefined = Object.keys(res.data).find(
          (key) =>
            res.data[key]?.fileName !== undefined &&
            res.data[key]?.fileName !== ""
        );
        foundKey && uploadfile(res.data[foundKey]?.uploadUrl, file);
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

async function uploadfile(uploadUrl: string, file: any) {
  await axios
    .put(uploadUrl, file, {
      headers: {
        "Content-Type": file.type,
      },
    })
    .then(() => {
      success($q, "อัปโหลไฟล์สำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    });
}

const downloadUrl = ref<string>("");
function checkDoc() {
  showLoader();
  http
    .get(
      config.API.loadFileDocument(
        "เล่ม 2",
        store.evaluateId,
        "2-เอกสารเล่ม 2 (ฉบับแก้ไข)"
      )
    )
    .then((res: any) => {
      downloadUrl.value = res.data.downloadUrl;
    })
    // .catch((e) => {
    //   messageError($q, e);
    // })
    .finally(() => {
      hideLoader();
    });
}

onMounted(async () => {
  await fetchDirector();
  checkDoc();
});
</script>

<template>
  <div class="row q-gutter-md">
    <div class="col-12 text-center">
      <q-badge
        v-if="status == 'WAIT_CHECK_DOC_V2'"
        outline
        color="orange-5"
        label="รอพิจารณาผลการประเมิน"
        class="q-pa-sm"
        style="font-size: 16px"
      />
    </div>

    <div class="col-12">
      <q-card bordered style="border: 1px solid #d6dee1">
        <q-card class="col-12 items-center">
          <q-tabs
            v-model="tabMenu"
            dense
            align="left"
            inline-label
            class="rounded-borders"
            indicator-color="primary"
            active-bg-color="teal-1"
            active-class="text-primary"
          >
            <q-tab name="director" label="กรรมการ" />
            <q-tab name="meeting" label="การประชุม" />
          </q-tabs>
          <q-separator />
          <q-tab-panels v-model="tabMenu" animated>
            <q-tab-panel name="director"
              ><TableDirector :type="tabMenu" :row="directorList"
            /></q-tab-panel>

            <q-tab-panel name="meeting">
              <TableDirector :type="tabMenu" :row="meetingList"
            /></q-tab-panel>
          </q-tab-panels>
        </q-card>
      </q-card>
    </div>

    <div class="col-12">
      <q-card bordered style="border: 1px solid #d6dee1">
        <div class="text-weight-medium bg-grey-1 q-py-sm q-px-md">
          เอกสารเล่ม 2 (ฉบับแก้ไข)
        </div>
        <div class="col-12"><q-separator /></div>
        <div class="row">
          <div class="col-12 q-pa-sm">
            <div class="row q-col-gutter-md col-12">
              <div class="col-12">
                <q-btn
                  v-if="downloadUrl != ''"
                  :href="downloadUrl"
                  target="_blank"
                  class="col-12"
                  outline
                  icon="visibility"
                  label="ดูไฟล์เอกสาร"
                  color="primary"
                >
                  <q-tooltip> ดูไฟล์เอกสาร </q-tooltip></q-btn
                >
              </div>

              <div v-if="store.currentStep == 8" class="row col-12">
                <div class="col-xs-12 col-sm-10 row">
                  <q-file
                    v-model="fileEvaluationEdit"
                    class="col-12"
                    outlined
                    dense
                    hide-bottom-space
                    lazy-rules
                    accept=".pdf"
                  >
                    <template v-slot:prepend>
                      <q-icon name="attach_file" />
                    </template>
                  </q-file>
                </div>
                <div class="col-2 self-center text-center q-pl-none">
                  <q-btn
                    flat
                    round
                    dense
                    color="primary"
                    icon="mdi-upload"
                    @click="
                      fetchPathUpload(
                        'เล่ม 2',
                        evaluateId,
                        '2-เอกสารเล่ม 2 (ฉบับแก้ไข)',
                        fileEvaluationEdit
                      )
                    "
                    ><q-tooltip>อัปโหลดไฟล์</q-tooltip></q-btn
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </q-card>
    </div>
  </div>

  <!-- Dialog Full Screen -->
  <q-dialog
    v-model="modalView"
    persistent
    :maximized="true"
    transition-show="slide-up"
    transition-hide="slide-down"
  >
    <q-card class="bg-white">
      <div class="flex justify-end items-center align-center q-mr-md q-mt-sm">
        <q-btn
          icon="close"
          unelevated
          round
          dense
          style="color: #ff8080; background-color: #ffdede"
          size="12px"
          v-close-popup
        />
      </div>
      <div class="q-pa-md">
        <div class="row items-start items-center">
          <div class="col">
            <q-btn
              padding="xs"
              icon="mdi-chevron-left"
              color="grey-2"
              text-color="grey-5"
              size="md"
              class="my-auto"
              @click="backPage"
              :disable="page == 1"
            />
          </div>
          <div class="col-12 col-md-auto">
            <div class="q-pa-md flex">
              หน้าที่ {{ page }} จาก {{ numOfPages }}
            </div>
          </div>
          <div class="col text-right">
            <q-btn
              padding="xs"
              icon="mdi-chevron-right"
              color="grey-2"
              text-color="grey-5"
              size="md"
              @click="nextPage"
              :disable="page === numOfPages"
            />
          </div>
        </div>
        <div class="row items- items-center">
          <VuePDF ref="vuePDFRef" :pdf="pdfSrc" :page="page" fit-parent />
        </div>
        <div class="row items- items-end">
          <div class="col">
            <q-btn
              padding="xs"
              icon="mdi-chevron-left"
              color="grey-2"
              text-color="grey-5"
              size="md"
              class="my-auto"
              @click="backPage"
              :disable="page == 1"
            />
          </div>
          <div class="col-12 col-md-auto">
            <div class="q-pa-md flex">
              หน้าที่ {{ page }} จาก {{ numOfPages }}
            </div>
          </div>
          <div class="col text-right">
            <q-btn
              padding="xs"
              icon="mdi-chevron-right"
              color="grey-2"
              text-color="grey-5"
              size="md"
              @click="nextPage"
              :disable="page === numOfPages"
            />
          </div>
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
