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

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

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

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

const leaveText = ref<string>("");
const edit = ref<boolean>(true);
const leaveId = 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 formDataHelpWife = reactive<any>({
  type: dataStore.typeId,
  leaveWrote: "",
  wifeDayName: "",
  wifeDayDateBorn: null,
  leaveStartDate: null,
  leaveEndDate: null,
  leaveTotal: "",
  leaveDetail: "",
  leaveRange: "ALL",
  leaveRangeEnd: "ALL",
  leaveDocument: [],
});

/** ตัวแปร ref สำหรับแสดง validate */
const leaveWroteRef = ref<object | null>(null);
const wifeDayNameRef = ref<object | null>(null);
const wifeDayDateBornRef = 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);

const leaveDocumentList = ref<any>();
const statusCheck = ref<any>("");
const isLeave = ref<boolean>(true);
const dateEndInputStyle = computed(() => {
  return !isLeave.value ? "input-alert" : "";
});

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

/** ส่วนของการประกาศและเลือกไฟล์เอกสารประกอบ */
const fileDocDataUpload = ref<File[]>([]);
const fileUploadDoc = async (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 (formDataHelpWife.leaveDocument.length > 0) {
      formDataHelpWife.leaveDocument.forEach((file: File) => {
        formData.append("leaveDocument", file);
      });
    }
    formData.append("type", formDataHelpWife.type);
    formData.append(
      "leaveStartDate",
      convertDateToAPI(formDataHelpWife.leaveStartDate) ?? ""
    );
    formData.append(
      "leaveEndDate",
      convertDateToAPI(formDataHelpWife.leaveEndDate) ?? ""
    );
    formData.append("leaveWrote", formDataHelpWife.leaveWrote);
    formData.append("leaveAddress", dataStore.currentAddress);
    formData.append("leaveNumber", dataStore.telephoneNumber);
    formData.append("leaveDetail", formDataHelpWife.leaveDetail);
    formData.append("wifeDayName", formDataHelpWife.wifeDayName);
    formData.append("leaveRange", formDataHelpWife.leaveRange);
    formData.append("leaveRangeEnd", formDataHelpWife.leaveRangeEnd);
    formData.append(
      "wifeDayDateBorn",
      convertDateToAPI(formDataHelpWife.wifeDayDateBorn) ?? ""
    );
    formData.append("leaveTotal", formDataHelpWife.leaveTotal);

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

const reasonLeave = ref<string>("");
const checkDate = computed(() => {
  if (
    convertDateToAPI(formDataHelpWife.leaveEndDate) ==
    convertDateToAPI(formDataHelpWife.leaveStartDate)
  ) {
    return true;
  } else {
    return false;
  }
});

/**
 * check ว่าลาได้ไหม จาก api
 * @param formData
 */
// const totalCheck = ref<number | null>(null);
async function fetchCheck() {
  if (formDataHelpWife.leaveStartDate && formDataHelpWife.leaveEndDate) {
    showLoader();
    await http
      .post(config.API.leaveCheck(), {
        type: dataStore.typeId ?? null,
        StartLeaveDate:
          convertDateToAPI(formDataHelpWife.leaveStartDate) ?? null,
        EndLeaveDate: convertDateToAPI(formDataHelpWife.leaveEndDate) ?? null,
        leaveRange: formDataHelpWife.leaveRange,
        leaveRangeEnd: checkDate.value
          ? formDataHelpWife.leaveRange
          : formDataHelpWife.leaveRangeEnd,
      })
      .then((res: any) => {
        const data = res.data.result;
        formDataHelpWife.leaveTotal =
          data.totalDate - data.sumDateWork - data.sumDateHoliday;
        // totalCheck.value =
        //   data.totalDate - data.sumDateWork - data.sumDateHoliday;
        reasonLeave.value =
          data.message != ""
            ? data.message
            : formDataHelpWife.leaveTotal > 0
            ? "จำนวนวันลาเกินที่กำหนด"
            : "ช่วงวันลาที่ระบุไม่ถูกต้อง";
        isLeave.value = formDataHelpWife.leaveTotal > 0 ? data.isLeave : false;
        hideLoader();
      })
      .catch((e: any) => {
        messageError($q, e);
        // totalCheck.value = null;
        hideLoader();
      });
  }
}

/** ตรวจสอบว่ามีการส่งข้อมูลเข้ามาที่ฟอร์มไหม เมื่อมีการส่งจะ map ข้อมูลเข้า v-model ของฟอร์ม */

watch(
  () => props.data,
  async () => {
    if (props.data) {
      // totalCheck.value = null;
      formDataHelpWife.leaveWrote = props.data.leaveWrote;
      formDataHelpWife.wifeDayName = props.data.wifeDayName;
      formDataHelpWife.wifeDayDateBorn = props.data.wifeDayDateBorn;
      formDataHelpWife.leaveStartDate = props.data.leaveStartDate;
      formDataHelpWife.leaveEndDate = props.data.leaveEndDate;
      formDataHelpWife.leaveTotal = props.data.leaveTotal;
      formDataHelpWife.leaveRangeEnd = props.data.leaveRangeEnd;
      formDataHelpWife.leaveRange = props.data.leaveRange;
      formDataHelpWife.leaveDetail = props.data.leaveDetail;
      formDataHelpWife.leaveDocument = [];
      leaveDocumentList.value = props.data.leaveDocument;
      statusCheck.value = props.data.status;
    }
  }
);

/**Hook */
onMounted(async () => {
  if (props.data) {
    // totalCheck.value = null;
    formDataHelpWife.leaveWrote = props.data.leaveWrote;
    formDataHelpWife.wifeDayName = props.data.wifeDayName;
    formDataHelpWife.wifeDayDateBorn = props.data.wifeDayDateBorn;
    formDataHelpWife.leaveStartDate = props.data.leaveStartDate;
    formDataHelpWife.leaveEndDate = props.data.leaveEndDate;
    formDataHelpWife.leaveTotal = props.data.leaveTotal;
    formDataHelpWife.leaveDetail = props.data.leaveDetail;
    leaveDocumentList.value = props.data.leaveDocument;
    formDataHelpWife.leaveRange = props.data.leaveRange;
    formDataHelpWife.leaveRangeEnd = props.data.leaveRangeEnd;
    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.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"
            for="leaveWroteRef"
            dense
            outlined
            hide-bottom-space
            bg-color="white"
            v-model="formDataHelpWife.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="formDataHelpWife.leaveStartDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="!edit || statusCheck === 'NEW'"
                @update:model-value="
                  (formDataHelpWife.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="
                      formDataHelpWife.leaveStartDate != null
                        ? date2Thai(formDataHelpWife.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="formDataHelpWife.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="formDataHelpWife.leaveEndDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                @update:model-value="fetchCheck()"
                borderless
                :enableTimePicker="false"
                week-start="0"
                :min-date="formDataHelpWife.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="
                      formDataHelpWife.leaveEndDate != null
                        ? date2Thai(formDataHelpWife.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
                v-if="!checkDate"
                outlined
                dense
                bg-color="white"
                v-model="formDataHelpWife.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="col-12">
          <div class="row q-col-gutter-sm">
            <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <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 : ''"
                class="col-12 col-md-3 col-sm-6"
                dense
                outlined
                ref="leaveTotalRef"
                for="leaveTotalRef"
                v-model="formDataHelpWife.leaveTotal"
                label="จำนวนวันที่ลา (วัน)"
                readonly
              >
                <template v-slot:hint>
                  <span style="color: red">
                    {{ !isLeave ? reasonLeave : "" }}
                  </span>
                </template>
              </q-input>
            </div>
          </div>
        </div>

        <div class="col-12 col-md-8 col-sm-12 inputgreen">
          <q-input
            class="col-12 col-sm-12"
            ref="wifeDayNameRef"
            for="wifeDayNameRef"
            dense
            bg-color="white"
            outlined
            hide-bottom-space
            v-model="formDataHelpWife.wifeDayName"
            label="ชื่อภรรยา"
            :readonly="!edit || statusCheck === 'NEW'"
            :rules="[(val:string) => !!val || `${'ชื่อภรรยา'}`]"
          />
        </div>

        <div class="col-12 col-md-4 col-sm-12 inputgreen">
          <datepicker
            v-model="formDataHelpWife.wifeDayDateBorn"
            :locale="'th'"
            autoApply
            borderless
            hide-bottom-space
            :enableTimePicker="false"
            week-start="0"
            :readonly="!edit || statusCheck === 'NEW'"
          >
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input
                outlined
                dense
                ref="wifeDayDateBornRef"
                for="wifeDayDateBornRef"
                hide-bottom-space
                bg-color="white"
                :readonly="!edit || statusCheck === 'NEW'"
                class="full-width datepicker"
                :model-value="
                  formDataHelpWife.wifeDayDateBorn != null
                    ? date2Thai(formDataHelpWife.wifeDayDateBorn)
                    : 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="full-width">
          <div class="q-col-gutter-sm row">
            <div class="col-12 col-md-3 col-sm-12 inputgreen">
              <q-input
                dense
                outlined
                ref="leaveNumberRef"
                for="leaveNumberRef"
                v-model="dataStore.telephoneNumber"
                mask="(###)-###-####"
                unmasked-value
                hide-bottom-space
                lazy-rules
                bg-color="white"
                label="หมายเลขโทรศัพท์ที่ติดต่อได้"
                :readonly="!edit || statusCheck === 'NEW'"
                :rules="[
                (val:string) => !!val || `${'กรุณากรอกหมายเลขโทรศัพท์ที่ติดต่อได้'}`,
              ]"
              />
            </div>

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

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

        <div class="full-width" v-if="statusCheck != 'NEW'">
          <div class="q-col-gutter-sm row">
            <div class="q-pl-sm col-12">
              <q-file
                bg-color="white"
                ref="leaveDocumentRef"
                v-model="formDataHelpWife.leaveDocument"
                @added="fileUploadDoc"
                dense
                label="เอกสารประกอบ"
                outlined
                use-chips
                multiple
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" color="primary" />
                </template>
              </q-file>
            </div>
          </div>
        </div>
        <div class="col-12" v-if="data">
          <div class="col-12 col-md-12 col-sm-12">
            <q-card>
              <q-list
                separator
                v-if="leaveDocumentList && leaveDocumentList.length > 0"
              >
                <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>

    <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
        :disable="!isLeave"
        class="q-px-md items-center btnBlue"
        label="บันทึก"
        ><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>
