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

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

import type { MilitaryForm } from "@/modules/05_leave/interface/request/AddAbsence";

/** Use */
const dataStore = useLeaveStore();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  calculateDurationYmd,
  dateToISO,
  messageError,
  convertDateToAPI,
  showLoader,
  hideLoader,
} = mixin;
const edit = ref<boolean>(true);
const leaveId = ref<string>("");
const leaveText = ref<string>("");
/** ตัวแปร ref สำหรับแสดง validate */
const leaveStartDateRef = ref<object | null>(null);
const leaveEndDateRef = ref<object | null>(null);
const leaveWroteRef = ref<object | null>(null);
const absentDaySummonRef = ref<object | null>(null);
const absentDayLocationRef = ref<object | null>(null);
const absentDayRegistorDateRef = ref<object | null>(null);
const absentDayGetInRef = ref<object | null>(null);
const absentDayAtRef = ref<object | null>(null);
const leaveDetailRef = ref<object | null>(null);

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

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

const isLeave = ref<boolean>(true);
const fileDocDataUpload = ref<File[]>([]);
const fileUploadDoc = async (files: any) => {
  files.forEach((file: any) => {
    fileDocDataUpload.value.push(file);
  });
};

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

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

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const formRef: MilitaryForm = {
  leaveStartDate: leaveStartDateRef,
  leaveEndDate: leaveEndDateRef,
  leaveWrote: leaveWroteRef,
  absentDaySummon: absentDaySummonRef,
  absentDayLocation: absentDayLocationRef,
  absentDayRegistorDate: absentDayRegistorDateRef,
  absentDayGetIn: absentDayGetInRef,
  absentDayAt: absentDayAtRef,
  leaveDetail: leaveDetailRef,
};

/** ฟังก์ชั่นตรวจสอบความถูกต้องก่อน บันทึก */
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);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    const formData = new FormData();
    if (formDataMilitary.leaveDocument) {
      formDataMilitary.leaveDocument.forEach((file: File) => {
        formData.append("leaveDocument", file);
      });
    }
    // formData.append("leaveDocument", formDataMilitary.leaveDocument);
    formData.append("type", formDataMilitary.type);
    formData.append(
      "leaveStartDate",
      convertDateToAPI(formDataMilitary.leaveStartDate) ?? ""
    );
    formData.append(
      "leaveEndDate",
      convertDateToAPI(formDataMilitary.leaveEndDate) ?? ""
    );
    formData.append("absentDaySummon", formDataMilitary.absentDaySummon);
    formData.append("absentDayLocation", formDataMilitary.absentDayLocation);
    formData.append(
      "absentDayRegistorDate",
      convertDateToAPI(formDataMilitary.absentDayRegistorDate) ?? ""
    );
    formData.append("absentDayGetIn", formDataMilitary.absentDayGetIn);
    formData.append("absentDayAt", formDataMilitary.absentDayAt);
    formData.append("leaveWrote", formDataMilitary.leaveWrote);
    formData.append("leaveDetail", formDataMilitary.leaveDetail);
    formData.append("leaveTotal", formDataMilitary.leaveTotal);

    formData.append("leaveRange", formDataMilitary.leaveRange);
    formData.append("leaveRangeEnd", formDataMilitary.leaveRangeEnd);
    props.onSubmit(formData, isLeave.value);
  }
}
const reasonLeave = ref<string>("");

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

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

        hideLoader();
      })
      .catch((e: any) => {
        messageError($q, e);
        // totalCheck.value = null
        hideLoader();
      });
  }
}

// /**
//  * function อัพเดทค่า LeaveTotal
//  */
// function updateLeaveTotal() {
//   const newLeaveTotal = calculateDurationYmd(
//     formDataMilitary.leaveStartDate,
//     formDataMilitary.leaveEndDate
//   );
//   formDataMilitary.leaveTotal = newLeaveTotal;
// }

watch(
  () => props.data,
  async () => {
    if (props.data) {
      // totalCheck.value = null;
      formDataMilitary.leaveWrote = props.data.leaveWrote;
      formDataMilitary.leaveStartDate = props.data.leaveStartDate;
      formDataMilitary.leaveEndDate = props.data.leaveEndDate;
      formDataMilitary.leaveTotal = props.data.leaveTotal;
      formDataMilitary.absentDaySummon = props.data.absentDaySummon;
      formDataMilitary.absentDayLocation = props.data.absentDayLocation;
      formDataMilitary.absentDayRegistorDate = props.data.absentDayRegistorDate;
      formDataMilitary.absentDayGetIn = props.data.absentDayGetIn;
      formDataMilitary.absentDayAt = props.data.absentDayAt;
      formDataMilitary.leaveRange = props.data.leaveRange;
      formDataMilitary.leaveRangeEnd = props.data.leaveRangeEnd;
      const leaveTotal = await calculateDurationYmd(
        props.data.leaveStartDate,
        props.data.leaveEndDate
      );
      leaveText.value = leaveTotal;
      formDataMilitary.leaveDetail = props.data.leaveDetail;
      leaveDocumentList.value = props.data.leaveDocument;
      statusCheck.value = props.data.status;
      formDataMilitary.leaveDocument = [];
    }
  }
);

/**Hook */
onMounted(async () => {
  if (props.data) {
    // totalCheck.value = null;
    formDataMilitary.leaveWrote = props.data.leaveWrote;
    formDataMilitary.leaveStartDate = props.data.leaveStartDate;
    formDataMilitary.leaveEndDate = props.data.leaveEndDate;
    formDataMilitary.leaveTotal = props.data.leaveTotal;
    formDataMilitary.absentDaySummon = props.data.absentDaySummon;
    formDataMilitary.absentDayLocation = props.data.absentDayLocation;
    formDataMilitary.absentDayRegistorDate = props.data.absentDayRegistorDate;
    formDataMilitary.absentDayGetIn = props.data.absentDayGetIn;
    formDataMilitary.absentDayAt = props.data.absentDayAt;
    formDataMilitary.leaveDetail = props.data.leaveDetail;

    formDataMilitary.leaveRange = props.data.leaveRange;
    formDataMilitary.leaveRangeEnd = props.data.leaveRangeEnd;
    const leaveTotal = await calculateDurationYmd(
      props.data.leaveStartDate,
      props.data.leaveEndDate
    );
    leaveText.value = leaveTotal;
    leaveDocumentList.value = props.data.leaveDocument;
    statusCheck.value = props.data.status;
    leaveId.value = props.data.id;
  }
});
</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="onValidate">
    <q-card bordered class="q-pa-md bg-grey-1">
      <div class="row q-pa-sm q-col-gutter-sm">
        <div class="col-12 inputgreen">
          <q-input
            ref="leaveWroteRef"
            dense
            outlined
            bg-color="white"
            hide-bottom-space
            v-model="formDataMilitary.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="formDataMilitary.leaveStartDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="!edit || statusCheck === 'NEW'"
                @update:model-value="
                  (formDataMilitary.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="
                      formDataMilitary.leaveStartDate != null
                        ? date2Thai(formDataMilitary.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-sm-3 inputgreen">
              <q-select
                outlined
                dense
                bg-color="white"
                v-model="formDataMilitary.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="formDataMilitary.leaveEndDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                @update:model-value="fetchCheck()"
                borderless
                :enableTimePicker="false"
                week-start="0"
                :min-date="formDataMilitary.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="
                      formDataMilitary.leaveEndDate != null
                        ? date2Thai(formDataMilitary.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-sm-3 inputgreen">
              <q-select
                v-if="!checkDate"
                outlined
                dense
                bg-color="white"
                v-model="formDataMilitary.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>
        </div>

        <div class="full-width">
          <div class="q-col-gutter-sm row"> -->
            <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">
          <div class="row q-col-gutter-sm">
            <div class="col-12 col-md-8 col-sm-6 inputgreen">
              <q-input
                ref="absentDaySummonRef"
                dense
                bg-color="white"
                outlined
                v-model="formDataMilitary.absentDaySummon"
                label="ได้รับหมายเรียกของ"
                hide-bottom-space
                :readonly="!edit || statusCheck === 'NEW'"
                :rules="[(val:string) => !!val || `${'กรุณากรอกได้รับหมายเรียกของ'}`]"
              />
            </div>

            <div class="col-12 col-md-4 col-sm-6 inputgreen">
              <q-input
                ref="atRef"
                dense
                bg-color="white"
                outlined
                v-model="formDataMilitary.absentDayLocation"
                label="ที่"
                hide-bottom-space
                :readonly="!edit || statusCheck === 'NEW'"
                :rules="[(val:string) => !!val || `${'กรุณากรอกที่'}`]"
              />
            </div>
          </div>
        </div>

        <div class="full-width">
          <div class="q-col-gutter-sm row">
            <datepicker
              class="col-12 col-md-4 col-sm-6 inputgreen"
              v-model="formDataMilitary.absentDayRegistorDate"
              :locale="'th'"
              autoApply
              borderless
              :readonly="!edit || statusCheck === 'NEW'"
              :enableTimePicker="false"
              week-start="0"
            >
              <template #year="{ year }">
                {{ year + 543 }}
              </template>
              <template #year-overlay-value="{ value }">
                {{ parseInt(value + 543) }}
              </template>
              <template #trigger>
                <q-input
                  outlined
                  dense
                  ref="absentDayRegistorDateRef"
                  bg-color="white"
                  hide-bottom-space
                  :readonly="!edit || statusCheck === 'NEW'"
                  class="full-width datepicker"
                  :model-value="
                    formDataMilitary.absentDayRegistorDate != null
                      ? date2Thai(formDataMilitary.absentDayRegistorDate)
                      : 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>

            <q-input
              class="col-12 col-md-4 col-sm-6 inputgreen"
              dense
              bg-color="white"
              ref="absentDayGetInRef"
              outlined
              v-model="formDataMilitary.absentDayGetIn"
              label="ให้เข้ารับการ"
              hide-bottom-space
              :readonly="!edit || statusCheck === 'NEW'"
              :rules="[(val:string) => !!val || `${'กรุณากรอกให้เข้ารับการ'}`]"
            />

            <q-input
              class="col-12 col-md-4 col-sm-12 inputgreen"
              dense
              bg-color="white"
              outlined
              ref="absentDayAtRef"
              v-model="formDataMilitary.absentDayAt"
              label="ณ ที่"
              hide-bottom-space
              :readonly="!edit || statusCheck === 'NEW'"
              :rules="[(val:string) => !!val || `${'กรุณากรอก ณ ที่'}`]"
            />
          </div>
        </div>

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

        <div class="col-12" v-if="statusCheck != 'NEW'">
          <!-- multiple -->
          <q-file
            v-model="formDataMilitary.leaveDocument"
            multiple
            dense
            label="เอกสารประกอบ"
            outlined
            bg-color="white"
            hide-bottom-space
            use-chips
            @added="fileUploadDoc"
          >
            <template v-slot:prepend>
              <q-icon name="attach_file" color="primary" />
            </template>
          </q-file>
          <div class="col-12 q-mt-sm" 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>
      </div>
    </q-card>
    <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>
  </form>
</template>
