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

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

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

/** use*/
const $q = useQuasar();
const mixin = useCounterMixin();
const { dialogConfirm, success, messageError } = mixin;

/** props*/
const modal = defineModel<boolean>("modal", { required: true });
const amount = defineModel<number | null>("amount", { required: true });
const profileId = defineModel<string>("profileId", { required: true });
const props = defineProps({
  fetchData: {
    type: Function,
  },
});

const amountRef = ref<any>();

/** ฟังก์ชั่นสำหรับ validate ฟอร์ม */
function validateForm() {
  if (amountRef.value.validate()) {
    onSubmit();
  }
}

/** function ปืด Popup */
function close() {
  modal.value = false;
  amount.value = null;
}

/** function ยืนยันการบันทึกข้อมูล*/
function onSubmit() {
  dialogConfirm($q, () => {
    if (amount.value !== null) {
      const amountString: string = amount.value.toString();
      const body = {
        profileId: profileId.value,
        amount:
          typeof amount.value === "number"
            ? amount.value
            : Number(amountString.replace(/,/g, "")),
      };
      http
        .post(config.API.salaryPeriodEmp() + `/change/amount`, body)
        .then(() => {
          success($q, "บันทึกข้อมูลสำเร็จ");
          props.fetchData?.();
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          close();
        });
    }
  });
}
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 30%">
      <Header :tittle="`แก้ไขเงินเดือน`" :close="close" />
      <q-separator />

      <q-card-section class="scroll" style="max-height: 70vh">
        <div class="q-gutter-y-sm">
          <q-input
            ref="amountRef"
            dense
            outlined
            v-model="amount"
            label="เงินเดือนฐาน"
            mask="###,###,###,###"
            reverse-fill-mask
            :rules="[(val) => !!val || `${'กรุณากรอกเงินเดือนฐาน'}`]"
            lazy-rules
            hide-bottom-space
          />
        </div>
      </q-card-section>
      <q-separator />
      <form @submit.prevent="validateForm">
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn
            type="submit"
            for="#submitForm"
            unelevated
            dense
            class="q-px-md items-center"
            color="light-blue-10"
            label="บันทึก"
          />
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
</template>

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