<script setup lang="ts">
import { ref, watch, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
import { useQuasar } from "quasar";
import axios from "axios";

import http from "@/plugins/http";
import config from "@/app.config";
import genReport from "@/plugins/genreport";
import { tokenParsed } from "@/plugins/auth";
import { VuePDF } from "@tato30/vue-pdf";

import type { FormCommand } from "@/modules/06_evaluate/interface/evalute";

import { useCounterMixin } from "@/stores/mixin";
import { useEvaluateStore } from "@/modules/06_evaluate/store";

/** use*/
const $q = useQuasar();
const store = useEvaluateStore();
const mixin = useCounterMixin();
const route = useRoute();
const { showLoader, hideLoader, date2Thai, messageError, success } = mixin;

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

/** emit */
const emit = defineEmits(["update:form"]);

/** form ผู้เซ็นเอกสาร*/
const formCommand = reactive<FormCommand>({
  commanderFullname: "",
  commanderPosition: "",
  commanderPositionOld: "",
  commanderOrg: "",
  commanderOrgOld: "",
  commanderAboveFullname: "",
  commanderAbovePosition: "",
  commanderAbovePositionOld: "",
  commanderAboveOrgOld: "",
  commanderAboveOrg: "",
  author: "",
  subject: [""],
  assignedPosition: "",
});

const formTemplates = ref<any[]>([
  {
    code: "EV1_005",
    templateName: "template-1",
    title: "แบบพิจารณาคุณสมบัติบุคคล",
    fileName: "1-แบบพิจารณาคุณสมบัติบุคคล",
    downloadFile: "",
    file: null,
    isLoading: false,
  },
  {
    code: "EV1_006",
    templateName: "template-2",
    title: "แบบแสดงรายละเอียดการเสนอผลงาน",
    fileName: "2-แบบแสดงรายละเอียดการเสนอผลงาน",
    downloadFile: "",
    file: null,
    isLoading: false,
  },
  {
    code: "EV1_008",
    templateName: "template-4",
    title: "แบบประเมินคุณลักษณะบุคคล",
    fileName: "4-แบบประเมินคุณลักษณะบุคคล",
    downloadFile: "",
    file: null,
    isLoading: false,
  },
  {
    code: "EV1_010",
    templateName: "template-6",
    title: "ผลงานที่จะส่งประเมิน (เอกสารหมายเลข 11)",
    fileName: "6-ผลงานที่จะส่งประเมิน (เอกสารหมายเลข 11)",
    downloadFile: "",
    file: null,
    isLoading: false,
  },
]);

/**
 * function updateFormref
 * @param val value ผู้เซ็นเอกสาร
 */
function updateInput(val: any) {
  const ref = {
    statusUpload: false,
    downloadFile: formTemplates.value.map((e) => e.downloadFile),
  };
  emit("update:form", val, ref); // ส่งข้อมูลไปอัปเดท
}

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

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

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

/**
 * funcion ดาวน์โหลดไฟล์
 * @param tp templatname
 * @param templateName
 * @param fileName ชือ่ไฟล์
 */
async function onClickDowloadFile(
  tp: string,
  templateName: string,
  fileName: string
) {
  showLoader();
  const body = {
    template: tp,
    reportName: templateName,
    data: profile.value,
  };
  await genReport(body, fileName); //สร้างไฟล์ต้นแบบ
  hideLoader();
}

/**
 * function fetch ลิงก์อัปโหลดไฟล์
 * @param volume เล่ม
 * @param id  evaluate ID
 * @param type ประเภทไฟล์
 * @param file ไฟล์
 */
async function fetchPathUpload(
  volume: string,
  id: string | undefined,
  type: string,
  file: any
) {
  const body = {
    fileList: {
      fileName: type,
      metadata: {
        subject: formCommand.subject,
        author: formCommand.author,
      },
    },
  };

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

/**
 *  functoin อัปโหลดไฟล์
 * @param uploadUrl  link อัปโหลด
 * @param file  ไฟล์
 */
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);
    });
}

/**
 * function fecth รายชื่อผู้เซ็นเอกสาร
 * @param id evaluate ID
 */
async function fetcheSigner(id: string) {
  isLoading.value = true;
  await http
    .get(config.API.evaluationSignerDoc1(id))
    .then((res) => {
      const data = res.data.result;
      formCommand.commanderFullname = data.commanderFullname;
      formCommand.commanderPosition = data.commanderPosition;
      formCommand.commanderPositionOld = data.commanderPositionOld;
      formCommand.commanderOrg = data.commanderOrg;
      formCommand.commanderOrgOld = data.commanderOrgOld;
      formCommand.commanderAboveFullname = data.commanderAboveFullname;
      formCommand.commanderAbovePosition = data.commanderAbovePosition;
      formCommand.commanderAbovePositionOld = data.commanderAbovePositionOld;
      formCommand.commanderAboveOrgOld = data.commanderAboveOrgOld;
      formCommand.commanderAboveOrg = data.commanderAboveOrg;
      formCommand.author = data.author;
      formCommand.subject = data.subject;
      store.statusUpload = true;
    })
    .catch(async () => {
      store.statusUpload = false;
      await getCommander();
    })
    .finally(() => {
      isLoading.value = false;
    });
}

/**
 * function
 * @param id  evaluate ID
 */
async function fetchCheckSpec(id: string) {
  await http
    .get(config.API.evaluationReportCheckspecByid(id))
    .then((res) => {
      const data = res.data.result;
      profile.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * function ดาวน์โหลดไฟล์
 * @param fileName ชื่อไฟล์
 */
async function downloadFile(fileName: string) {
  const loadingKey = formTemplates.value.findIndex(
    (item) => item.fileName === fileName
  );
  formTemplates.value[loadingKey].isLoading = true;

  await http
    .get(config.API.loadFileDocument("เล่ม 1", evaluateId.value, fileName))
    .then((res) => {
      const index = formTemplates.value.findIndex(
        (item) => item.fileName === fileName
      );
      if (index !== -1) {
        formTemplates.value[index].downloadFile = res.data.downloadUrl;
      }
    })
    .finally(() => {
      const ref = {
        statusUpload: false,
        downloadFile: formTemplates.value.map((e) => e.downloadFile),
      };

      emit("update:form", formCommand, ref);
      formTemplates.value[loadingKey].isLoading = false;
    });
}

function getCommander() {
  http
    .get(config.API.searchCommander)
    .then((res) => {
      const data = res.data.result;
      formCommand.author = data.fullname;
      formCommand.commanderFullname = data.commanderFullname;
      formCommand.commanderPosition = data.commanderPosition;
      formCommand.commanderAboveFullname = data.commanderAboveFullname;
      formCommand.commanderAbovePosition = data.commanderAbovePosition;
      formCommand.commanderOrg = data.commanderOrg;
      formCommand.commanderAboveOrg = data.commanderAboveOrg;
    })
    .catch((e) => {
      console.log(e);
    });
}

function onAddSubject() {
  formCommand.subject.push("");
}

function onDeleteSubject(index: number) {
  formCommand.subject.splice(index, 1);
}

/** callback function */
watch(
  () => store.checkFileupload,
  () => {
    for (let i = 0; i < formTemplates.value.length; i++) {
      if (formTemplates.value[i].downloadFile === "") {
        formTemplates.value[i].file = null;
      }
    }
  }
);

watch(
  () => store.statusUpload,
  () => {
    setTimeout(() => {
      store.statusUpload && updateInput(formCommand);
    }, 200);
  }
);

/**lifecycle Hooks*/
onMounted(async () => {
  try {
    await Promise.all([
      fetcheSigner(evaluateId.value),
      fetchCheckSpec(evaluateId.value),
      formTemplates.value.forEach((e) => {
        downloadFile(e.fileName);
      }),
    ]);
  } catch (error) {
    console.log(error);
  }
});
</script>

<template>
  <div class="col-12 q-pa-sm">
    <!-- ผลงาน -->
    <div class="col-12">
      <q-skeleton height="100px" v-if="isLoading" class="q-mb-sm" />
      <q-card v-else bordered class="cardSp1 col-12">
        <div class="text-weight-medium bg-grey-1 col-12 q-py-sm q-px-md">
          ผลงาน
        </div>
        <div class="col-12"><q-separator /></div>
        <div class="col-12 q-pa-sm">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-input
                :readonly="store.currentStep != 2 || store.statusUpload"
                dense
                outlined
                v-model="formCommand.author"
                @update:model-value="updateInput(formCommand)"
                label="เจ้าของผลงาน"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเจ้าของผลงาน'}`]"
                lazy-rules
                hide-bottom-space
              />
            </div>
            <div
              class="col-12"
              v-if="store.currentStep === 2 && !store.statusUpload"
            >
              <q-btn
                flat
                round
                color="primary"
                icon="add"
                @click="onAddSubject"
              >
                <q-tooltip>เพิ่มชื่อผลงาน</q-tooltip>
              </q-btn>
            </div>
            <div
              class="row col-12 q-col-gutter-sm"
              v-for="(item, index) in formCommand.subject"
              :key="index"
            >
              <div class="col-11">
                <q-input
                  :readonly="store.currentStep != 2 || store.statusUpload"
                  dense
                  outlined
                  label="ชื่อผลงาน"
                  v-model="formCommand.subject[index]"
                  @update:model-value="updateInput(formCommand)"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อผลงาน'}`]"
                  lazy-rules
                  hide-bottom-space
                />
              </div>
              <div
                class="row col-1 items-centet justify-center"
                v-if="index !== 0"
              >
                <q-btn
                  v-if="store.currentStep === 2 && !store.statusUpload"
                  flat
                  round
                  color="red"
                  icon="delete"
                  @click="onDeleteSubject(index)"
                >
                  <q-tooltip>ลบ</q-tooltip>
                </q-btn>
              </div>
            </div>
          </div>
        </div>
      </q-card>
    </div>

    <!-- เลือกผู้เซ็นเอกสาร -->
    <div class="col-12">
      <q-skeleton height="200px" v-if="isLoading" />
      <q-card v-else bordered class="cardSp1 col-12">
        <div class="text-weight-medium bg-grey-1 q-py-sm q-px-md">
          เลือกผู้เซ็นเอกสาร
        </div>
        <div class="col-12"><q-separator /></div>
        <div class="col-12 q-pa-sm">
          <div class="row q-col-gutter-sm">
            <div class="col-xs-12 col-sm-12 row">
              <div class="text-weight-medium q-pt-xs q-pl-sm">
                ผู้บังคับบัญชาชั้นต้น
              </div>
              <div class="row col-12 q-col-gutter-sm q-pa-sm">
                <q-input
                  :readonly="store.currentStep != 2 || store.statusUpload"
                  dense
                  class="col-xs-12 col-sm-6"
                  outlined
                  label="ชื่อ-นามสกุล"
                  v-model="formCommand.commanderFullname"
                  @update:model-value="updateInput(formCommand)"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อ-นามสกุล'}`]"
                  lazy-rules
                  hide-bottom-space
                />
                <div class="col-12">
                  <div class="row col-12 q-col-gutter-sm">
                    <q-input
                      :readonly="store.currentStep != 2 || store.statusUpload"
                      class="col-xs-6 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderPosition"
                      @update:model-value="updateInput(formCommand)"
                      label="ตำแหน่ง"
                      :rules="[(val:string) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
                      lazy-rules
                      hide-bottom-space
                    />

                    <q-input
                      :readonly="store.currentStep != 2 || store.statusUpload"
                      class="col-xs-6 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderOrg"
                      @update:model-value="updateInput(formCommand)"
                      label="สังกัด"
                      :rules="[(val:string) => !!val || `${'กรุณากรอกสังกัด'}`]"
                      lazy-rules
                      hide-bottom-space
                    />
                    <q-input
                      :readonly="store.currentStep != 2 || store.statusUpload"
                      class="col-xs-6 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderPositionOld"
                      @update:model-value="updateInput(formCommand)"
                      label="ตำแหน่งเดิม"
                      hide-bottom-space
                    />
                    <q-input
                      :readonly="store.currentStep != 2 || store.statusUpload"
                      class="col-xs-6 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderOrgOld"
                      @update:model-value="updateInput(formCommand)"
                      label="สังกัดเดิม"
                      hide-bottom-space
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="row q-col-gutter-sm col-12">
            <div class="col-xs-12 col-sm-12 row">
              <div class="text-weight-medium q-pl-sm q-pt-sm">
                ผู้บังคับบัญชาเหนือขึ้นไป 1 ระดับ
              </div>
              <div class="row col-12 q-col-gutter-md q-pa-sm">
                <q-input
                  :readonly="store.currentStep != 2 || store.statusUpload"
                  dense
                  class="col-xs-12 col-sm-6"
                  outlined
                  v-model="formCommand.commanderAboveFullname"
                  label="ชื่อ-นามสกุล"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อ-นามสกุล'}`]"
                  lazy-rules
                  @update:model-value="updateInput(formCommand)"
                  hide-bottom-space
                />

                <div class="col-12">
                  <div class="row col-12 q-col-gutter-sm">
                    <q-input
                      :readonly="store.currentStep != 2 || store.statusUpload"
                      class="col-xs-6 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderAbovePosition"
                      label="ตำแหน่ง"
                      :rules="[(val:string) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
                      lazy-rules
                      hide-bottom-space
                      @update:model-value="updateInput(formCommand)"
                    />
                    <q-input
                      :readonly="store.currentStep != 2 || store.statusUpload"
                      class="col-xs-6 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderAboveOrg"
                      label="สังกัด"
                      :rules="[(val:string) => !!val || `${'กรุณากรอกสังกัด'}`]"
                      lazy-rules
                      hide-bottom-space
                      @update:model-value="updateInput(formCommand)"
                    />
                    <q-input
                      :readonly="store.currentStep != 2 || store.statusUpload"
                      class="col-xs-6 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderAbovePositionOld"
                      label="ตำแหน่งเดิม"
                      hide-bottom-space
                      @update:model-value="updateInput(formCommand)"
                    />
                    <q-input
                      :readonly="store.currentStep != 2 || store.statusUpload"
                      class="col-xs-6 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderAboveOrgOld"
                      label="สังกัดเดิม"
                      hide-bottom-space
                      @update:model-value="updateInput(formCommand)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </q-card>
    </div>

    <!-- v-if="store.statusUpload -->
    <div class="row q-col-gutter-sm q-mt-sm">
      <div
        class="col-6"
        v-if="store.currentStep === 2"
        v-for="(item, index) in formTemplates"
        :key="index"
      >
        <q-skeleton height="100px" v-if="item.isLoading" />

        <q-card bordered class="cardSp1" v-else>
          <div
            class="text-weight-medium bg-grey-1 q-py-sm q-pl-md q-pr-sm col-12 row items-center"
          >
            <div>{{ item.title }}</div>
            <q-space />
            <div>
              <q-btn
                flat
                dense
                icon="download"
                color="indigo"
                @click="
                  onClickDowloadFile(item.code, item.templateName, item.title)
                "
              >
                <q-tooltip> ดาวน์โหลดต้นแบบ </q-tooltip></q-btn
              >
            </div>
            <div>
              <q-btn
                v-if="item.downloadFile != ''"
                :href="item.downloadFile"
                target="_blank"
                class="q-ml-sm"
                color="blue"
                flat
                dense
                icon="visibility"
              >
                <q-tooltip> ดูไฟล์เอกสาร </q-tooltip></q-btn
              >
            </div>
          </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">
                <q-file
                  v-model="item.file"
                  :disable="!store.statusUpload"
                  class="col-xs-12 col-sm-12"
                  label="อัปโหลดไฟล์"
                  outlined
                  dense
                  lazy-rules
                  hide-bottom-space
                  accept=".pdf"
                  :rules="
                  item.downloadFile === ''
                      ? [(val:any) => !!val || 'กรุณาเลือกไฟล์']
                      : []
                  "
                >
                  <template v-slot:prepend>
                    <q-icon name="attach_file" />
                  </template>
                  <template v-slot:after>
                    <q-btn
                      :disable="!store.statusUpload"
                      flat
                      round
                      dense
                      color="primary"
                      icon="mdi-upload"
                      @click="
                        fetchPathUpload(
                          'เล่ม 1',
                          evaluateId,
                          item.fileName,
                          item.file
                        )
                      "
                      ><q-tooltip>อัปโหลดไฟล์</q-tooltip></q-btn
                    >
                  </template>
                </q-file>
              </div>
            </div>
          </div>
        </q-card>
      </div>
    </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>
