<script setup lang="ts">
import { ref, watch, computed } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import DialogHeader from "@/components/DialogHeader.vue";
import type { FormDateTimeRef } from "@/modules/02_organizationalNew/interface/index/Main";
import { useOrganizational } from "@/modules/02_organizationalNew/store/organizational";
import http from "@/plugins/http";
import config from "@/app.config";

const props = defineProps({
  modal: Boolean,
  close: Function,
  fetchActive: {
    type: Function,
    require: true,
    default: () => "Function fetchActive",
  },
});

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

const minDate = computed(() => {
  const date = new Date();
  date.setDate(date.getDate() + 1);
  return date;
});
const dateTimeRef = ref<Object | null>(null);

const dateTime = ref<Date | null>();

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const objectRef: FormDateTimeRef = {
  dateTime: dateTimeRef,
};

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
function validateForm() {
  const hasError = [];
  for (const key in objectRef) {
    if (Object.prototype.hasOwnProperty.call(objectRef, key)) {
      const property = objectRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    onSubmit();
  } else {
  }
}

/** ฟังชั่น บันทึก */
function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.orgSetDateTime(store.draftId as string), {
        orgPublishDate: dateTime.value,
      })
      .then((res) => {
        props.close?.();
        props.fetchActive();
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function onClickPublish() {
  dialogConfirm(
    $q,
    () => {
      showLoader();
      http
        .get(config.API.organizationPublishGet)
        .then((res) => {
          props.fetchActive();
          props.close?.();
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการเผยเเพร่ข้อมูล",
    "ต้องการยืนยันการเผยเเพร่ข้อมูลนี้ใช่หรือไม่?"
  );
}
watch(
  () => props.modal,
  () => {
    if (props.modal === true) {
      dateTime.value = store.orgPublishDate ? store.orgPublishDate : null;
    }
  }
);
</script>
<template>
  <template>
    <q-dialog v-model="props.modal" persistent>
      <q-card style="min-width: 18vw">
        <form @submit.prevent="validateForm">
          <DialogHeader :tittle="`ตั้งเวลาเผยแพร่`" :close="props.close" />
          <q-separator />

          <q-card-section>
            <div class="row q-col-gutter-sm">
              <div class="col-12">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="dateTime"
                  :locale="'th'"
                  autoApply
                  borderless
                  :enableTimePicker="false"
                  week-start="0"
                  :min-date="minDate"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      for="#dateTime"
                      ref="dateTimeRef"
                      outlined
                      dense
                      hide-bottom-space
                      :model-value="
                        dateTime != null ? date2Thai(dateTime) : 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>
              </div>
            </div>
          </q-card-section>
          <q-separator />
          <q-card-actions align="right">
            <q-btn flat color="blue-7" icon="public" @click="onClickPublish()">
              <q-tooltip>เผยแพร่ข้อมูลทันที</q-tooltip>
            </q-btn>
            <q-space />
            <q-btn type="submit" :label="`บันทึก`" color="public" />
          </q-card-actions>
        </form>
      </q-card>
    </q-dialog>
  </template>
</template>
