<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useQuasar } from "quasar";
import type { FormRef } from "@/modules/05_leave/interface/request/BirthForm";
import { useCounterMixin } from "@/stores/mixin";
import { useLeaveStore } from "@/modules/05_leave/store";
import http from "@/plugins/http";
import config from "@/app.config";
import { useRouter } from "vue-router";

/** Use */
const dataStore = useLeaveStore();
const mixin = useCounterMixin();
const router = useRouter();
const $q = useQuasar();
const { date2Thai, dateToISO, dialogConfirm, success, messageError, fails } =
  mixin;
const edit = ref<boolean>(true);

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

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

/** ตัวแปร ref สำหรับแสดง validate */
const leaveWroteRef = ref<object | null>(null);
const leaveStartDateRef = ref<object | null>(null);
const leaveEndDateRef = ref<object | null>(null);
const leaveTotalRef = ref<object | null>(null);
const leaveNumberRef = ref<object | null>(null);
const leaveAddressRef = 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,
  leaveTotal: leaveTotalRef,
  leaveNumber: leaveNumberRef,
  leaveAddress: leaveAddressRef,
  leaveDetail: leaveDetailRef,
  leaveDocument: leaveDocumentRef,
};

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

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
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 (formDataBirth.leaveDocument.length > 0) {
    // 	const blob = formDataBirth.leaveDocument.slice(0, formDataBirth.leaveDocument[0].size)
    // 	const newFile = new File(blob, nameFile.value, {
    // 		type: formDataBirth.leaveDocument[0].type,
    // 	})
    // 	formData.append("leaveDocument", newFile)
    // }
    formData.append("leaveDocument", formDataBirth.leaveDocument);
    formData.append("type", formDataBirth.type);
    formData.append("leaveStartDate", dateToISO(formDataBirth.leaveStartDate));
    formData.append("leaveEndDate", dateToISO(formDataBirth.leaveEndDate));
    formData.append("leaveWrote", formDataBirth.leaveWrote);
    formData.append("leaveAddress", formDataBirth.leaveAddress);
    formData.append("leaveNumber", formDataBirth.leaveNumber);
    formData.append("leaveDetail", formDataBirth.leaveDetail);

    props.onSubmit(formData);
  }
}

/**
 * check ว่าลาได้ไหม จาก api
 * @param formData
 */
const isLeave = ref<boolean>(true);
async function fetchCheck() {
  await http
    .post(config.API.leaveCheck(), {
      type: dataStore.typeId ?? null,
      StartLeaveDate: formDataBirth.leaveStartDate ?? null,
      EndLeaveDate: formDataBirth.leaveEndDate ?? null,
    })
    .then((res: any) => {
      const data = res.data.result;
      isLeave.value = data.isLeave;
      if (data.isLeave === true) {
        formDataBirth.leaveTotal = data.totalDate;
        // formDataBirth.leaveLast = data.sumDateWork
      } else {
        fails($q, "ไม่สามารถลาได้");
      }
    })
    .catch((e: any) => {
      messageError($q, e);
    });
}

/** ตรวจสอบว่ามีการส่งข้อมูลเข้ามาที่ฟอร์มไหม เมื่อมีการส่งจะ map ข้อมูลเข้า v-model ของฟอร์ม */
onMounted(() => {
  if (props.data) {
    formDataBirth.leaveWrote = props.data.leaveWrote;
    formDataBirth.leaveStartDate = props.data.leaveStartDate;
    formDataBirth.leaveEndDate = props.data.leaveEndDate;
    formDataBirth.leaveTotal = props.data.leaveTotal;
    formDataBirth.leaveNumber = props.data.leaveNumber;
    formDataBirth.leaveAddress = props.data.leaveAddress;
    formDataBirth.leaveDetail = props.data.leaveDetail;
    // formDataBirth.leaveDocument = props.data.leaveDocument;
  }
});
</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">
        <q-input
          class="col-12 col-sm-12 cursor-pointer inputgreen"
          ref="leaveWroteRef"
          for="leaveWroteRef"
          dense
          outlined
          v-model="formDataBirth.leaveWrote"
          label="เขียนที่"
          hide-bottom-space
          bg-color="white"
          :readonly="!edit"
          :rules="[(val) => !!val || `${'เขียนที่'}`]"
        />

        <datepicker
          class="col-12 col-md-3 col-sm-12 cursor-pointer inputgreen"
          menu-class-name="modalfix"
          v-model="formDataBirth.leaveStartDate"
          :locale="'th'"
          autoApply
          hide-bottom-space
          borderless
          :enableTimePicker="false"
          week-start="0"
          :readonly="!edit"
          @update:model-value="formDataBirth.leaveEndDate = null"
        >
          <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"
              class="full-width datepicker"
              :model-value="
                formDataBirth.leaveStartDate != null
                  ? date2Thai(formDataBirth.leaveStartDate)
                  : null
              "
              :label="`${'ลาตั้งแต่วันที่'}`"
              :rules="[(val) => !!val || `${'กรุณาเลือกลาตั้งแต่วันที่'}`]"
            >
              <template v-slot:prepend>
                <q-icon
                  name="event"
                  class="cursor-pointer"
                  style="color: var(--q-primary)"
                >
                </q-icon>
              </template>
            </q-input>
          </template>
        </datepicker>

        <datepicker
          class="col-12 col-md-3 col-sm-12 cursor-pointer inputgreen"
          menu-class-name="modalfix"
          v-model="formDataBirth.leaveEndDate"
          :locale="'th'"
          autoApply
          @update:model-value="fetchCheck()"
          borderless
          hide-bottom-space
          :enableTimePicker="false"
          week-start="0"
          :readonly="!formDataBirth.leaveStartDate"
          :min-date="formDataBirth.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"
              :readonly="!formDataBirth.leaveStartDate"
              class="full-width datepicker"
              :model-value="
                formDataBirth.leaveEndDate != null
                  ? date2Thai(formDataBirth.leaveEndDate)
                  : null
              "
              :label="`${'ลาถึงวันที่'}`"
              :rules="[(val) => !!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-3 col-sm-6"
          dense
          outlined
          ref="leaveTotalRef"
          for="leaveTotalRef"
          v-model="formDataBirth.leaveTotal"
          label="จำนวนวันที่ลา"
          bg-color="white"
          readonly
          hide-bottom-space
        />
        <q-input
          class="col-12 col-md-3 col-sm-6"
          dense
          outlined
          ref="leaveLastRef"
          for="leaveLastRef"
          v-model="dataStore.leaveLast"
          label="ลาครั้งสุดท้ายเมื่อวันที่"
          readonly
          hide-bottom-space
          bg-color="white"
        />
        <div class="full-width">
          <div class="q-col-gutter-sm row">
            <q-input
              class="col-12 col-md-3 col-sm-12 cursor-pointer inputgreen"
              dense
              outlined
              hide-bottom-space
              bg-color="white"
              ref="leaveNumberRef"
              for="leaveNumberRef"
              v-model="formDataBirth.leaveNumber"
              mask="(###)-###-####"
              unmasked-value
              label="หมายเลขโทรศัพท์ที่ติดต่อได้"
              :readonly="!edit"
              :rules="[
                (val) => !!val || `${'กรุณากรอกหมายเลขโทรศัพท์ที่ติดต่อได้'}`,
              ]"
            />

            <q-input
              class="col-12 col-md-9 col-sm-12 cursor-pointer inputgreen"
              dense
              outlined
              hide-bottom-space
              bg-color="white"
              ref="leaveAddressRef"
              for="leaveAddressRef"
              v-model="formDataBirth.leaveAddress"
              label="ที่อยู่ที่ติดต่อได้ระหว่างลา"
              :readonly="!edit"
              :rules="[
                (val) => !!val || `${'กรุณากรอกที่อยู่ที่ติดต่อได้ระหว่างลา'}`,
              ]"
            />
          </div>
        </div>
        <q-input
          type="textarea"
          class="col-12 col-md-12 col-sm-12 cursor-pointer inputgreen"
          dense
          outlined
          bg-color="white"
          ref="leaveDetailRef"
          for="leaveDetailRef"
          v-model="formDataBirth.leaveDetail"
          label="รายละเอียด"
          :readonly="!edit"
        />

        <!-- multiple -->
        <q-file
          for="leaveDocumentRef"
          hide-bottom-space
          v-model="formDataBirth.leaveDocument"
          @added="fileUploadDoc"
          dense
          bg-color="white"
          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 class="col-12 row" v-if="!edit">
          <div class="bg-grey-1 q-pa-sm col-12 row items-center text-primary">
            <div class="q-pl-sm text-weight-bold text-dark">
              เอกสารเพิ่มเติม
            </div>
          </div>
          <q-card bordered flat class="full-width">
            <q-list separator>
              <q-item
                v-for="(file, index) in formDataBirth.leaveDocument"
                :key="index"
                class="q-my-xs"
              >
                <q-item-section>
                  <q-item-label class="full-width ellipsis">
                    {{ file.name }}
                  </q-item-label>
                  <q-item-label caption> </q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
          </q-card>
        </div>
      </div>
    </q-card>

    <q-separator class="q-mt-sm" />

    <div class="row col-12 q-pt-md">
      <q-space />
      <q-btn
        v-if="!props.data || props.data.status == 'DRAFT'"
        id="onSubmit"
        type="submit"
        unelevated
        dense
        class="q-px-md items-center btnBlue"
        label="บันทึก"
        ><q-tooltip>บันทึกแบบร่าง</q-tooltip></q-btn
      >
      <q-btn
        v-if="data"
        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>
