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

import type { ObjectSalaryRateRef } from "@/modules/13_salary/interface/index/Main";

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

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

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

const salaryId = ref<string>(route.params.id.toString());

const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  typeAction: {
    type: String,
    required: true,
  },
  data: {
    type: Object,
    defult: [],
  },
  fetchData: {
    type: Function,
    defult: () => {},
  },
});

const formData = reactive<any>({
  salaryId: "",
  salary: null,
  salaryHalf: null,
  salaryHalfSpecial: null,
  salaryFull: null,
  salaryFullSpecial: null,
  salaryFullHalf: null,
  salaryFullHalfSpecial: null,
  isNext: false,
});

/** ตัวแปร ref สำหรับแสดง validate */
const salaryRef = ref<Object | null>(null);
const salaryHalfRef = ref<Object | null>(null);
const salaryHalfSpecialRef = ref<Object | null>(null);
const salaryFullRef = ref<Object | null>(null);
const salaryFullSpecialRef = ref<Object | null>(null);
const salaryFullHalfRef = ref<Object | null>(null);
const salaryFullHalfSpecialRef = ref<Object | null>(null);

const ObjectRef: ObjectSalaryRateRef = {
  salary: salaryRef,
  salaryHalf: salaryHalfRef,
  salaryHalfSpecial: salaryHalfSpecialRef,
  salaryFull: salaryFullRef,
  salaryFullSpecial: salaryFullSpecialRef,
  salaryFullHalf: salaryFullHalfRef,
  salaryFullHalfSpecial: salaryFullHalfSpecialRef,
};

const title = computed(() => {
  const name =
    props.typeAction === "add"
      ? "เพิ่มอัตราเงินเดือน"
      : props.typeAction === "edit"
      ? "แก้ไขอัตราเงินเดือน"
      : "อัตราเงินเดือน";

  return name;
});

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

function clearFormData() {
  formData.salaryId = "";
  formData.salary = null;
  formData.salaryHalf = null;
  formData.salaryHalfSpecial = null;
  formData.salaryFull = null;
  formData.salaryFullSpecial = null;
  formData.salaryFullHalf = null;
  formData.salaryFullHalfSpecial = null;
  formData.isNext = false;
}

function onClickSubmit() {
  console.log(formData.salaryHalfSpecial);
  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)) {
    createSalaryRate();
  }
}

function createSalaryRate() {
  dialogConfirm($q, async () => {
    showLoader();
    const body: any = {
      salary:
        typeof formData.salary === "number"
          ? formData.salary
          : Number(formData.salary.replace(/,/g, "")), //*เงินเดือนฐาน

      salaryHalf:
        typeof formData.salaryHalf === "number"
          ? formData.salaryHalf
          : Number(formData.salaryHalf.replace(/,/g, "")), //0.5 ขั้น

      salaryHalfSpecial:
        formData.salaryHalfSpecial === "" || formData.salaryHalfSpecial === null
          ? null
          : typeof formData.salaryHalfSpecial === "number"
          ? formData.salaryHalfSpecial
          : Number(formData.salaryHalfSpecial.replace(/,/g, "")), //0.5 ขั้น(เงินพิเศษ)

      salaryFull:
        typeof formData.salaryFull === "number"
          ? formData.salaryFull
          : Number(formData.salaryFull.replace(/,/g, "")), //1 ขั้น

      salaryFullSpecial:
        formData.salaryFullSpecial === "" || formData.salaryFullSpecial === null
          ? null
          : typeof formData.salaryFullSpecial === "number"
          ? formData.salaryFullSpecial
          : Number(formData.salaryFullSpecial.replace(/,/g, "")), //1 ขั้น(เงินพิเศษ)

      salaryFullHalf:
        typeof formData.salaryFullHalf === "number"
          ? formData.salaryFullHalf
          : Number(formData.salaryFullHalf.replace(/,/g, "")), //1.formData5 ขั้น

      salaryFullHalfSpecial:
        formData.salaryFullHalfSpecial === "" ||
        formData.salaryFullHalfSpecial === null
          ? null
          : typeof formData.salaryFullHalfSpecial === "number"
          ? formData.salaryFullHalfSpecial
          : Number(formData.salaryFullHalfSpecial.replace(/,/g, "")), //1.5 ขั้น(เงินพิเศษ)
      isNext: formData.isNext, //*ทะลุขั้น
    };
    if (props.typeAction === "add") {
      body.salaryId = salaryId.value;
    }
    try {
      const url =
        props.typeAction === "add"
          ? config.API.salaryRateList
          : config.API.salaryRateListByid(formData.salaryId);
      await http[props.typeAction === "add" ? "post" : "put"](url, body);
      success($q, "บันทีกข้อมูลสำเร็จ");
      props.fetchData?.();
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
      closeDialog();
    }
  });
}

watch(
  () => modal.value,
  () => {
    if (modal.value && props.typeAction === "edit") {
      if (props.data) {
        const data = props.data;
        formData.salaryId = data.id;
        formData.salary = data.salary;
        formData.salaryHalf = data.salaryHalf;
        formData.salaryHalfSpecial = data.salaryHalfSpecial;
        formData.salaryFull = data.salaryFull;
        formData.salaryFullSpecial = data.salaryFullSpecial;
        formData.salaryFullHalf = data.salaryFullHalf;
        formData.salaryFullHalfSpecial = data.salaryFullHalfSpecial;
        formData.isNext = data.isNext;
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <Header :tittle="title" :close="closeDialog" />
      <q-separator />

      <q-card-section >
        <div class="row q-gutter-sm q-pa-sm">
          <div class="row col-xs-12 col-md-12 q-col-gutter-sm">
            <div class="col-6">
              <q-input
                ref="salaryRef"
                dense
                outlined
                v-model="formData.salary"
                label="เงินเดือนฐาน"
                mask="###,###,###,###"
                reverse-fill-mask
                :rules="[(val) => !!val || `${'กรุณากรอกเงินเดือนฐาน'}`]"
                lazy-rules
                hide-bottom-space
              />
            </div>
            <div class="col-6 row items-center">
              <q-checkbox dense v-model="formData.isNext" label="ทะลุขั้น" />
            </div>
            <div class="col-6">
              <q-input
                ref="salaryHalfRef"
                dense
                outlined
                v-model="formData.salaryHalf"
                label="เลื่อน 0.5 ขั้น"
                mask="###,###,###,###"
                reverse-fill-mask
                :rules="[(val) => !!val || `${'กรุณากรอกเลื่อน 0.5 ขั้น'}`]"
                lazy-rules
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                ref="salaryHalfSpecialRef"
                dense
                outlined
                v-model="formData.salaryHalfSpecial"
                label="เงินพิเศษ"
                mask="###,###,###,###"
                reverse-fill-mask
                lazy-rules
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                ref="salaryFullRef"
                dense
                outlined
                v-model="formData.salaryFull"
                label="เลื่อน 1 ขั้น"
                mask="###,###,###,###"
                reverse-fill-mask
                :rules="[(val) => !!val || `${'กรุณากรอกเลื่อน 1 ขั้น'}`]"
                lazy-rules
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                ref="salaryFullSpecialRef"
                dense
                outlined
                v-model="formData.salaryFullSpecial"
                label="เงินพิเศษ"
                mask="###,###,###,###"
                reverse-fill-mask
                lazy-rules
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                ref="salaryFullHalfRef"
                dense
                outlined
                v-model="formData.salaryFullHalf"
                label="เลื่อน 1.5 ขั้น"
                mask="###,###,###,###"
                reverse-fill-mask
                :rules="[(val) => !!val || `${'กรุณากรอกเลื่อน 1.5 ขั้น'}`]"
                lazy-rules
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                ref="salaryFullHalfSpecialRef"
                dense
                outlined
                v-model="formData.salaryFullHalfSpecial"
                label="เงินพิเศษ"
                mask="###,###,###,###"
                reverse-fill-mask
                lazy-rules
                hide-bottom-space
              />
            </div>
          </div>
        </div>
      </q-card-section>
      <q-separator />

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn label="บันทึก" color="secondary" @click="onClickSubmit"
          ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scoped></style>
