<script setup lang="ts">
import { ref, watch } from "vue";
import { useQuasar } from "quasar";
import config from "@/app.config";
import http from "@/plugins/http";

import type { DataOption } from "@/modules/09_leave/interface/index/Main";

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

import { useCounterMixin } from "@/stores/mixin";

const $q = useQuasar();
const mixin = useCounterMixin();
const { dialogConfirm, success, showLoader, hideLoader, messageError } = mixin;

const props = defineProps({
  modal: {
    type: Boolean,
    require: true,
  },
  detail: {
    type: Object,
    require: true,
  },
  close: {
    type: Function,
    require: true,
  },
  fetchData: {
    type: Function,
    require: true,
  },
});

const morningStatus = ref<string>("");
const afternoonStatus = ref<string | null>("");
const reason = ref<string>("");

const morningStatusRef = ref<any>();
const afternoonStatusRef = ref<any>();

const optionsMain = ref<DataOption[]>([
  { id: "NORMAL", name: "ปกติ" },
  { id: "LATE", name: "สาย" },
  { id: "ABSENT", name: "ขาดราชการ" },
]);
const options = ref<DataOption[]>(optionsMain.value);

async function onClickSave() {
  morningStatusRef.value?.validate();
  afternoonStatusRef.value?.validate();
  if (
    !morningStatusRef.value.hasError && props.detail?.checkOutStatus !== "-"
      ? !afternoonStatusRef.value.hasError
      : true
  ) {
    const body = {
      checkInStatus: morningStatus.value,
      checkOutStatus: afternoonStatus.value,
      reason: reason.value,
    };

    dialogConfirm($q, async () => {
      showLoader();
      await http
        .put(config.API.leaveEditCheckin(props.detail?.id), body)
        .then(async () => {
          await props.fetchData?.();
          await props.close?.();
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    });
  }
}

function filterFnOptions(val: string, update: Function) {
  update(() => {
    options.value = optionsMain.value.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

function convertStatu(val: string) {
  switch (val) {
    case "ปกติ":
      return "NORMAL";
    case "สาย":
      return "LATE";
    case "ขาดราชการ":
      return "ABSENT";
  }
}

watch(
  () => props.modal,
  () => {
    if (props.modal) {
      const checkInStatus: string | undefined = props.detail?.checkInStatus
        ? convertStatu(props.detail?.checkInStatus)
        : "";

      const checkOutStatus: string | undefined = props.detail?.checkOutStatus
        ? convertStatu(props.detail?.checkOutStatus)
        : "";

      morningStatus.value = checkInStatus ? checkInStatus : "";
      afternoonStatus.value = checkOutStatus ? checkOutStatus : "-";
      reason.value = "";
    }
  }
);
</script>
<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card class="column" style="width: 320px">
      <HeaderDialog :tittle="'แก้ไขสถานะการเข้า-ออกงาน'" :close="props.close" />

      <q-separator />
      <q-card-section class="q-pt-none">
        <q-card flat bordered class="col-12 q-mt-sm">
          <div class="q-pa-sm text-green-8">
            สถานะช่วงเช้า
            <q-select
              ref="morningStatusRef"
              class="q-pa-sm"
              dense
              outlined
              v-model="morningStatus"
              :options="options"
              label="สถานะ"
              emit-value
              map-options
              option-label="name"
              option-value="id"
              :rules="[(val:string) => !!val || `${'กรุณาเลือกสถานะ'}`]"
              hide-bottom-space
              use-input
              @filter="(inputValue: string,doneFn: Function) => filterFnOptions(inputValue, doneFn)"
              ><template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template></q-select
            >
          </div>
        </q-card>
        <q-card
          flat
          bordered
          class="col-12 q-mt-sm"
          v-if="props.detail?.checkOutStatus !== '-'"
        >
          <div class="q-pa-sm text-green-8">
            สถานะช่วงบ่าย

            <q-select
              ref="afternoonStatusRef"
              class="q-pa-sm"
              dense
              outlined
              v-model="afternoonStatus"
              :options="options"
              label="สถานะ"
              emit-value
              map-options
              option-label="name"
              option-value="id"
              :rules="[(val:string) => !!val || `${'กรุณาเลือกสถานะ'}`]"
              hide-bottom-space
              use-input
              @filter="(inputValue: string,doneFn: Function) => filterFnOptions(inputValue, doneFn)"
              ><template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template></q-select
            >
          </div>
        </q-card>

        <q-card flat class="col-12 q-mt-sm">
          <q-input
            outlined
            dense
            v-model="reason"
            type="textarea"
            label="เหตุผล"
          />
        </q-card>
      </q-card-section>

      <q-separator />
      <q-card-actions align="right">
        <q-btn dense color="secondary" label="บันทึก" @click="onClickSave" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
