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

import type {
  ResGroup,
  ResLevel,
} from "@/modules/01_metadataNew/interface/response/positionEmployee/Main";
import type { ObjectPosRef } from "@/modules/01_metadataNew/interface/index/positionEmployee";
import type { DataOption } from "@/modules/16_positionEmployee/interface/index/Main";

import type { OptionType } from "@/modules/16_positionEmployee/interface/response/organizational";

import DialogHeader from "@/components/DialogHeader.vue";

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

const isSpecial = ref<boolean>(false);
const props = defineProps({
  emitSearch: Function,
  getData: Function,
  data: Object,
  levelOp: Object,
});
const modal = defineModel<boolean>("modalAdd", { required: true });
const isEditCheck = defineModel<boolean>("isEdit", { required: true });
const $q = useQuasar();
const mixin = useCounterMixin();
const { dialogConfirm, showLoader, hideLoader, messageError, success } = mixin;

const isDisValidate = ref<boolean>(false);
const formDataPos = reactive({
  posName: "",
  posTypeName: "",
  posLevelName: "",
});

const posNameRef = ref<object | null>(null);
const posTypeNameRef = ref<object | null>(null);
const posLevelNameRef = ref<object | null>(null);
const objectRef: ObjectPosRef = {
  posName: posNameRef,
  posTypeName: posTypeNameRef,
  posLevelName: posLevelNameRef,
};
const posTypeMain = ref<ResGroup[]>([]);
const posTypeOp = ref<DataOption[]>([]);
const posLevelOp = ref<DataOption[]>([]);

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
function validateFormPositionEdit() {
  isDisValidate.value = false;
  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)) {
    dialogConfirm($q, () => {
      submit();
    });
  }
}
async function submit() {
  const body = {
    posDictName: formDataPos.posName,
    posTypeId: formDataPos.posTypeName,
    posLevelId: formDataPos.posLevelName,
  };
  showLoader();
  try {
    const url = !isEditCheck.value
      ? config.API.orgEmployeePos
      : config.API.orgEmployeePosById(props?.data?.id);
    await http[!isEditCheck.value ? "post" : "put"](url, body);
    success($q, "บันทีกข้อมูลสำเร็จ");
    props.emitSearch?.(formDataPos.posName, "positionName");
    close();
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

async function clearFormPositionSelect() {
  isEditCheck.value = false;
  isDisValidate.value = true;
  formDataPos.posName = "";
  formDataPos.posTypeName = "";
  formDataPos.posLevelName = "";
  isSpecial.value = false;
  setTimeout(() => {
    isDisValidate.value = false;
  }, 1000);
}

function close() {
  modal.value = false;
  clearFormPositionSelect();
}

async function fetchType() {
  showLoader();
  await http
    .get(config.API.orgEmployeeType)
    .then((res) => {
      posTypeMain.value = res.data.result;
      posTypeOp.value = res.data.result.map((e: OptionType) => ({
        id: e.id,
        name: e.posTypeName,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function updatePosTypeName(id: string) {
  const posLevel = posTypeMain.value.find((e: ResGroup) => e.id === id);
  posLevelOp.value =
    posLevel?.posLevels.map((e: ResLevel) => ({
      id: e.id,
      name: e.posLevelName.toString(),
    })) ?? [];
  formDataPos.posLevelName = "";
}

watch(
  () => modal.value,
  async () => {
    if (modal.value === true) {
      await fetchType();

      if (props.data) {
        const dataList = props.data;
        updatePosTypeName(dataList.posTypeId);

        formDataPos.posName = dataList.posDictName;
        formDataPos.posTypeName = dataList.posTypeId;
        formDataPos.posLevelName = dataList.posLevelId;
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 50vw">
      <DialogHeader
        :tittle="`${isEditCheck ? `แก้ไขข้อมูลตำแหน่ง` : `เพิ่มข้อมูลตำแหน่ง`}`"
        :close="close"
      />
      <q-separator />

      <q-card-section class="q-pa-none">
        <form @submit.prevent="validateFormPositionEdit">
          <div class="row q-col-gutter-sm col-12 q-pa-md">
            <div class="col-12">
              <q-input
                ref="posNameRef"
                v-model="formDataPos.posName"
                dense
                outlined
                for="#positionName"
                label="ชื่อตำแหน่ง"
                lazy-rules
                hide-bottom-space
                :rules="[(val) => !!val || `${'กรุณากรอกชื่อตำแหน่ง'}`]"
              />
            </div>

            <div class="col-6">
              <q-select
                ref="posTypeNameRef"
                label="กลุ่มงาน"
                v-model="formDataPos.posTypeName"
                :options="posTypeOp"
                emit-value
                dense
                map-options
                outlined
                option-label="name"
                option-value="id"
                lazy-rules
                hide-bottom-space
                :rules="[(val) => !!val || `${'กรุณาเลือกกลุ่มงาน'}`]"
                @update:model-value="updatePosTypeName"
              />
            </div>

            <div class="col-6">
              <q-select
                ref="posLevelNameRef"
                label="ระดับชั้นงาน"
                v-model="formDataPos.posLevelName"
                :disable="formDataPos.posTypeName === ''"
                :options="posLevelOp"
                emit-value
                dense
                map-options
                outlined
                option-label="name"
                option-value="id"
                lazy-rules
                hide-bottom-space
                :rules="[(val) => !!val || `${'กรุณาเลือกระดับชั้นงาน'}`]"
              />
            </div>
          </div>

          <q-separator />
          <q-card-actions align="right" class="bg-white text-teal q-pa-sm">
            <q-btn
              type="submit"
              :label="`${isEditCheck ? 'แก้ไขตำแหน่ง' : 'เพิ่มตำแหน่ง'}`"
              color="public"
            />
          </q-card-actions>
        </form>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>
