<script setup lang="ts">
import { reactive, ref, computed, onMounted, watch } from "vue";
import { useCounterMixin } from "@/stores/mixin";

import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";
import { useLeaveStore } from "@/modules/05_leave/store";

import type { TrainForm } from "@/modules/05_leave/interface/request/AddAbsence";
import type { DocumentLists } from "@/modules/05_leave/interface/index/main";

/** Use */
const $q = useQuasar();
const dataStore = useLeaveStore();
const mixin = useCounterMixin();
const {
  date2Thai,
  arabicNumberToText,
  calculateDurationYmd,
  messageError,
  convertDateToAPI,
} = 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 formDataTrain = reactive<any>({
  type: dataStore.typeId,
  leaveWrote: "",
  leaveStartDate: null,
  leaveEndDate: null,
  leavebirthDate: new Date(),
  leavegovernmentDate: new Date(),
  leaveSalary: 10000,
  leaveSalaryText: arabicNumberToText(10000),
  studyDayScholarship: "",
  studyDayCountry: "",
  studyDayTrainingSubject: "",
  leaveRange: "ALL",
  leaveRangeEnd: "ALL",
  studyDayTrainingName: "",
  leaveDocument: [],
  leaveDetail: "",
  leaveTotal: "", //จำนวนวันลา
  leaveTotalDay: "", //จำนวนวันลา
});

/** ตัวแปร ref สำหรับแสดง validate */
const leaveStartDateRef = ref<object | null>(null);
const leaveEndDateRef = ref<object | null>(null);
const leavebirthDateRef = ref<object | null>(null);
const leavegovernmentDateRef = ref<object | null>(null);
const leaveNumberRef = ref<object | null>(null);
const leaveAddressRef = ref<object | null>(null);
const studyDayScholarshipRef = ref<object | null>(null);
const studyDayCountryRef = ref<object | null>(null);
const studyDayTrainingSubjectRef = ref<object | null>(null);
const studyDayTrainingNameRef = ref<object | null>(null);
const leaveWroteRef = ref<object | null>(null);

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const formRef: TrainForm = {
  leaveStartDate: leaveStartDateRef,
  leaveEndDate: leaveEndDateRef,
  leavebirthDate: leavebirthDateRef,
  leavegovernmentDate: leavegovernmentDateRef,
  leaveNumber: leaveNumberRef,
  leaveAddress: leaveAddressRef,
  studyDayScholarship: studyDayScholarshipRef,
  studyDayCountry: studyDayCountryRef,
  studyDayTrainingSubject: studyDayTrainingSubjectRef,
  studyDayTrainingName: studyDayTrainingNameRef,
  leaveWrote: leaveWroteRef,
};

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

/** ฟังก์ชั่นตรวจสอบความถูกต้องก่อน บันทึก */
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 (formDataTrain.leaveDocument) {
      formDataTrain.leaveDocument.forEach((file: File) => {
        formData.append("leaveDocument", file);
      });
    }
    formData.append("type", formDataTrain.type); //
    formData.append(
      "leaveStartDate",
      convertDateToAPI(formDataTrain.leaveStartDate) ?? ""
    ); //
    formData.append(
      "leaveEndDate",
      convertDateToAPI(formDataTrain.leaveEndDate) ?? ""
    ); //
    formData.append("studyDayCountry", formDataTrain.studyDayCountry);
    formData.append("studyDayTrainingName", formDataTrain.studyDayTrainingName);
    formData.append(
      "studyDayTrainingSubject",
      formDataTrain.studyDayTrainingSubject
    );
    formData.append("leaveWrote", formDataTrain.leaveWrote); //
    formData.append("leaveDetail", formDataTrain.leaveDetail); //
    formData.append("studyDayScholarship", formDataTrain.studyDayScholarship);
    formData.append("leaveAddress", dataStore.currentAddress); //
    formData.append("leaveNumber", dataStore.telephoneNumber); //
    formData.append("leaveSalaryText", formDataTrain.leaveSalaryText); //
    formData.append("leaveSalary", formDataTrain.leaveSalary); //
    formData.append("leaveTotal", formDataTrain.leaveTotal); //

    formData.append("leaveRange", formDataTrain.leaveRange);
    formData.append("leaveRangeEnd", formDataTrain.leaveRangeEnd);
    props.onSubmit(formData, isLeave.value);
  }
}

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

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

const isLoadCheck = ref<boolean>(false);

async function fetchCheck() {
  if (formDataTrain.leaveStartDate && formDataTrain.leaveEndDate) {
    isLoadCheck.value = true;
    await http
      .post(config.API.leaveCheck(), {
        type: dataStore.typeId ?? null,
        StartLeaveDate: convertDateToAPI(formDataTrain.leaveStartDate) ?? null,
        EndLeaveDate: convertDateToAPI(formDataTrain.leaveEndDate) ?? null,
        leaveRange: formDataTrain.leaveRange,
        leaveRangeEnd: checkDate.value
          ? formDataTrain.leaveRange
          : formDataTrain.leaveRangeEnd,
      })
      .then((res) => {
        const data = res.data.result;
        isLeave.value = data.isLeave;
        formDataTrain.leaveTotal = data.totalDate;

        leaveText.value = calculateDurationYmd(
          convertDateToAPI(formDataTrain.leaveStartDate),
          convertDateToAPI(formDataTrain.leaveEndDate)
        );
        reasonLeave.value = data.message
          ? data.message
          : "จำนวนวันลาเกินที่กำหนด";
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        isLoadCheck.value = false;
      });
  }
}

watch(
  () => props.data,
  async () => {
    if (props.data) {
      formDataTrain.leaveWrote = props.data.leaveWrote;
      formDataTrain.leaveStartDate = props.data.leaveStartDate;
      formDataTrain.leaveEndDate = props.data.leaveEndDate;
      formDataTrain.leaveTotal = props.data.leaveTotal;
      formDataTrain.leavebirthDate = props.data.leavebirthDate;
      formDataTrain.leavegovernmentDate = props.data.leavegovernmentDate;
      formDataTrain.leaveSalary = props.data.leaveSalary;
      formDataTrain.leaveSalaryText = props.data.leaveSalaryText;
      formDataTrain.studyDayScholarship = props.data.studyDayScholarship;
      formDataTrain.studyDayCountry = props.data.studyDayCountry;
      formDataTrain.studyDayTrainingSubject =
        props.data.studyDayTrainingSubject;
      formDataTrain.studyDayTrainingName = props.data.studyDayTrainingName;
      formDataTrain.leaveDetail = props.data.leaveDetail;
      formDataTrain.leaveRange = props.data.leaveRange;
      formDataTrain.leaveRangeEnd = props.data.leaveRangeEnd;
      formDataTrain.leaveDocument = [];
      const leaveTotal = await calculateDurationYmd(
        props.data.leaveStartDate,
        props.data.leaveEndDate
      );
      leaveText.value = leaveTotal;
      leaveDocumentList.value = props.data.leaveDocument;
      statusCheck.value = props.data.status;
    }
  },
  { deep: true }
);

/**Hook */
onMounted(async () => {
  if (props.data) {
    // totalCheck.value = null;
    formDataTrain.leaveWrote = props.data.leaveWrote;
    formDataTrain.leaveStartDate = props.data.leaveStartDate;
    formDataTrain.leaveEndDate = props.data.leaveEndDate;
    formDataTrain.leaveTotal = props.data.leaveTotal;
    formDataTrain.leavebirthDate = props.data.leavebirthDate;
    formDataTrain.leavegovernmentDate = props.data.leavegovernmentDate;
    formDataTrain.leaveSalary = props.data.leaveSalary;
    formDataTrain.leaveSalaryText = props.data.leaveSalaryText;
    formDataTrain.studyDayScholarship = props.data.studyDayScholarship;
    formDataTrain.studyDayCountry = props.data.studyDayCountry;
    formDataTrain.studyDayTrainingSubject = props.data.studyDayTrainingSubject;

    formDataTrain.leaveRange = props.data.leaveRange;
    formDataTrain.leaveRangeEnd = props.data.leaveRangeEnd;

    formDataTrain.studyDayTrainingName = props.data.studyDayTrainingName;
    formDataTrain.leaveDetail = props.data.leaveDetail;
    // formDataTrain.leaveDocument = props.data.leaveDocument;
    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
            v-model="formDataTrain.leaveWrote"
            ref="leaveWroteRef"
            bg-color="white"
            dense
            outlined
            label="เขียนที่"
            :readonly="!edit || statusCheck === 'NEW'"
            hide-bottom-space
            :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="formDataTrain.leaveStartDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="!edit || statusCheck === 'NEW'"
                @update:model-value="
                  (formDataTrain.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="
                      formDataTrain.leaveStartDate != null
                        ? date2Thai(formDataTrain.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="formDataTrain.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="formDataTrain.leaveEndDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                @update:model-value="fetchCheck()"
                borderless
                :enableTimePicker="false"
                week-start="0"
                :min-date="formDataTrain.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="
                      formDataTrain.leaveEndDate != null
                        ? date2Thai(formDataTrain.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="formDataTrain.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
                :loading="isLoadCheck"
              >
                <template v-slot:hint>
                  <span style="color: red">
                    {{ !isLeave ? reasonLeave : "" }}
                  </span>
                </template>
              </q-input>
            </div>
          </div>
        </div>

        <div class="full-width">
          <div class="q-col-gutter-sm row">
            <div class="col-12 col-sm-3">
              <datepicker
                v-model="formDataTrain.leavegovernmentDate"
                autoApply
                borderless
                week-start="0"
                readonly
                :enableTimePicker="false"
                :locale="'th'"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    ref="leavegovernmentDateRef"
                    class="full-width"
                    outlined
                    readonly
                    bg-color="white"
                    dense
                    hide-bottom-space
                    :label="`${'วันที่เข้ารับราชการ'}`"
                    :model-value="
                      dataStore.dateAppoint != null
                        ? date2Thai(dataStore.dateAppoint)
                        : null
                    "
                    :rules="[
                    (val:string) => !!val || `${'กรุณาเลือกวันที่เข้ารับราชการ'}`,
                  ]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--black)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <div class="col-12 col-sm-3">
              <datepicker
                v-model="formDataTrain.leavebirthDate"
                autoApply
                borderless
                readonly
                week-start="0"
                :enableTimePicker="false"
                :locale="'th'"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    ref="leavebirthDateRef"
                    class="full-width"
                    bg-color="white"
                    outlined
                    dense
                    readonly
                    hide-bottom-space
                    :label="`${'วันเดือนปีเกิด'}`"
                    :model-value="
                      dataStore.birthDate != null
                        ? date2Thai(dataStore.birthDate)
                        : null
                    "
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(---black)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <div class="col-12 col-sm-3">
              <q-input
                v-model="dataStore.salary"
                bg-color="white"
                dense
                outlined
                readonly
                label="เงินเดือนปัจจุบัน"
              />
            </div>

            <div class="col-12 col-sm-3">
              <q-input
                v-model="dataStore.salaryText"
                dense
                readonly
                outlined
                bg-color="white"
                label="เงินเดือนปัจจุบัน (ตัวอักษร)"
              />
            </div>
          </div>
        </div>

        <div class="full-width">
          <div class="q-col-gutter-sm row">
            <div class="col-12 col-sm-8 inputgreen">
              <q-input
                v-model="formDataTrain.studyDayTrainingSubject"
                ref="studyDayTrainingSubjectRef"
                bg-color="white"
                dense
                outlined
                label="ด้าน/หลักสูตร"
                hide-bottom-space
                :readonly="!edit || statusCheck === 'NEW'"
                :rules="[(val:string) => !!val || `${'กรุณากรอกด้าน/หลักสูตร'}`]"
              />
            </div>

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

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

            <div class="col-12 col-sm-8 inputgreen">
              <q-input
                v-model="formDataTrain.studyDayScholarship"
                ref="studyDayScholarshipRef"
                bg-color="white"
                dense
                outlined
                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">
            <q-input
              v-model="dataStore.telephoneNumber"
              class="col-12 col-sm-4 inputgreen"
              ref="leaveNumberRef"
              dense
              outlined
              unmasked-value
              hide-bottom-space
              bg-color="white"
              mask="(###)-###-####"
              :readonly="!edit || statusCheck === 'NEW'"
              label="หมายเลขโทรศัพท์ที่ติดต่อได้"
              :rules="[
                (val:string) => !!val || `${'กรุณากรอกหมายเลขโทรศัพท์ที่ติดต่อได้'}`,
              ]"
            />

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

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

        <div class="col-12" v-if="statusCheck != 'NEW'">
          <q-file
            v-model="formDataTrain.leaveDocument"
            bg-color="white"
            multiple
            dense
            outlined
            use-chips
            label="เอกสารประกอบ"
          >
            <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
                  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>
      </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
        class="q-px-md items-center btnBlue"
        label="บันทึก"
        :disable="!isLeave"
        :loading="isLoadCheck"
      >
        <q-tooltip>บันทึกแบบร่าง</q-tooltip>
      </q-btn>
      <q-btn
        v-if="data && statusCheck != 'NEW'"
        id="onSubmit"
        type="button"
        unelevated
        class="q-px-md items-center q-ml-sm"
        color="primary"
        label="ยื่นใบลา"
        @click="onConfirm()"
        :loading="isLoadCheck"
      >
        <q-tooltip>ยื่นใบลา</q-tooltip>
      </q-btn>
    </div>
  </form>
</template>
