<script setup lang="ts">
import { 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 { ObjectReteRef } from "@/modules/13_salary/interface/index/EmployeeChart";
import type { FormDataRate } from "@/modules/13_salary/interface/request/EmployeeChart";

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 salaryEmployeeId = ref<string>(route.params.id.toString());

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

const formData = reactive<any>({
  salaryNo: null,
  salaryMonth: null,
  salaryDay: null,
});

/** ตัวแปร ref สำหรับแสดง validate */
const salaryNoRef = ref<Object | null>(null);
const salaryMonthRef = ref<Object | null>(null);
const salaryDayRef = ref<Object | null>(null);

const ObjectRef: ObjectReteRef = {
  salaryNo: salaryNoRef,
  salaryMonth: salaryMonthRef,
  salaryDay: salaryDayRef,
};

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

function clearFormData() {
  formData.salaryNo = null;
  formData.salaryMonth = null;
  formData.salaryDay = null;
}

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)) {
    onSubmit();
  }
}

function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const body: FormDataRate = {
      salaryEmployeeId: !props.isStatusEdit
        ? salaryEmployeeId.value
        : undefined,
      step:
        typeof formData.salaryNo === "number"
          ? formData.salaryNo
          : Number(formData.salaryNo.replace(/,/g, "")),

      salaryMonth:
        typeof formData.salaryMonth === "number"
          ? formData.salaryMonth
          : Number(formData.salaryMonth.replace(/,/g, "")), //*เงินเดือนฐาน

      salaryDay:
        typeof formData.salaryDay === "number"
          ? formData.salaryDay
          : Number(formData.salaryDay.replace(/,/g, "")), //0.5 ขั้น
    };
    try {
      const url = !props.isStatusEdit
        ? config.API.salaryEmployeeRateList
        : config.API.salaryEmployeeRateListByid(props?.data?.id);
      await http[!props.isStatusEdit ? "post" : "put"](url, body);
      success($q, "บันทีกข้อมูลสำเร็จ");
      props.fetchData?.();
    } catch (err) {
      messageError($q, err);
      hideLoader();
    } finally {
      closeDialog();
    }
  });
}

watch(
  () => modal.value,
  () => {
    if (modal.value && props.isStatusEdit) {
      if (props.data) {
        const data = props.data;
        console.log(data);
        formData.salaryNo = data.step;
        formData.salaryMonth = data.salaryMonth;
        formData.salaryDay = data.salaryDay;
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 500px">
      <Header
        :tittle="props.isStatusEdit ? 'แก้ไขอัตราค่าจ้าง' : 'เพิ่มอัตราค่าจ้าง'"
        :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-12">
              <q-input
                ref="salaryNoRef"
                dense
                outlined
                v-model="formData.salaryNo"
                label="ลำดับชั้น"
                :rules="[
                  (val) => !!val || 'กรุณากรอกลำดับชั้น',
                  (val) =>
                    Number(val) === Math.floor(val) ||
                    Number(val) === Math.floor(val) + 0.5 ||
                    `กรุณากรอกจำนวนเต็มเท่านั้ หรือ .5`,
                ]"
                lazy-rules
                hide-bottom-space
              />
            </div>

            <div class="col-12">
              <q-input
                ref="salaryMonthRef"
                dense
                outlined
                v-model="formData.salaryMonth"
                label="อัตราค่าจ้าง/ขั้นวิ่ง (รายเดือน)"
                mask="###,###,###,###"
                reverse-fill-mask
                :rules="[
                  (val) =>
                    !!val || `${'กรุณากรอกอัตราค่าจ้าง/ขั้นวิ่ง (รายเดือน)'}`,
                ]"
                lazy-rules
                hide-bottom-space
              />
            </div>
            <div class="col-12">
              <q-input
                ref="salaryDayRef"
                dense
                outlined
                v-model="formData.salaryDay"
                label="อัตราค่าจ้าง/ขั้นวิ่ง (รายวัน)"
                mask="###,###,###,###"
                reverse-fill-mask
                lazy-rules
                hide-bottom-space
                :rules="[
                  (val) =>
                    !!val || `${'กรุณากรอกอัตราค่าจ้าง/ขั้นวิ่ง (รายวัน)'}`,
                ]"
              />
            </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>
