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

import http from "@/plugins/http";
import config from "@/app.config";
import genReport from "@/plugins/genreport";
import { useCounterMixin } from "@/stores/mixin";
import { useLeaveStore } from "@/modules/05_leave/store";

import type { FormRef } from "@/modules/05_leave/interface/request/WorkInternationalForm";

/** Use */
const $q = useQuasar();
const dataStore = useLeaveStore();
const mixin = useCounterMixin();
const {
  date2Thai,
  calculateDurationYmd,
  messageError,
  showLoader,
  hideLoader,
  convertDateToAPI,
} = mixin;

const edit = ref<boolean>(true);
const isSave = ref<boolean>(false);
const leaveId = ref<string>("");
const leaveText = ref<string>("");

/** รับ props มาจากหน้าหลัก */
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
  onConfirm: {
    type: Function,
    default: () => "",
  },
  clickDelete: {
    type: Function,
    default: () => "",
  },
});

/** ข้อมูล v-model ของฟอร์ม */
const formDataWorkInternational = reactive<any>({
  type: dataStore.typeId,
  leaveWrote: "",
  leaveStartDate: null,
  leaveEndDate: null,
  leaveDetail: "",
  leaveRange: "ALL",
  leaveRangeEnd: "ALL",
  leaveDocument: [],
  leaveDraftDocument: null,
});

/** ตัวแปร ref สำหรับแสดง validate */
const leaveWroteRef = ref<object | null>(null);
const leaveStartDateRef = ref<object | null>(null);
const leaveEndDateRef = ref<object | null>(null);
const leaveDetailRef = ref<object | null>(null);
const leaveDocumentRef = ref<object | null>(null);

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const FormRef: FormRef = {
  leaveWrote: leaveWroteRef,
  leaveStartDate: leaveStartDateRef,
  leaveEndDate: leaveEndDateRef,
  leaveDetail: leaveDetailRef,
  leaveDocument: leaveDocumentRef,
};

/** ส่วนของการประกาศและเลือกไฟล์เอกสารประกอบ */
const nameFile = ref<string>("");
const nameFileDraft = ref<string>("");
const fileDocDataUpload = ref<File[]>([]);
const fileUploadDoc = async (files: any) => {
  files.forEach((file: any) => {
    fileDocDataUpload.value.push(file);
  });
};

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
async function onValidate() {
  const hasError = [];
  for (const key in FormRef) {
    if (Object.prototype.hasOwnProperty.call(FormRef, key)) {
      const property = FormRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  // ถ้า Validate ผ่านให้บันทึกข้อมูล
  if (hasError.every((result) => result === true)) {
    const formData = new FormData();

    if (formDataWorkInternational.leaveDocument.length > 0) {
      formDataWorkInternational.leaveDocument.forEach((file: File) => {
        formData.append("leaveDocument", file);
      });
    }

    if (formDataWorkInternational.leaveDraftDocument) {
      formData.append(
        "leaveDraftDocument",
        formDataWorkInternational.leaveDraftDocument
      );
    }
    formData.append("type", formDataWorkInternational.type); //
    formData.append(
      "leaveStartDate",
      convertDateToAPI(formDataWorkInternational.leaveStartDate) ?? ""
    ); //
    formData.append(
      "leaveEndDate",
      convertDateToAPI(formDataWorkInternational.leaveEndDate) ?? ""
    ); //
    formData.append("leaveWrote", formDataWorkInternational.leaveWrote); //
    formData.append("leaveDetail", formDataWorkInternational.leaveDetail);
    formData.append("leaveTotal", formDataWorkInternational.leaveTotal); //

    formData.append("leaveRange", formDataWorkInternational.leaveRange);
    formData.append("leaveRangeEnd", formDataWorkInternational.leaveRangeEnd);

    await props.onSubmit(formData, isLeave.value);
  }
}

//download function
async function onClickDownloadFile(id: string, fileName: string) {
  showLoader();
  await http
    .get(config.API.leaveReport(id))
    .then(async (res) => {
      const data = res.data.result;
      await genReport(data, fileName);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const reasonLeave = ref<string>("");

const checkDate = computed(() => {
  if (
    convertDateToAPI(formDataWorkInternational.leaveEndDate) ==
    convertDateToAPI(formDataWorkInternational.leaveStartDate)
  ) {
    return true;
  } else {
    return false;
  }
});

/**
 * check ว่าลาได้ไหม จาก api
 * @param formData
 */
const isLeave = ref<boolean>(true);
// const totalCheck = ref<number|null>(null)
async function fetchCheck() {
  if (
    formDataWorkInternational.leaveStartDate &&
    formDataWorkInternational.leaveEndDate
  ) {
    await http
      .post(config.API.leaveCheck(), {
        type: dataStore.typeId ?? null,
        StartLeaveDate:
          convertDateToAPI(formDataWorkInternational.leaveStartDate) ?? null,
        EndLeaveDate:
          convertDateToAPI(formDataWorkInternational.leaveEndDate) ?? null,
        leaveRange: formDataWorkInternational.leaveRange,
        leaveRangeEnd: checkDate.value
          ? formDataWorkInternational.leaveRange
          : formDataWorkInternational.leaveRangeEnd,
      })
      .then((res: any) => {
        const data = res.data.result;
        isLeave.value = data.isLeave;
        formDataWorkInternational.leaveTotal = data.totalDate;
        // totalCheck.value = data.totalDate;
        leaveText.value = calculateDurationYmd(
          convertDateToAPI(formDataWorkInternational.leaveStartDate),
          convertDateToAPI(formDataWorkInternational.leaveEndDate)
        );
        reasonLeave.value = data.message
          ? data.message
          : "จำนวนวันลาเกินที่กำหนด";
      })
      .catch((e: any) => {
        // totalCheck.value = null;
        messageError($q, e);
      });
  }
}

/** แจ้งเมื่อวันลาไม่ถูกต้อง */
const dateEndInputStyle = computed(() => {
  return !isLeave.value ? "input-alert" : "";
});

/** ตรวจสอบว่ามีการส่งข้อมูลเข้ามาที่ฟอร์มไหม เมื่อมีการส่งจะ map ข้อมูลเข้า v-model ของฟอร์ม */
const leaveDocumentList = ref<any>();
const leaveDraftDocument = ref<string>();
const statusCheck = ref<string>("");

watch(
  () => props,
  async () => {
    if (props.data) {
      // totalCheck.value = null;
      formDataWorkInternational.leaveWrote = props.data.leaveWrote;
      formDataWorkInternational.leaveStartDate = new Date(
        props.data.leaveStartDate
      );
      formDataWorkInternational.leaveEndDate = new Date(
        props.data.leaveEndDate
      );
      formDataWorkInternational.leaveDetail = props.data.leaveDetail;
      leaveDraftDocument.value = props.data.leaveDraftDocument;
      formDataWorkInternational.leaveRange = props.data.leaveRange;
      formDataWorkInternational.leaveRangeEnd = props.data.leaveRangeEnd;
      formDataWorkInternational.leaveTotal = props.data.leaveTotal;
      leaveDocumentList.value = props.data.leaveDocument;
      statusCheck.value = props.data.status;
      formDataWorkInternational.leaveDraftDocument = null;
      formDataWorkInternational.leaveDocument = [];
      const leaveTotal = await calculateDurationYmd(
        props.data.leaveStartDate,
        props.data.leaveEndDate
      );
      leaveText.value = leaveTotal;
    }
  }
);

watch(
  () => formDataWorkInternational.leaveEndDate,
  () => {
    if (
      formDataWorkInternational.leaveStartDate !== null &&
      formDataWorkInternational.leaveEndDate !== null
    ) {
      fetchCheck();
    }
  }
);

/**Hook */
onMounted(async () => {
  if (props.data) {
    // totalCheck.value = null;
    formDataWorkInternational.leaveWrote = props.data.leaveWrote;

    formDataWorkInternational.leaveRange = props.data.leaveRange;
    formDataWorkInternational.leaveRangeEnd = props.data.leaveRangeEnd;
    formDataWorkInternational.leaveTotal = props.data.leaveTotal;

    formDataWorkInternational.leaveStartDate = new Date(
      props.data.leaveStartDate
    );
    formDataWorkInternational.leaveEndDate = new Date(props.data.leaveEndDate);
    formDataWorkInternational.leaveDetail = props.data.leaveDetail;
    leaveDraftDocument.value = props.data.leaveDraftDocument;
    leaveDocumentList.value = props.data.leaveDocument;
    statusCheck.value = props.data.status;
    leaveId.value = props.data.id;
    const leaveTotal = await calculateDurationYmd(
      props.data.leaveStartDate,
      props.data.leaveEndDate
    );
    leaveText.value = leaveTotal;
  }
});
</script>

<template>
  <div style="display: flex; align-items: center">
    <q-icon name="mdi-numeric-3-circle" size="20px" color="primary" />
    <div class="q-pl-sm text-weight-bold text-dark">กรอกข้อมูล</div>
  </div>
  <form @submit.prevent.stop="onValidate">
    <q-card bordered class="q-pa-md bg-grey-1">
      <div class="col-12 row q-pa-sm q-col-gutter-sm">
        <div class="col-12 inputgreen">
          <q-input
            ref="leaveWroteRef"
            hide-bottom-space
            bg-color="white"
            for="leaveWroteRef"
            dense
            outlined
            v-model="formDataWorkInternational.leaveWrote"
            label="เขียนที่"
            :readonly="!edit || statusCheck === 'NEW'"
            :rules="[(val:string) => !!val || `${'เขียนที่'}`]"
          />
        </div>

        <div class="col-12">
          <div class="row q-col-gutter-sm">
            <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <datepicker
                v-model="formDataWorkInternational.leaveStartDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="!edit || statusCheck === 'NEW'"
                @update:model-value="
                  (formDataWorkInternational.leaveEndDate = null), fetchCheck()
                "
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    outlined
                    dense
                    ref="leaveStartDateRef"
                    for="leaveStartDateRef"
                    hide-bottom-space
                    bg-color="white"
                    :readonly="!edit || statusCheck === 'NEW'"
                    class="full-width datepicker"
                    :model-value="
                      formDataWorkInternational.leaveStartDate != null
                        ? date2Thai(formDataWorkInternational.leaveStartDate)
                        : null
                    "
                    :label="`${'วันที่เริ่มต้น'}`"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่เริ่มต้น'}`]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <!-- <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <q-select
                outlined
                dense
                bg-color="white"
                v-model="formDataWorkInternational.leaveRange"
                :options="dataStore.rangeOptions"
                emit-value
                map-options
                option-value="id"
                option-label="name"
                @update:model-value="fetchCheck()"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="mdi-clock-outline"
                    style="color: var(--q-primary)"
                  />
                </template>
              </q-select>
            </div> -->
            <!-- </div>
        </div>
        <div class="col-12">
          <div class="row q-col-gutter-sm"> -->
            <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <datepicker
                v-model="formDataWorkInternational.leaveEndDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                @update:model-value="fetchCheck()"
                borderless
                :enableTimePicker="false"
                week-start="0"
                :min-date="formDataWorkInternational.leaveStartDate"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    outlined
                    dense
                    ref="leaveEndDateRef"
                    for="leaveEndDateRef"
                    hide-bottom-space
                    bg-color="white"
                    class="full-width datepicker"
                    :model-value="
                      formDataWorkInternational.leaveEndDate != null
                        ? date2Thai(formDataWorkInternational.leaveEndDate)
                        : null
                    "
                    :label="`${'วันที่สิ้นสุด'}`"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่สิ้นสุด'}`]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <!-- <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <q-select
                outlined
                dense
                v-if="!checkDate"
                bg-color="white"
                v-model="formDataWorkInternational.leaveRangeEnd"
                :options="dataStore.rangeOptions.filter((items:any)=> items.id !== 'AFTERNOON')"
                emit-value
                map-options
                option-value="id"
                option-label="name"
                @update:model-value="fetchCheck()"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="mdi-clock-outline"
                    style="color: var(--q-primary)"
                  />
                </template>
              </q-select>
            </div> -->

            <div class="col-12 col-md-3 col-sm-6">
              <q-input
                :bottom-slots="!isLeave ? true : false"
                :color="!isLeave ? 'red' : 'black'"
                :bg-color="!isLeave ? 'red-2' : 'white'"
                :border-color="!isLeave ? 'red' : 'gray'"
                :input-class="!isLeave ? dateEndInputStyle : ''"
                dense
                outlined
                ref="leaveTotalRef"
                for="leaveTotalRef"
                v-model="leaveText"
                label="มีกำหนด"
                readonly
              >
                <template v-slot:hint>
                  <span style="color: red">
                    {{ !isLeave ? reasonLeave : "" }}
                  </span>
                </template>
              </q-input>
            </div>
          </div>
        </div>

        <div class="col-12 inputgreen">
          <q-input
            hide-bottom-space
            type="textarea"
            dense
            bg-color="white"
            outlined
            ref="leaveDetailRef"
            for="leaveDetailRef"
            v-model="formDataWorkInternational.leaveDetail"
            label="สาเหตุการลา"
            :readonly="!edit || statusCheck === 'NEW'"
          />
        </div>

        <div class="full-width" v-if="statusCheck != 'NEW'">
          <div class="q-col-gutter-sm row">
            <q-file
              ref="fileRef"
              bg-color="white"
              v-model="formDataWorkInternational.leaveDocument"
              multiple
              @added="fileUploadDoc"
              dense
              label="เอกสารประกอบ"
              outlined
              use-chips
              class="q-pl-sm col-12"
            >
              <template v-slot:prepend>
                <q-icon name="attach_file" color="primary" />
              </template>
            </q-file>
          </div>
        </div>
        <div class="col-12" v-if="data">
          <div class="col-12 col-md-12 col-sm-12">
            <q-card>
              <q-list
                v-if="leaveDocumentList && leaveDocumentList.length > 0"
                separator
              >
                <q-item
                  v-for="(document, index) in leaveDocumentList"
                  :key="index"
                  class="q-my-xs"
                >
                  <q-item-section>
                    <q-item-label class="row items-baseline">
                      <div class="col">
                        {{ "เอกสารแนบที่ " + (index + 1) }}
                      </div>
                      <div>
                        <q-btn
                          :href="document.path"
                          target="_blank"
                          outline
                          flat
                          dense
                          color="blue"
                          icon="mdi-download"
                          size="12px"
                          class="q-mr-md"
                        >
                          <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
                        </q-btn>
                      </div>
                      <div>
                        <q-btn
                          @click="clickDelete(leaveId, document.docId)"
                          target="_blank"
                          outline
                          color="red"
                          flat
                          dense
                          icon="delete"
                          size="12px"
                        >
                          <q-tooltip>ลบไฟล์</q-tooltip>
                        </q-btn>
                      </div>
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-card>
          </div>
        </div>
      </div>
    </q-card>

    <div v-if="data && data.id" class="q-mt-md">
      <div style="display: flex; align-items: center">
        <q-icon name="mdi-numeric-4-circle" size="20px" color="primary" />
        <div class="q-pl-sm text-weight-bold text-dark">
          ดาวน์โหลด/อัปโหลดแบบฟอร์ม
        </div>
      </div>
      <q-card class="bg-grey-1 q-pa-sm" bordered>
        <div class="row">
          <div class="col-sm-3 q-my-sm">
            <div class="column q-mx-xs">
              <q-btn
                color="primary"
                icon="download"
                label="ดาวน์โหลดแบบฟอร์ม"
                @click="
                  onClickDownloadFile(data.id, `แบบฟอร์ม${data.leaveTypeName}`)
                "
              />
            </div>
          </div>
          <div class="col-sm-5 q-my-sm">
            <div class="column q-mx-xs">
              <q-file
                v-model="formDataWorkInternational.leaveDraftDocument"
                use-chips
                dense
                label="อัปโหลดแบบฟอร์ม"
                outlined
                bg-color="white"
                accept="application/pdf"
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" color="primary" />
                </template>
              </q-file>
            </div>
          </div>

          <div v-if="leaveDraftDocument" class="col-sm-2 q-my-sm">
            <div class="column q-mx-xs">
              <!-- <div class="q-pl-sm text-weight-bold text-dark text-center">
                ดูไฟล์อัปโหลด
              </div> -->
              <q-btn
                icon="visibility"
                color="blue"
                label="ดาวน์โหลดไฟล์"
                :href="leaveDraftDocument"
                target="_blank"
              />
            </div>
          </div>
        </div>
      </q-card>
    </div>

    <div v-if="!isSave">
      <q-separator class="q-mt-sm" />
      <div class="row col-12 q-pt-md">
        <q-space />
        <!-- <div v-if="totalCheck == 0" class="text-red q-mr-sm">**จำนวนวันลาของท่านไม่ถูกต้อง หรือวันที่ยื่นลาของท่านตรงกับวันหยุด</div> -->
        <q-btn
          v-if="!props.data || props.data.status == 'DRAFT'"
          id="onSubmit"
          type="submit"
          unelevated
          dense
          class="q-px-md items-center btnBlue"
          label="บันทึก"
          :disable="!isLeave"
          ><q-tooltip>บันทึกแบบร่าง</q-tooltip></q-btn
        >
        <q-btn
          v-if="data && statusCheck != 'NEW'"
          id="onSubmit"
          type="button"
          unelevated
          dense
          class="q-px-md items-center q-ml-sm"
          color="primary"
          label="ยื่นใบลา"
          @click="onConfirm()"
          ><q-tooltip>ยื่นใบลา</q-tooltip></q-btn
        >
      </div>
    </div>
  </form>
</template>
