<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 { useProfileDataStore } from "@/modules/04_registryNew/stores/profile";
import DialogHeader from "@/components/DialogHeader.vue";

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

const profileStore = useProfileDataStore();
const $q = useQuasar();
const store = useRegistryNewDataStore();
const {
  dialogConfirm,
  success,
  messageError,
  hideLoader,
  dialogMessageNotify,
  date2Thai,
} = useCounterMixin();
const { calculateAge } = profileStore;
const modal = defineModel<boolean>("modal", { required: true });

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

const prefixOps = ref<DataOption[]>([]);
const rankOps = ref<DataOption[]>([]);
const levelOps = ref<DataType[]>([]);
const age = ref<string | null>("");
const formData = reactive<FormAddPerson>({
  prefix: "",
  firstName: "",
  lastName: "",
  citizenId: "",
  position: "",
  posTypeId: "",
  posLevelId: "",
  rank: "",
  birthDate: null,
});

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 fetchRank() {
  http
    .get(config.API.orgRank)
    .then((res) => {
      rankOps.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();
}

const calculateMaxDate = () => {
  const today = new Date();
  today.setFullYear(today.getFullYear() - 18);
  return today;
};

function clearFormData() {
  formData.prefix = "";
  formData.firstName = "";
  formData.lastName = "";
  formData.citizenId = "";
  formData.position = "";
  formData.posTypeId = "";
  formData.posLevelId = "";
  formData.rank = "";
  age.value = "";
  formData.birthDate = null;
}

async function onSubmit() {
  dialogConfirm($q, async () => {
    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();
      fetchRank();
      props.fetchType?.();
    }
  }
);

watch(
  () => formData.birthDate,
  (v) => {
    if (v) {
      age.value = calculateAge(v);
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 350px">
      <q-form @submit.prevent @validation-success="onSubmit()" greedy>
        <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">
          <div class="row q-gutter-sm">
            <div class="col">
              <q-select
                bg-color="white"
                v-model="formData.prefix"
                label="คำนำหน้าชื่อ"
                outlined
                dense
                lazy-rules
                :options="prefixOps"
                option-label="name"
                option-value="id"
                map-options
                hide-bottom-space
                :rules="[
                  (val) => {
                    return val.length > 0 || 'กรุณาเลือกคำนำหน้าชื่อ';
                  },
                ]"
                emit-value
              />
            </div>
            <div class="col">
              <q-select
                bg-color="white"
                v-model="formData.rank"
                label="ยศ"
                outlined
                dense
                :options="rankOps"
                option-label="name"
                option-value="id"
                map-options
                hide-bottom-space
                emit-value
              />
            </div>
          </div>
          <q-input
            bg-color="white"
            outlined
            v-model="formData.firstName"
            label="ชื่อ"
            dense
            lazy-rules
            borderless
            :rules="[(val) => val.length > 0 || 'กรุณากรอกชื่อ']"
            hide-bottom-space
          />
          <q-input
            bg-color="white"
            outlined
            v-model="formData.lastName"
            label="นามสกุล"
            dense
            lazy-rules
            borderless
            :rules="[(val) => val.length > 0 || 'กรุณากรอกนามสกุล']"
            hide-bottom-space
          />
          <q-input
            bg-color="white"
            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"
          />
          <div class="row q-col-gutter-sm">
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                autoApply
                borderless
                week-start="0"
                :max-date="calculateMaxDate()"
                :enableTimePicker="false"
                menu-class-name="modalfix"
                v-model="formData.birthDate"
                :locale="'th'"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    for="inputDatereceive"
                    outlined
                    dense
                    hide-bottom-space
                    class="inputgreen"
                    :model-value="
                      formData.birthDate != null
                        ? date2Thai(formData.birthDate)
                        : null
                    "
                    label="วัน/เดือน/ปี เกิด"
                    :rules="[
                      (val) => !!val || `${'กรุณาเลือก วัน/เดือน/ปี เกิด'}`,
                    ]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                readonly
                class="inputgreen"
                v-model="age"
                label="อายุ"
              />
            </div>
          </div>
          <q-input
            bg-color="white"
            outlined
            v-model="formData.position"
            label="ตำแหน่ง"
            dense
            lazy-rules
            borderless
            :rules="[(val) => val.length > 0 || 'กรุณากรอกตำแหน่ง']"
            hide-bottom-space
          />
          <q-select
            bg-color="white"
            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"
            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>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
