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

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

/** importComponents*/
import ViewPDF from "@/modules/06_evaluate/components/viewstep/viewPDF.vue";

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

/** use*/
const $q = useQuasar();
const store = useEvaluateStore();
const mixins = useCounterMixin();
const route = useRoute();

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

/** id ประเมิน*/
const evaluateId = ref<string>(route.params.id.toString());

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

const fileEvaluation1 = ref<any>();

/** form จัดเตรียมเอกสารเล่ม 2*/
const formCommand = reactive<FormCommand>({
  commanderFullname: "",
  commanderPosition: "",
  commanderAboveFullname: "",
  commanderAbovePosition: "",
  author: "",
  subject: "",
  assignedPosition: "",
});
/** ref input*/
const commanderFullnameRef = ref<object | null>(null);
const commanderPositionRef = ref<object | null>(null);
const commanderAboveFullnameRef = ref<object | null>(null);
const commanderAbovePositionRef = ref<object | null>(null);
const fileEvaluation1Ref = ref<object | null>(null);
const performanceRef = ref<object | null>(null);
const performanceOwnerRef = ref<object | null>(null);
const assignedPositionRef = ref<object | null>(null);

const modalView = ref<boolean>(false);

/** function อัปเดท ผลงาน,ผู้เซ็นเอกสาร*/
function updateInput(value: any) {
  const ref = {
    commanderFullnameRef: commanderFullnameRef.value,
    commanderPositionRef: commanderPositionRef.value,
    commanderAboveFullnameRef: commanderAboveFullnameRef.value,
    commanderAbovePositionRef: commanderAbovePositionRef.value,
    fileEvaluation1Ref: fileEvaluation1Ref.value,
    downloadFile: [downloadUrl.value],
    performance: performanceRef.value,
    performanceOwner: performanceOwnerRef.value,
    assignedPosition: assignedPositionRef.value,
  };
  emit("update:form", value, ref);
}

/**
 * function เรียก Path อัปโหลดไฟล์
 * @param volume เล่ม
 * @param 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,
        position: formCommand.assignedPosition,
      },
    },
  };
  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();
      });
  }
}

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

/**
 * function เรียกข้อมูล ผลงาน,ผู้เช็นเอกสาร
 * @param id ประเมิน
 */
async function fetcheSigner(id: string) {
  showLoader();
  await http
    .get(config.API.evaluationSignerDoc2(id))
    .then((res) => {
      const data = res.data.result;
      formCommand.commanderFullname = data.commanderFullnameDoc2;
      formCommand.commanderPosition = data.commanderPositionDoc2;
      formCommand.commanderAboveFullname = data.commanderAboveFullnameDoc2;
      formCommand.commanderAbovePosition = data.commanderAbovePositionDoc2;
      formCommand.author = data.authorDoc2;
      formCommand.subject = data.subjectDoc2;
      formCommand.assignedPosition = data.assignedPosition;

      store.statusUpload = true;
    })
    .catch(() => {
      store.statusUpload = false;
    })
    .finally(() => {
      hideLoader();
    });
}

const dateEndPrepareDoc2 = ref<string | null>(date2Thai(new Date()));
/** functoin เรียกข้อมูลวันสุดท้ายของการส่งผลงาน*/
async function fetchCheckDate() {
  evaluateId.value &&
    (await http
      .get(config.API.evaluationCheckDate(evaluateId.value))
      .then((res) => {
        const data = res.data.result;

        const endDate = new Date(data.dateEndAnnounce);
        endDate.setDate(endDate.getDate() + 180);
        dateEndPrepareDoc2.value = date2Thai(endDate);
      })
      .catch((err) => {}));
}

const downloadUrl = ref<string>("");
/** function เช็คไฟล์อัปโหลด*/
function checkDoc() {
  showLoader();
  http
    .get(
      config.API.loadFileDocument("เล่ม 2", evaluateId.value, "1-เอกสารเล่ม 2")
    )
    .then((res: any) => {
      downloadUrl.value = res.data.downloadUrl;
    })
    .catch(() => {})
    .finally(() => {
      hideLoader();
      const ref = {
        commanderFullnameRef: commanderFullnameRef.value,
        commanderPositionRef: commanderPositionRef.value,
        commanderAboveFullnameRef: commanderAboveFullnameRef.value,
        commanderAbovePositionRef: commanderAbovePositionRef.value,
        fileEvaluation1Ref: fileEvaluation1Ref.value,
        downloadFile: [downloadUrl.value],
        performance: performanceRef.value,
        performanceOwner: performanceOwnerRef.value,
        assignedPosition: assignedPositionRef.value,
      };

      emit("update:form", formCommand, ref);
    });
}

/** hook lifecycle*/
onMounted(async () => {
  if (keycloak.tokenParsed != null) {
    formCommand.author = keycloak.tokenParsed.name;
  }
  checkDoc();
  if (store.currentStep > 2) {
    fetcheSigner(evaluateId.value);
  }
  await fetchCheckDate();
});

watch(
  () => store.checkFileupload,
  () => {
    downloadUrl.value === ""
      ? (fileEvaluation1.value = "")
      : fileEvaluation1.value;
  }
);
watch(
  () => store.statusUpload,
  () => {
    setTimeout(() => {
      store.statusUpload && updateInput(formCommand);
    }, 200);
  }
);
</script>

<template>
  <div class="row col-12 q-pa-md">
    <div class="row q-col-gutter-sm">
      <div class="col-12 text-center">
          <q-banner rounded class="text-weight-bold text-red-14 bg-red-1">
          <div class="text-weight-bold">
            <q-icon name="info_outline" color="red-14" size="24px" />
            วันสุดท้ายของการส่งผลงานคือวันที่ {{ dateEndPrepareDoc2 }}
          </div>
        </q-banner>
      </div>

      <!-- ผลงาน -->
      <div class="col-12">
        <q-card bordered class="shadow-0" style="border: 1px solid #d6dee1">
          <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">
            <div class="row q-col-gutter-sm col-12">
              <div class="col-xs-12 col-sm-12 row">
                <div class="row col-12 q-col-gutter-sm q-pa-sm">
                  <q-input
                    :readonly="store.currentStep != 6"
                    ref="performanceRef"
                    dense
                    class="col-xs-12 col-sm-6"
                    outlined
                    label="ชื่อผลงาน"
                    v-model="formCommand.subject"
                    @update:model-value="updateInput(formCommand)"
                    :rules="[(val) => !!val || `${'กรุณากรอกชื่อผลงาน'}`]"
                    hide-bottom-space
                    lazy-rules
                  />
                  <q-input
                    :readonly="store.currentStep != 6"
                    ref="performanceOwnerRef"
                    class="col-xs-12 col-sm-6"
                    dense
                    outlined
                    v-model="formCommand.author"
                    @update:model-value="updateInput(formCommand)"
                    label="เจ้าของผลงาน"
                    hide-bottom-space
                    :rules="[(val) => !!val || `${'กรุณากรอกเจ้าของผลงาน'}`]"
                    lazy-rules
                  />
                  <q-input
                    :readonly="store.currentStep != 6"
                    ref="assignedPositionRef"
                    class="col-xs-12 col-sm-6"
                    dense
                    outlined
                    v-model="formCommand.assignedPosition"
                    @update:model-value="updateInput(formCommand)"
                    label="ตำแหน่งที่ได้รับ"
                    hide-bottom-space
                    :rules="[
                      (val) => !!val || `${'กรุณากรอกตำแหน่งที่ได้รับ'}`,
                    ]"
                    lazy-rules
                  />
                </div>
              </div>
            </div>
          </div>
        </q-card>
      </div>

      <!-- เลือกผู้เซ็นเอกสาร -->
      <div class="col-12">
        <q-card bordered class="shadow-0" style="border: 1px solid #d6dee1">
          <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 != 6"
                      ref="commanderFullnameRef"
                      dense
                      class="col-xs-12 col-sm-6"
                      outlined
                      label="ชื่อ-นามสกุล"
                      v-model="formCommand.commanderFullname"
                      @update:model-value="updateInput(formCommand)"
                      :rules="[(val) => !!val || `${'กรุณากรอกชื่อ-นามสกุล'}`]"
                      lazy-rules
                      hide-bottom-space
                    />
                    <q-input
                      :readonly="store.currentStep != 6"
                      ref="commanderPositionRef"
                      class="col-xs-12 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderPosition"
                      @update:model-value="updateInput(formCommand)"
                      label="ตำแหน่ง"
                      :rules="[(val) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
                      lazy-rules
                      hide-bottom-space
                    />
                  </div>
                </div>
              </div>

              <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">
                    ผู้บังคับบัญชาเหนือขึ้นไป 1 ระดับ
                  </div>
                  <div class="row col-12 q-col-gutter-sm q-pa-sm">
                    <q-input
                      :readonly="store.currentStep != 6"
                      ref="commanderAboveFullnameRef"
                      dense
                      class="col-xs-12 col-sm-6"
                      outlined
                      v-model="formCommand.commanderAboveFullname"
                      label="ชื่อ-นามสกุล"
                      :rules="[(val) => !!val || `${'กรุณากรอกชื่อ-นามสกุล'}`]"
                      lazy-rules
                      @update:model-value="updateInput(formCommand)"
                      hide-bottom-space
                    />
                    <q-input
                      :readonly="store.currentStep != 6"
                      ref="commanderAbovePositionRef"
                      class="col-xs-12 col-sm-6"
                      dense
                      outlined
                      v-model="formCommand.commanderAbovePosition"
                      label="ตำแหน่ง"
                      :rules="[(val) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
                      lazy-rules
                      @update:model-value="updateInput(formCommand)"
                      hide-bottom-space
                    />
                  </div>
              </div>
            </div>
          </div>
        </q-card>
      </div>

      <!-- อัปไฟล์ -->
      <div class="col-12" v-if="store.currentStep === 6">
        <q-card bordered class="shadow-0" style="border: 1px solid #d6dee1">
          <div class="col-12 row bg-grey-1">
            <div class="text-weight-medium q-py-sm q-px-md">
              เอกสารเล่ม 2
            </div>
            <q-space /> 
            <div v-if="downloadUrl">
              <q-btn
                :href="downloadUrl"
                target="_blank"
                outline
                flat
                icon="visibility"
                color="blue"
              >
                <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-sm col-12">
               
                <div class="col-12">
                  <!-- :rules="[(val) => !!val || 'เลือกไฟล']" -->
                  <q-file
                    :disable="!store.statusUpload"
                    ref="fileEvaluation1Ref"
                    v-model="fileEvaluation1"
                    class="col-12"
                    outlined
                    hide-bottom-space
                    dense
                    lazy-rules
                    accept=".pdf"
                    :rules="
                      downloadUrl === ''
                        ? [(val) => !!val || 'กรุณาเลือกไฟล์']
                        : []
                    "
                  >
                    <template v-slot:prepend>
                      <q-icon name="attach_file" />
                    </template>
                    <template v-slot:after>
                      <div>
                      <q-btn
                        :disable="!store.statusUpload"
                        round
                        dense
                        flat
                        color="primary"
                        icon="mdi-upload"
                        @click="
                          fetchPathUpload(
                            'เล่ม 2',
                            evaluateId,
                            '1-เอกสารเล่ม 2',
                            fileEvaluation1
                          )
                        "
                        ><q-tooltip>อัปโหลดไฟล์</q-tooltip></q-btn
                      >
                      </div>
                    </template>
                  </q-file>
                </div>
              </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">
        <ViewPDF />
      </div>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
