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

/** importType*/
import type { DataOption } from "@/modules/08_registryEmployee/interface/index/Main";
import type { FormDataEmployee } from "@/modules/08_registryEmployee/interface/request/Employee";
import type { ResOptionPerson } from "@/modules/08_registryEmployee/interface/response/Employee";

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

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useRegistryEmp } from "@/modules/08_registryEmployee/stores/registry-employee";

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

/**  props*/
const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  fetchData: { type: Function, require: true },
});

const formData = reactive<FormDataEmployee>({
  citizenId: "", //เลขประจำตัวประชาชน
  prefix: "", //คำนำหน้าชื่อ
  rank: "", //ยศ
  firstName: "", //ชื่อ
  lastName: "", //นามสกุล
  birthDate: null, //วัน/เดือน/ปี เกิด
  gender: "", //เพศ
  relationship: "", //สถานภาพ
  nationality: "", //สัญชาติ
  ethnicity: "", //เชื้อชาติ
  religion: "", //ศาสนา
  bloodGroup: "", //หมู่เลือด
  phone: "", //เบอร์โทร
  employeeClass: "TEMP",
});

//ตัวเลือก
const prefixOpsMain = ref<DataOption[]>([]); //คำนำหน้าชื่อ
const prefixOps = ref<DataOption[]>([]); //คำนำหน้าชื่อ
const rankOpsMain = ref<DataOption[]>([]); //ยศ
const rankOps = ref<DataOption[]>([]); //ยศ
const genderOpsMain = ref<DataOption[]>([]); //เพศ
const genderOps = ref<DataOption[]>([]); //เพศ
const statusOpsMain = ref<DataOption[]>([]); //สถานภาพ
const statusOps = ref<DataOption[]>([]); //สถานภาพ
const religionOpsMain = ref<DataOption[]>([]); // ศาสนา
const religionOps = ref<DataOption[]>([]); //ศาสนา
const bloodOpsMain = ref<DataOption[]>([]); //หมู่เลือด
const bloodOps = ref<DataOption[]>([]); //หมู่เลือด

/**
 * ฟังก์ชันดึงข้อมูลเกี่ยวกับข้อมูลส่วนตัว
 */
function fetchDataPerson() {
  showLoader();
  http
    .get(config.API.profileNewMetaMain)
    .then((res) => {
      const data = res.data.result;

      let optionPerfix: DataOption[] = [];
      data.prefixs.map((r: ResOptionPerson) => {
        optionPerfix.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      prefixOpsMain.value = optionPerfix;

      let optionrank: DataOption[] = [];
      data.rank.map((r: ResOptionPerson) => {
        optionrank.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      rankOpsMain.value = optionrank;

      let optiongenders: DataOption[] = [];
      data.genders.map((r: ResOptionPerson) => {
        optiongenders.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      genderOpsMain.value = optiongenders;

      let optionrelationships: DataOption[] = [];
      data.relationships.map((r: ResOptionPerson) => {
        optionrelationships.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      statusOpsMain.value = optionrelationships;

      let optionreligions: DataOption[] = [];
      data.religions.map((r: ResOptionPerson) => {
        optionreligions.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      religionOpsMain.value = optionreligions;

      let optionBlood: DataOption[] = [];
      data.bloodGroups.map((r: ResOptionPerson) => {
        optionBlood.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      bloodOpsMain.value = optionBlood;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันเช็คเลขบัตรประจำตัวซ้ำ
 * @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 ค้นหาข้อมูล Option
 * @param val คำค้นหา
 * @param update function
 * @param refData ประเภท
 */
function filterSelector(val: string, update: Function, refData: string) {
  switch (refData) {
    case "prefix":
      update(() => {
        prefixOps.value = prefixOpsMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "rank":
      update(() => {
        rankOps.value = rankOpsMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "gender":
      update(() => {
        genderOps.value = genderOpsMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "status":
      update(() => {
        statusOps.value = statusOpsMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "religion":
      update(() => {
        religionOps.value = religionOpsMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "blood":
      let f = val.toLocaleUpperCase();
      update(() => {
        bloodOps.value = bloodOpsMain.value.filter(
          (v: DataOption) => v.name.indexOf(f) > -1
        );
      });
      break;

    default:
      break;
  }
}

/**
 * ฟังก์ชันคำนวนอายุ
 */
function calculateMaxDate() {
  const today = new Date();
  today.setFullYear(today.getFullYear() - 18);
  return today;
}

/**
 * ฟังก์ชันบันทึกข้อมูลลูกจ้างชั่วคราว
 */
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .post(config.API.registryNew("-employee"), formData)
      .then(async () => {
        await props.fetchData?.();
        await success($q, "บันทึกข้อมูลสำเร็จ");
        closeDialog();
      })
      .catch((err) => {
        messageError($q, err);
        hideLoader();
      });
  });
}

/**
 * ฟังก์ชันปืด popup
 */
function closeDialog() {
  modal.value = false;
  formData.citizenId = "";
  formData.prefix = "";
  formData.rank = "";
  formData.firstName = "";
  formData.lastName = "";
  formData.birthDate = null;
  formData.gender = "";
  formData.relationship = "";
  formData.nationality = "";
  formData.ethnicity = "";
  formData.religion = "";
  formData.bloodGroup = "";
  formData.phone = "";
}

watch(
  () => modal.value,
  () => {
    if (modal.value) {
      fetchDataPerson();
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 600px">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          tittle="เพิ่มข้อมูลลูกจ้างชั่วคราว"
          :close="closeDialog"
        />

        <q-separator />
        <q-card-section class="q-pa-md q-col-gutter-md">
          <div class="row q-col-gutter-md">
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                maxlength="13"
                mask="#############"
                v-model="formData.citizenId"
                class="inputgreen"
                label="เลขประจำตัวประชาชน"
                :rules="[
                  (val: string) => !!val || `${'กรุณากรอก เลขประจำตัวประชาชน'}`,
                  (val: string) =>
                    val.length >= 13 ||
                    `${'กรุณากรอกเลขประจำตัวประชาชนให้ครบ'}`,
                ]"
                @update:model-value="changeCardID"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                use-input
                lazy-rules
                emit-value
                map-options
                hide-bottom-space
                input-debounce="0"
                option-label="name"
                option-value="name"
                v-model="formData.prefix"
                class="inputgreen"
                :options="prefixOps"
                label="คำนำหน้าชื่อ"
                :rules="[(val: string) => !!val || `${'กรุณาเลือก คำนำหน้าชื่อ'}`]"
                @filter="(inputValue: string,
                doneFn: Function) => filterSelector(inputValue, doneFn, 'prefix'
                )"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                clearable
                use-input
                lazy-rules
                emit-value
                map-options
                hide-bottom-space
                input-debounce="0"
                option-label="name"
                option-value="name"
                v-model="formData.rank"
                class="inputgreen"
                :options="rankOps"
                label="ยศ"
                @filter="(inputValue: string,
                doneFn: Function) => filterSelector(inputValue, doneFn, 'rank'
                )"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.firstName"
                class="inputgreen"
                label="ชื่อ"
                :rules="[(val: string) => !!val || `${'กรุณากรอกชื่อ'}`]"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.lastName"
                class="inputgreen"
                label="นามสกุล"
                :rules="[(val: string) => !!val || `${'กรุณากรอกนามสกุล'}`]"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                autoApply
                :max-date="calculateMaxDate()"
                borderless
                :enableTimePicker="false"
                week-start="0"
                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"
                    ref="dateReceivedRef"
                    outlined
                    dense
                    hide-bottom-space
                    class="inputgreen"
                    :model-value="
                      formData.birthDate != null
                        ? date2Thai(formData.birthDate)
                        : null
                    "
                    label="วัน/เดือน/ปี เกิด"
                    :rules="[
                      (val:string) => !!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-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                readonly
                :model-value="
                  formData.birthDate !== null
                    ? calculateAge(formData.birthDate)
                    : null
                "
                label="อายุ"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                use-input
                clearable
                lazy-rules
                emit-value
                map-options
                hide-bottom-space
                input-debounce="0"
                option-label="name"
                option-value="name"
                v-model="formData.gender"
                class="inputgreen"
                :options="genderOps"
                label="เพศ"
                @filter="(inputValue: string,
                doneFn: Function) => filterSelector(inputValue, doneFn, 'gender'
                )"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                use-input
                clearable
                lazy-rules
                emit-value
                map-options
                hide-bottom-space
                option-value="name"
                option-label="name"
                input-debounce="0"
                class="inputgreen"
                v-model="formData.relationship"
                :options="statusOps"
                label="สถานภาพ"
                @filter="(inputValue: string,
                doneFn: Function) => filterSelector(inputValue, doneFn, 'status'
                )"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                v-model="formData.nationality"
                label="สัญชาติ"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                v-model="formData.ethnicity"
                label="เชื้อชาติ"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                use-input
                clearable
                lazy-rules
                emit-value
                map-options
                hide-bottom-space
                option-value="name"
                option-label="name"
                input-debounce="0"
                v-model="formData.religion"
                class="inputgreen"
                :options="religionOps"
                label="ศาสนา"
                @filter="(inputValue: string,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'religion'
              )"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                use-input
                clearable
                lazy-rules
                emit-value
                map-options
                hide-bottom-space
                option-value="name"
                option-label="name"
                input-debounce="0"
                v-model="formData.bloodGroup"
                class="inputgreen"
                :options="bloodOps"
                label="หมู่เลือด"
                @filter="(inputValue: string,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'blood'
              )"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                mask="##########"
                class="inputgreen"
                v-model="formData.phone"
                label="เบอร์โทร"
              />
            </div>
          </div>
        </q-card-section>

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

<style scoped></style>
