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

import type { ObjectCharRef } from "@/modules/13_salary/interface/index/EmployeeChart";
import type { FormDataChar } from "@/modules/13_salary/interface/request/EmployeeChart";

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

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

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

const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  isStatusEdit: { type: Boolean, required: true },
  data: { type: Object, required: true },
  fetchData: {
    type: Function,
    required: true,
  },
});
const formData = reactive<FormDataChar>({
  name: "", //ชื่อผังบัญชีอัตราค่าจ้าง
  group: "", //*กลุ่มของผังบัญชีอัตราค่าจ้าง
  isActive: false, //*สถานะการใช้งาน
  date: null, //ให้ไว้ ณ วันที่
  startDate: null, //วันที่มีผลบังคับใช้
  endDate: null, //วันที่สิ้นสุดบังคับใช้
  details: "", //คำอธิบาย
});

const nameRef = ref<Object | null>(null);
const groupRef = ref<Object | null>(null);

const ObjectRef: ObjectCharRef = {
  name: nameRef,
  group: groupRef,
};

function fetchSalaryDetail(id: string) {
  showLoader();
  http
    .get(config.API.salaryEmployeeChartByid(id))
    .then((res) => {
      const data = res.data.result;
      formData.name = data.name;
      formData.group = data.group;
      formData.isActive = data.isActive;
      formData.date = data.date;
      formData.startDate = data.startDate;
      formData.endDate = data.endDate;
      formData.details = data.details;
      isReadonly.value = data.isActive ? true : false;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const isReadonly = ref<boolean>(false);
function onClickSubmit() {
  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)) {
    dialogConfirm($q, () => {
      onSubmit();
    });
  }
}

async function onSubmit() {
  showLoader();
  try {
    const url = !props.isStatusEdit
      ? config.API.salaryEmployeeChart
      : config.API.salaryEmployeeChartByid(props.data.id);
    await http[!props.isStatusEdit ? "post" : "put"](url, formData);
    success($q, "บันทีกข้อมูลสำเร็จ");
    props.fetchData?.();
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
    closeDialog();
  }
}

function closeDialog() {
  modal.value = false;
  clearFormData();
}

function clearFormData() {
  formData.name = "";
  formData.group = "";
  formData.isActive = false;
  formData.date = null;
  formData.startDate = null;
  formData.endDate = null;
  formData.details = "";
}

/** function checkEndDate*/
function checkEndDate() {
  if (formData.endDate !== null && formData.startDate !== null) {
    if (formData.endDate < formData.startDate) {
      formData.endDate = null;
    }
  }
}

watch(
  () => modal.value,
  () => {
    if (modal.value && props.isStatusEdit) {
      fetchSalaryDetail(props.data.id);
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 80%">
      <form @submit.prevent.stop="onClickSubmit">
        <Header
          :tittle="
            props.isStatusEdit
              ? 'แก้ไขผังบัญชีค่าจ้างลูกจ้างประจำ'
              : 'เพิ่มผังบัญชีค่าจ้างลูกจ้างประจำ'
          "
          :close="closeDialog"
        />
        <q-separator />
        <q-card-section class="scroll" style="max-height: 70vh">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-md-12">
              <div class="row col-12 q-col-gutter-sm">
                <div class="col-xs-12 col-md-4">
                  <q-input
                    :readonly="isReadonly"
                    ref="nameRef"
                    dense
                    hide-bottom-space
                    outlined
                    v-model="formData.name"
                    label="ชื่อผังบัญชีอัตราค่าจ้าง"
                    :rules="[
                      (val) => !!val || 'กรุณากรอกชื่อผังบัญชีอัตราค่าจ้าง',
                    ]"
                    lazy-rules
                  />
                </div>

                <div class="col-xs-12 col-md-4">
                  <q-input
                    ref="groupRef"
                    week-start="0"
                    :readonly="isReadonly"
                    dense
                    outlined
                    v-model="formData.group"
                    label="กลุ่มของผังบัญชีอัตราค่าจ้าง"
                    hide-bottom-space
                    mask="########"
                    :rules="[
                      (val) => !!val || 'กรุณากรอกกลุ่มของผังบัญชีอัตราค่าจ้าง',
                    ]"
                  />
                </div>

                <div
                  class="col-xs-12 col-md-4"
                  style="display: flex; justify-content: flex-start"
                >
                  <q-toggle
                    week-start="0"
                    :disable="isReadonly"
                    color="primary"
                    label="สถานะการใช้งาน"
                    v-model="formData.isActive"
                  />
                </div>

                <div class="col-xs-12 col-md-4">
                  <datepicker
                    menu-class-name="modalfix"
                    v-model="formData.date"
                    :locale="'th'"
                    autoApply
                    borderless
                    :enableTimePicker="false"
                    week-start="0"
                    :readonly="isReadonly"
                  >
                    <template #year="{ year }">
                      {{ year + 543 }}
                    </template>
                    <template #year-overlay-value="{ value }">
                      {{ parseInt(value + 543) }}
                    </template>
                    <template #trigger>
                      <q-input
                        :readonly="isReadonly"
                        outlined
                        dense
                        hide-bottom-space
                        :model-value="
                          formData.date != null
                            ? date2Thai(formData.date)
                            : null
                        "
                        label="ให้ไว้ ณ วันที่"
                      >
                        <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-xs-12 col-md-4">
                  <datepicker
                    :readonly="isReadonly"
                    menu-class-name="modalfix"
                    v-model="formData.startDate"
                    :locale="'th'"
                    autoApply
                    borderless
                    :enableTimePicker="false"
                    week-start="0"
                    @update:model-value="checkEndDate"
                  >
                    <template #year="{ year }">
                      {{ year + 543 }}
                    </template>
                    <template #year-overlay-value="{ value }">
                      {{ parseInt(value + 543) }}
                    </template>
                    <template #trigger>
                      <q-input
                        :readonly="isReadonly"
                        outlined
                        dense
                        hide-bottom-space
                        :model-value="
                          formData.startDate != null
                            ? date2Thai(formData.startDate)
                            : null
                        "
                        label="วันที่มีผลบังคับใช้"
                      >
                        <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-xs-12 col-md-4">
                  <datepicker
                    :readonly="isReadonly"
                    menu-class-name="modalfix"
                    v-model="formData.endDate"
                    :locale="'th'"
                    autoApply
                    borderless
                    :enableTimePicker="false"
                    week-start="0"
                    :min-date="formData.startDate"
                  >
                    <template #year="{ year }">
                      {{ year + 543 }}
                    </template>
                    <template #year-overlay-value="{ value }">
                      {{ parseInt(value + 543) }}
                    </template>
                    <template #trigger>
                      <q-input
                        :readonly="isReadonly"
                        outlined
                        dense
                        :model-value="
                          formData.endDate != null
                            ? date2Thai(formData.endDate)
                            : null
                        "
                        label="วันที่สิ้นสุดบังคับใช้"
                      >
                        <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">
                  <q-input
                    :readonly="isReadonly"
                    v-model="formData.details"
                    outlined
                    dense
                    type="textarea"
                    label="คำอธิบาย"
                  />
                </div>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <div class="text-right q-ma-sm">
          <q-btn
            label="บันทึก"
            type="submit"
            color="secondary"
            :disable="isReadonly"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </div>
      </form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
