<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import axios from "axios";
import { useQuasar } from "quasar";
import ViewPDF from "@/modules/06_evaluate/components/viewstep/viewPDF.vue";

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

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

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

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

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

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

const fileEvaluation1 = ref<any>();
const pdfSrc = ref<any>();

const formCommand = reactive<FormCommand>({
  commanderFullname: "",
  commanderPosition: "",
  commanderAboveFullname: "",
  commanderAbovePosition: "",
});

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 modalView = ref<boolean>(false);
function onClickViewPDF(file: any) {
  pdfSrc.value = file.webkitRelativePath;
  modalView.value = true;
}

const updateInput = (value: any) => {
  const ref = {
    commanderFullnameRef: commanderFullnameRef.value,
    commanderPositionRef: commanderPositionRef.value,
    commanderAboveFullnameRef: commanderAboveFullnameRef.value,
    commanderAbovePositionRef: commanderAbovePositionRef.value,
    fileEvaluation1Ref: fileEvaluation1Ref.value,
  };
  emit("update:form", value, ref);
};

async function fetchPathUpload(
  volume: string,
  id: string | undefined,
  type: string,
  file: any
) {
  const body = {
    fileList: { fileName: type, metadata: {} },

    // "1-แบบพิจารณาคุณสมบัติบุคคล",
    // "2-แบบแสดงรายละเอียดการเสนอผลงาน",
    // "3-แบบตรวจสอบความถูกต้องครบถ้วนของข้อมูลเพื่อประกอบการคัดเลือกบุคคล (เอกสารแบบ ก.)",
    // "4-แบบประเมินคุณลักษณะบุคคล",
    // "5-แบบสรุปข้อมูลของผู้ขอรับการคัดเลือก (เอกสารหมายเลข 9)",
    // "6-ผลงานที่จะส่งประเมิน (เอกสารหมายเลข 11)",
  };
  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) {
  console.log(uploadUrl);
  await axios
    .put(uploadUrl, file, {
      headers: {
        "Content-Type": file.type,
      },
    })
    .then(() => {
      success($q, "อัปโหลไฟล์สำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    });
}

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;
    })
    // .catch((err) => {
    //   messageError($q, err);
    // })
    .finally(() => {
      hideLoader();
    });
}

// const dateStartPrepareDoc2 = ref<string | null>(date2Thai(new Date()));
const dateEndPrepareDoc2 = ref<string | null>(date2Thai(new Date()));

async function fetchCheckDate() {
  evaluateId.value &&
    (await http
      .get(config.API.evaluationCheckDate(evaluateId.value))
      .then((res) => {
        const data = res.data.result;
        // dateStartPrepareDoc2.value = date2Thai(data.dateStartPrepareDoc2);
        const endDate = new Date(data.dateEndAnnounce);
        endDate.setDate(endDate.getDate() + 180);
        dateEndPrepareDoc2.value = date2Thai(endDate);
        // dateEndPrepareDoc2.value = data.dateEndPrepareDoc2
        //   ? date2Thai(data.dateEndPrepareDoc2)
        //   : dateEndPrepareDoc2.value;
      })
      .catch((err) => {}));
}

onMounted(async () => {
  const ref = {
    commanderFullnameRef: commanderFullnameRef.value,
    commanderPositionRef: commanderPositionRef.value,
    commanderAboveFullnameRef: commanderAboveFullnameRef.value,
    commanderAbovePositionRef: commanderAbovePositionRef.value,
    fileEvaluation1Ref: fileEvaluation1Ref.value,
  };
  if (store.currentStep > 2) {
    fetcheSigner(evaluateId.value);
  }
  await fetchCheckDate();
  emit("update:form", formCommand, ref);
  // props.evaluateId && (await fetchPathUpload("เล่ม 2", props.evaluateId));
});

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

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

<template>
  <div class="row q-col-gutter-md">
    <div class="col-12 text-center">
      <q-banner class="text-weight-bold text-red-14 bg-red-2">
        <div class="text-weight-bold">
          <q-icon name="info_outline" color="red-14" size="24px" />
          วันสุดท้ายของการส่งผลงานคือวันที่ {{ dateEndPrepareDoc2 }}
        </div>
      </q-banner>
    </div>
    <div class="col-6" v-if="store.currentStep === 6">
      <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-xs-12 col-sm-6 row">
                <q-btn
                  class="col-12"
                  outline
                  icon="download"
                  label="ดาวน์โหลดต้นแบบ"
                  color="primary"
                >
                  <q-tooltip> ดาวน์โหลดต้นแบบ </q-tooltip></q-btn
                >
              </div> -->
              <div class="col-xs-12 col-sm-6 row">
                <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 class="col-xs-12 col-sm-10 row">
                <!-- :rules="[(val) => !!val || 'เลือกไฟล']" -->

                <q-file
                  ref="fileEvaluation1Ref"
                  v-model="fileEvaluation1"
                  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,
                      '1-เอกสารเล่ม 2',
                      fileEvaluation1
                    )
                  "
                  ><q-tooltip>อัปโหลดไฟล์</q-tooltip></q-btn
                >
              </div>
            </div>
          </div>
        </div>
      </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">
          เลือกผู้เซ็นเอกสาร
        </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-xs-12 col-sm-12 row">
                <div class="text-weight-medium q-py-sm">
                  ผู้บังคับบัญชาชั้นต้น
                </div>
                <div class="row col-12 q-col-gutter-md 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
                  />
                  <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
                  />
                </div>
              </div>
            </div>

            <div class="row q-col-gutter-md col-12">
              <div class="col-xs-12 col-sm-12 row">
                <div class="text-weight-medium q-py-sm">
                  ผู้บังคับบัญชาเหนือขึ้นไป 1 ระดับ
                </div>
                <div class="row col-12 q-col-gutter-md 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)"
                  />
                  <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)"
                  />
                </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">
        <ViewPDF />
      </div>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
