<script setup lang="ts">
import { useQuasar } from "quasar";

import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

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

/** use*/
const $q = useQuasar();
const mixin = useCounterMixin();
const { dialogConfirm, success, messageError, showLoader, hideLoader } = 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,
  },
});

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

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

<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 30%">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <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:string) => !!val || `${'กรุณากรอกเงินเดือนฐาน'}`]"
              lazy-rules
              hide-bottom-space
              class="inputgreen"
            />
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn
            type="submit"
            for="#submitForm"
            color="secondary"
            label="บันทึก"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

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