<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";

/** importType*/
import type { FormSalaryRate } from "@/modules/13_salary/interface/index/Main";

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

/** importStore*/

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

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

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

const isReadonly = ref<boolean>(false);
const salaryId = ref<string>(route.params.id.toString());
const formData = reactive<FormSalaryRate>({
  salaryId: "",
  salary: null,
  salaryHalf: null,
  salaryHalfSpecial: null,
  salaryFull: null,
  salaryFullSpecial: null,
  salaryFullHalf: null,
  salaryFullHalfSpecial: null,
  isNext: false,
});

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

  return name;
});

/** function ปืด Dialog*/
function closeDialog() {
  modal.value = !modal.value;
  clearFormData();
}

/** function เคลียข้อมูล form*/
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 บันทึกข้อมูล*/
function onSubmit() {
  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();
    }
  });
}

/** callbackFunction ทำการ fetch ข้อมูลไฟล์เมื่อเปิด Dialog*/
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;
      }
    }
  }
);

/**
 * class จัดรูปแบบแสดงระหว่างข้อมูลที่แก้ไขหรือแสดงเฉยๆ
 * @param val ข้อมูล input สำหรับแก้ไขหรือไม่
 */
const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <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
                  :readonly="isReadonly"
                  :class="getClass(!isReadonly)"
                  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
                  :readonly="isReadonly"
                  :class="getClass(!isReadonly)"
                  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
                  :readonly="isReadonly"
                  :class="getClass(!isReadonly)"
                  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
                  :readonly="isReadonly"
                  :class="getClass(!isReadonly)"
                  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
                  :readonly="isReadonly"
                  :class="getClass(!isReadonly)"
                  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
                  :readonly="isReadonly"
                  :class="getClass(!isReadonly)"
                  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
                  :readonly="isReadonly"
                  :class="getClass(!isReadonly)"
                  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" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

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