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

import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useAbsentLateStore } from "@/modules/04_registryPerson/stores/AbsentLate";
import http from "@/plugins/http";
import config from "@/app.config";

/** import components*/
import DialogHeader from "@/components/DialogHeader.vue";

//use
const $q = useQuasar();
const route = useRoute();
const absentLateStore = useAbsentLateStore();
const {
  showLoader,
  hideLoader,
  messageError,
  success,
  date2Thai,
  convertDateToAPI,
  dialogConfirm,
  pathRegistryEmp,
} = useCounterMixin();

//props
const modal = defineModel<boolean>("modal", { required: true });
const isStatusEdit = defineModel<boolean>("isStatusEdit", { required: true });
const rowId = defineModel<string>("rowId", { required: true });

const props = defineProps<{
  fetchData: () => Promise<void>;
  dataAbsentLate: any;
}>();

const profileId = ref<string>(route.params.id?.toString() ?? ""); //ProfileId
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));

const form = reactive({
  status: "",
  stampDate: new Date(),
  stampType: "FULL_DAY",
  stampAmount: "1.0",
  remark: "",
});

const tittle = computed(() => {
  return isStatusEdit.value
    ? "แก้ไขข้อมูลขาดราชการ/มาสาย"
    : "เพิ่มข้อมูลขาดราชการ/มาสาย";
});

function onSubmit() {
  dialogConfirm($q, async () => {
    try {
      showLoader();
      const payload = {
        ...form,
        stampDate: convertDateToAPI(form.stampDate),
        profileId:
          !isStatusEdit.value && empType.value === ""
            ? profileId.value
            : undefined,
        profileEmployeeId:
          !isStatusEdit.value && empType.value !== ""
            ? profileId.value
            : undefined,
      };
      const method = isStatusEdit.value ? "patch" : "post";
      const url = isStatusEdit.value
        ? config.API.profileAbsentLate(empType.value) + `/${rowId.value}`
        : config.API.profileAbsentLate(empType.value);
      await http[method](url, payload);
      success($q, "บันทึกข้อมูลสำเร็จ");
      props.fetchData();
      closeDialog();
    } catch (error) {
      messageError($q, error);
    } finally {
      hideLoader();
    }
  });
}

/** function ปิด popup*/
function closeDialog() {
  modal.value = false;
}

watch(
  () => form.stampType,
  (stampType) => {
    if (stampType === "FULL_DAY") {
      form.stampAmount = "1.0";
    } else if (stampType === "MORNING" || stampType === "AFTERNOON") {
      form.stampAmount = "0.5";
    }
  }
);

watch(
  () => modal.value,
  (newVal) => {
    if (newVal) {
      form.status = isStatusEdit.value ? props.dataAbsentLate.status : "";
      form.stampDate = isStatusEdit.value
        ? new Date(props.dataAbsentLate.stampDate)
        : new Date();
      form.stampType = isStatusEdit.value
        ? props.dataAbsentLate.stampType
        : "FULL_DAY";
      form.stampAmount = isStatusEdit.value
        ? props.dataAbsentLate.stampAmount
        : "1.0";
      form.remark = isStatusEdit.value ? props.dataAbsentLate.remark : "";
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 50vw">
      <q-form greedy @submit.prevent="onSubmit">
        <DialogHeader :tittle="tittle" :close="closeDialog" />
        <q-separator />

        <q-card-section class="q-pa-md">
          <div class="col-12 row q-col-gutter-sm">
            <div class="col-12 row">
              <div class="col-md-4 col-sm-12">
                <q-select
                  class="full-width inputgreen cursor-pointer"
                  outlined
                  dense
                  lazy-rules
                  v-model="form.status"
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกสถานะ'}`]"
                  hide-bottom-space
                  :label="`${'สถานะ'}`"
                  map-options
                  emit-value
                  option-label="name"
                  option-value="id"
                  :options="absentLateStore.statusOps"
                  use-input
                  hide-selected
                  fill-input
                  input-debounce="0"
                />
              </div>
            </div>

            <div class="col-md-4 col-sm-12">
              <datepicker
                class="inputgreen"
                menu-class-name="modalfix"
                v-model="form.stampDate"
                :locale="'th'"
                autoApply
                borderless
                :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
                    hide-bottom-space
                    class="full-width"
                    :model-value="
                      form.stampDate != null ? date2Thai(form.stampDate) : 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-md-4 col-xs-12">
              <q-select
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="form.stampType"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกประเภทการลงเวลา'}`]"
                hide-bottom-space
                :label="`${'ประเภทการลงเวลา'}`"
                map-options
                emit-value
                option-label="name"
                :options="absentLateStore.stampTypeOps"
                option-value="id"
                use-input
                hide-selected
                fill-input
                input-debounce="0"
              />
            </div>

            <div class="col-md-4 col-xs-12">
              <q-input
                class="inputgreen"
                dense
                outlined
                v-model="form.stampAmount"
                label="จำนวน"
                hide-bottom-space
                readonly
                :rules="[(val:string) => !!val ||
              `${'กรุณากรอกจำนวน'}`]"
                mask="#.#"
              />
            </div>

            <div class="col-12">
              <q-input
                class="inputgreen"
                dense
                outlined
                v-model="form.remark"
                label="เหตุผล"
                hide-bottom-space
                type="textarea"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn type="submit" :label="`บันทึก`" color="public">
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
