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

import type { DataOption } from "@/modules/04_registryNew/interface/index/Main";
import type { DataType } from "@/modules/04_registryNew/interface/response/Main";
import type {
  FormAddPerson,
  MyObjectRef,
} from "@/modules/04_registryNew/interface/request/Main";

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

/** importStore*/
import { useRegistryNewDataStore } from "@/modules/04_registryNew/store";
import { useCounterMixin } from "@/stores/mixin";

const $q = useQuasar();
const store = useRegistryNewDataStore();
const {
  dialogRemove,
  dialogConfirm,
  success,
  messageError,
  showLoader,
  hideLoader,
  dialogMessageNotify,
} = useCounterMixin();

const modal = defineModel<boolean>("modal", { required: true });

const props = defineProps({
  fetchData: { type: Function },
  fetchType: { type: Function },
});

const prefixOps = ref<DataOption[]>([]);
const levelOps = ref<DataType[]>([]);

const formData = reactive<FormAddPerson>({
  prefix: "",
  firstName: "",
  lastName: "",
  citizenId: "",
  position: "",
  posTypeId: "",
  posLevelId: "",
});

const prefixRef = ref<object | null>(null);
const firstNameRef = ref<object | null>(null);
const lastNameRef = ref<object | null>(null);
const citizenIdRef = ref<object | null>(null);
const positionRef = ref<object | null>(null);
const posTypeIdRef = ref<object | null>(null);
const posLevelIdRef = ref<object | null>(null);

const objectRef: MyObjectRef = {
  prefix: prefixRef,
  firstName: firstNameRef,
  lastName: lastNameRef,
  citizenId: citizenIdRef,
  position: positionRef,
  posTypeId: posTypeIdRef,
  posLevelId: posLevelIdRef,
};

function fetchPrefix() {
  http
    .get(config.API.orgPrefix)
    .then((res) => {
      prefixOps.value = res.data.result.map((v: any) => ({
        id: v.name,
        name: v.name,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * function ตรวจสอบเลขประจำตัวประชาชน
 * @param citizenId เลขประจำตัวประชาชน
 */
function changeCardID(citizenId: string | number | null) {
  if (citizenId != null && typeof citizenId == "string") {
    if (citizenId.length == 13 && citizenId) {
      http
        .put(config.API.profileNewCitizenId(citizenId), {
          citizenId: citizenId,
        })
        .then(() => {})
        .catch((err) => {
          if (err.response.data.status === 500) {
            dialogMessageNotify($q, err.response.data.message);
          } else {
            messageError($q, err);
          }
        });
    }
  }
}

function fetchLevel(id: string) {
  const listLevel = store.posTypeMain.find((e: DataType) => e.id === id);
  levelOps.value = listLevel?.posLevels;

  const checkLevel = levelOps.value.filter(
    (e: DataType) => e.id === formData.posLevelId
  );
  if (checkLevel.length === 0) {
    formData.posLevelId = "";
  }
}

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

function clearFormData() {
  formData.prefix = "";
  formData.firstName = "";
  formData.lastName = "";
  formData.citizenId = "";
  formData.position = "";
  formData.posTypeId = "";
  formData.posLevelId = "";
}

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

async function onSubmit() {
  showLoader();
  await http
    .post(config.API.registryNew, formData)
    .then(() => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      props.fetchData?.();
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

watch(
  () => modal.value,
  () => {
    if (modal.value) {
      fetchPrefix();
      props.fetchType?.();
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 350px">
      <form @submit.prevent="validateForm">
        <q-card-section class="flex justify-between" style="padding: 0">
          <DialogHeader tittle="เพิ่มข้อมูล" :close="closeDialog" />
        </q-card-section>

        <q-separator />
        <q-card-section class="q-pa-md q-col-gutter-md">
          <q-select
            bg-color="white"
            ref="prefixRef"
            v-model="formData.prefix"
            label="คำนำหน้าชื่อ"
            outlined
            dense
            :options="prefixOps"
            option-label="name"
            option-value="id"
            map-options
            hide-bottom-space
            :rules="[(val) => !!val || 'กรุณาเลือกคำนำหน้าชื่อ']"
            emit-value
          />
          <q-input
            bg-color="white"
            ref="firstNameRef"
            outlined
            v-model="formData.firstName"
            label="ชื่อ"
            dense
            lazy-rules
            borderless
            :rules="[(val) => val.length > 0 || 'กรุณากรอกชื่อ']"
            hide-bottom-space
          />
          <q-input
            bg-color="white"
            ref="lastNameRef"
            outlined
            v-model="formData.lastName"
            label="นามสกุล"
            dense
            lazy-rules
            borderless
            :rules="[(val) => val.length > 0 || 'กรุณากรอกนามสกุล']"
            hide-bottom-space
          />
          <q-input
            bg-color="white"
            ref="citizenIdRef"
            outlined
            v-model="formData.citizenId"
            label="เลขประจำตัวประชาชน"
            dense
            lazy-rules
            borderless
            :rules="[
                        (val: string) => !!val || `${'กรุณากรอกเลขประจำตัวประชาชน'}`,
                        (val: string) =>
                          val.length >= 13 ||
                          `${'กรุณากรอกเลขประจำตัวประชาชนให้ครบ'}`,
                      ]"
            maxlength="13"
            hide-bottom-space
            mask="#############"
            @update:model-value="changeCardID"
          />
          <q-input
            bg-color="white"
            ref="positionRef"
            outlined
            v-model="formData.position"
            label="ตำแหน่ง"
            dense
            lazy-rules
            borderless
            :rules="[(val) => val.length > 0 || 'กรุณากรอกตำแหน่ง']"
            hide-bottom-space
          />
          <q-select
            bg-color="white"
            ref="posTypeIdRef"
            v-model="formData.posTypeId"
            label="ประเภทตำแหน่ง"
            outlined
            :options="store.posTypeOps"
            dense
            options-cover
            map-options
            emit-value
            option-label="name"
            option-value="id"
            hide-bottom-space
            :rules="[(val) => !!val || 'กรุณาเลือกประเภทตำแหน่ง']"
            @update:model-value="fetchLevel"
          />
          <q-select
            bg-color="white"
            ref="posLevelIdRef"
            v-model="formData.posLevelId"
            label="ระดับตำแหน่ง"
            :options="levelOps"
            outlined
            dense
            map-options
            emit-value
            option-label="posLevelName"
            option-value="id"
            options-cover
            hide-bottom-space
            :rules="[(val) => !!val || 'กรุณาเลือกระดับตำแหน่ง']"
          />
        </q-card-section>

        <q-separator />
        <q-card-actions align="right">
          <q-btn
            id="onSubmit"
            type="submit"
            dense
            unelevated
            label="บันทึก"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
