<script setup lang="ts">
import { ref, reactive, watch, onMounted } 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 { tokenParsed } from "@/plugins/auth";
import { useCounterMixin } from "@/stores/mixin";
import { useEvaluateStore } from "@/modules/06_evaluate/store";

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

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

/** 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>();
const assignedPosLevel = ref<string>(""); // ระดับตำแหน่งที่ได้รับ

/** form จัดเตรียมเอกสารเล่ม 2*/
const formCommand = reactive<FormCommand>({
  commanderFullname: "",
  commanderPosition: "",
  commanderPositionOld: "",
  commanderOrg: "",
  commanderOrgOld: "",
  commanderAboveFullname: "",
  commanderAbovePosition: "",
  commanderAbovePositionOld: "",
  commanderAboveOrgOld: "",
  commanderAboveOrg: "",
  author: "",
  subject: [""],
  assignedPosition: "",
});

const modalView = ref<boolean>(false);

/** function อัปเดท ผลงาน,ผู้เซ็นเอกสาร*/
function updateInput(value: any) {
  const ref = {
    downloadFile: [downloadUrl.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);
        hideLoader();
      });
  }
}

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

/**
 * 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.commanderPositionOld = data.commanderPositionOldDoc2;
      formCommand.commanderOrg = data.commanderOrgDoc2;
      formCommand.commanderOrgOld = data.commanderOrgOldDoc2;
      formCommand.commanderAboveFullname = data.commanderAboveFullnameDoc2;
      formCommand.commanderAbovePosition = data.commanderAbovePositionDoc2;
      formCommand.commanderAbovePositionOld =
        data.commanderAbovePositionOldDoc2;
      formCommand.commanderAboveOrgOld = data.commanderAboveOrgOldDoc2;
      formCommand.commanderAboveOrg = data.commanderAboveOrgDoc2;
      formCommand.author = data.authorDoc2;
      formCommand.subject = data.subjectDoc2;
      formCommand.assignedPosition = data.assignedPosition;

      assignedPosLevel.value = data.assignedPosLevel;

      store.statusUpload6 = data.isUpdated;
    })
    .catch((err) => {
      messageError($q, err);
      // store.statusUpload6 = false;
      // getCommander();
    })
    .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 เช็คไฟล์อัปโหลด*/
async function checkDoc() {
  await http
    .get(
      config.API.loadFileDocument("เล่ม 2", evaluateId.value, "1-เอกสารเล่ม 2")
    )
    .then((res: any) => {
      downloadUrl.value = res.data.downloadUrl;
    })
    .finally(() => {
      const ref = {
        downloadFile: [downloadUrl.value],
      };

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

// function getCommander() {
//   http
//     .get(config.API.searchCommander)
//     .then((res) => {
//       const data = res.data.result;
//       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) => {
//       messageError($q, e);
//     });
// }

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

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

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

/** hook lifecycle*/
onMounted(async () => {
  const user = await tokenParsed();
  if (user) {
    formCommand.author = user.name;
  }
  checkDoc();
  if (store.currentStep >= 6) {
    fetcheSigner(evaluateId.value);
  }
  await fetchCheckDate();
});
</script>

<template>
  <div class="row col-12 q-pa-sm">
    <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 q-pa-sm">
            <div class="row q-col-gutter-sm">
              <div class="col-12 row q-col-gutter-sm">
                <div class="col-6">
                  <q-input
                    :readonly="store.currentStep != 6 || store.statusUpload6"
                    dense
                    outlined
                    v-model="formCommand.author"
                    @update:model-value="updateInput(formCommand)"
                    label="เจ้าของผลงาน"
                    hide-bottom-space
                    :rules="[(val:string) => !!val || `${'กรุณากรอกเจ้าของผลงาน'}`]"
                    lazy-rules
                  />
                </div>
                <div class="col-3">
                  <q-input
                    :readonly="store.currentStep != 6 || store.statusUpload6"
                    class="col-xs-12 col-sm-6"
                    dense
                    outlined
                    v-model="formCommand.assignedPosition"
                    @update:model-value="updateInput(formCommand)"
                    label="ตำแหน่งที่ได้รับ"
                    hide-bottom-space
                    :rules="[
                    (val:string) => !!val || `${'กรุณากรอกตำแหน่งที่ได้รับ'}`,
                  ]"
                    lazy-rules
                  />
                </div>
                <div class="col-3">
                  <q-input
                    readonly
                    class="col-xs-12 col-sm-6"
                    dense
                    outlined
                    v-model="assignedPosLevel"
                    label="ระดับตำแหน่งที่ได้รับ"
                    hide-bottom-space
                  />
                </div>
              </div>

              <div
                class="col-12"
                v-if="store.currentStep === 6 && !store.statusUpload6"
              >
                <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 != 6 || store.statusUpload6"
                    dense
                    outlined
                    label="ชื่อผลงาน"
                    v-model="formCommand.subject[index]"
                    @update:model-value="updateInput(formCommand)"
                    :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อผลงาน'}`]"
                    hide-bottom-space
                    lazy-rules
                  />
                </div>
                <div
                  class="row col-1 items-centet justify-center"
                  v-if="index !== 0"
                >
                  <q-btn
                    v-if="store.currentStep === 6 && !store.statusUpload6"
                    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-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 || store.statusUpload6"
                    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 != 6 || store.statusUpload6
                        "
                        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 != 6 || store.statusUpload6
                        "
                        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 != 6 || store.statusUpload6
                        "
                        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 != 6 || store.statusUpload6
                        "
                        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">
              <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 || store.statusUpload6"
                    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 != 6 || store.statusUpload6
                        "
                        class="col-xs-6 col-sm-6"
                        dense
                        outlined
                        v-model="formCommand.commanderAbovePosition"
                        label="ตำแหน่ง"
                        :rules="[(val:string) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
                        lazy-rules
                        @update:model-value="updateInput(formCommand)"
                        hide-bottom-space
                      />
                      <q-input
                        :readonly="
                          store.currentStep != 6 || store.statusUpload6
                        "
                        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 != 6 || store.statusUpload6
                        "
                        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 != 6 || store.statusUpload6
                        "
                        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>

      <!-- อัปไฟล์ -->
      <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">
                  <q-file
                    :disable="!store.statusUpload6"
                    v-model="fileEvaluation1"
                    class="col-12"
                    outlined
                    hide-bottom-space
                    dense
                    lazy-rules
                    label="อัปโหลดไฟล์"
                    accept=".pdf"
                    :rules="
                      downloadUrl === ''
                        ? [(val:any) => !!val || 'กรุณาเลือกไฟล์']
                        : []
                    "
                  >
                    <template v-slot:prepend>
                      <q-icon name="attach_file" />
                    </template>
                    <template v-slot:after>
                      <div>
                        <q-btn
                          :disable="!store.statusUpload6"
                          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>
