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

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

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

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

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

/** props*/
const modal = defineModel<boolean>("modal", { required: true });
const effective = defineModel<Date | null | string>("effective", {
  required: true,
});
const isRead = defineModel<boolean>("isRead", { required: true });
const year = defineModel<number | null | string>("year");
const props = defineProps({
  getData: Function,
  edit: Boolean,
  idRound: String,
  period: String,
  effectiveDate: Date,
  isActive: Boolean,
  isRead: Boolean,
});

const period = ref<string>(""); //รอบการขึ้นเงินเดือน
const isActive = ref<boolean>(false); //สถานะการใช้งาน
const effectiveDate = ref<Date | null>(null); //วันที่มีผล
//ตัวเลือกรอบ
const typeOptions = ref<DataOption[]>([
  { id: "SPECIAL", name: "รอบพิเศษ" },
  { id: "APR", name: "รอบเมษายน" },
  { id: "OCT", name: "รอบตุลาคม" },
]);

/**
 * function เคลียข้อมูล form
 */
function clearForm() {
  isActive.value = false;
  period.value = "";
  effective.value = null;
  year.value = 0;
  isRead.value = false;
}

/**
 *  function ปืด Dialog
 */
function close() {
  modal.value = false;
  clearForm();
}

/**
 * function บัยทึกข้อมูลรอบการขึ้นเงินเดือน
 */
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const body = {
      period: period.value,
      isActive: isActive.value,
      effectiveDate: effective.value,
      year: year.value,
    };
    try {
      const url = !props.edit
        ? config.API.salaryPeriod()
        : config.API.salaryPeriod() + `/${props.idRound}`;
      await http[!props.edit ? "post" : "put"](url, body);
      await props.getData?.();
      await success($q, "บันทีกข้อมูลสำเร็จ");
      close();
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer inputgreen ": val,
    "full-width cursor-pointer ": !val,
  };
}

function onUpdatePeriod(val: string) {
  if (val === "SPECIAL") {
    isActive.value = true;
  } else {
    isActive.value = false;
  }
}

/**
 * callbackFunction ทำการ fetch ข้อมูลไฟล์เมื่อเปิด Dialog
 */
watch(
  () => modal.value,
  () => {
    if (props.edit == true) {
      period.value = props.period ? props.period : "";
      effectiveDate.value = props.effectiveDate ? props.effectiveDate : null;
      isActive.value = props.isActive;
    } else {
      year.value = 0;
      effective.value = null;
      period.value = "";
      isActive.value = false;
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 23%">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <Header
          :tittle="`${
            isRead == true
              ? `ข้อมูลรอบการขึ้นเงินเดือน`
              : props.edit
              ? `แก้ไขรอบการขึ้นเงินเดือน`
              : `เพิ่มรอบการขึ้นเงินเดือน`
          }`"
          :close="close"
        />
        <q-separator />
        <q-card-section class="scroll" style="max-height: 70vh">
          <div class="q-gutter-y-sm">
            <datepicker
              :readonly="isRead"
              :class="inputEdit(!isRead)"
              menu-class-name="modalfix"
              v-model="year"
              class="col-2"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  :readonly="isRead"
                  :class="inputEdit(!isRead)"
                  ref="yearRef"
                  dense
                  hide-bottom-space
                  outlined
                  :model-value="year === 0 ? null : Number(year) + 543"
                  :label="`${'ปีงบประมาณ'}`"
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกเลือกปีงบประมาณ'}`]"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>

            <q-select
              :readonly="isRead"
              ref="periodRef"
              :class="inputEdit(!isRead)"
              v-model="period"
              label="รอบการขึ้นเงินเดือน"
              dense
              outlined
              emit-value
              map-options
              option-label="name"
              option-value="id"
              :options="typeOptions"
              lazy-rules
              :rules="[(val:string) => !!val || `${'กรุณาเลือกรอบการขึ้นเงินเดือน'}`]"
              hide-bottom-space
              @update:model-value="onUpdatePeriod"
            />
            <datepicker
              :readonly="isRead"
              menu-class-name="modalfix"
              v-model="effective"
              :locale="'th'"
              autoApply
              borderless
              :enableTimePicker="false"
              week-start="0"
            >
              <template #year="{ year }">
                {{ year + 543 }}
              </template>
              <template #year-overlay-value="{ value }">
                {{ parseInt(value + 543) }}
              </template>
              <template #trigger>
                <q-input
                  for="effectiveDate"
                  ref="effectiveDateRef"
                  outlined
                  dense
                  :class="inputEdit(!isRead)"
                  :readonly="isRead"
                  hide-bottom-space
                  :model-value="
                    effective != null ? date2Thai(effective as Date) : null
                  "
                  label="วันที่มีผลบังคับใช้งาน"
                  :rules="[
                    (val:string) => !!val || `${'กรุณาเลือกวันที่มีผลบังคับใช้งาน'}`,
                  ]"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
            <div class="col q-pa-sm bg-white border_custom text-weight-medium">
              <div class="row items-center justify-between">
                <p class="q-ma-none">สถานะการใช้งาน</p>
                <label>
                  <q-toggle
                    v-model="isActive"
                    :disable="period === 'SPECIAL' || isRead"
                    :readonly="isRead"
                  />
                </label>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator v-if="!isRead" />
        <q-card-actions align="right" class="bg-white text-teal" v-if="!isRead">
          <q-btn label="บันทึก" type="submit" color="secondary">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scoped>
.border_custom {
  border-radius: 6px !important;
  border: 1px solid #e1e1e1;
}
</style>
