<!-- card ข้อมูลส่วนตัว -->
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import type { PropType } from "vue";

import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useProfileDataStore } from "@/modules/05_placement/store";
import http from "@/plugins/http";
import config from "@/app.config";

import type {
  Information,
  DataOption,
} from "@/modules/05_placement/components/PersonalDetail/profileType";
import type { QForm } from "quasar";
import { defaultInformation } from "@/modules/05_placement/components/PersonalDetail/profileType";

import HeaderTop from "@/modules/05_placement/components/PersonalDetail/Information/top.vue";

const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin();
const profileStore = useProfileDataStore();
const { changeRetireText, changeBirth } = profileStore;
const {
  date2Thai,
  success,
  dateToISO,
  messageError,
  modalError,
  showLoader,
  hideLoader,
  dialogConfirm,
  convertDateToAPI,
} = mixin;

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
  notiNoEdit: {
    type: Function,
    default: () => console.log("not function"),
  },
  fetch: {
    type: Function,
    default: () => console.log("not function"),
  },
  data: {
    type: Object as PropType<Information>,
    default: defaultInformation,
  },
  Ops: {
    type: Object as PropType<any>,
  },
  OpsFilter: {
    type: Object as PropType<any>,
  },
});
const emit = defineEmits(["update:statusEdit"]);

const myform = ref<QForm | null>(null);
const onEdit = ref<boolean>(false); //การแก้ไขข้อมูล
const edit = ref<boolean>(false); //การแก้ไขข้อมูล
const informaData = ref<Information>(props.data); //ข้อมูลส่วนตัว
const age = ref<boolean>(true); //อายุ

const onCancel = async () => {
  if (myform.value != null) {
    myform.value.reset();
  }
  if (onEdit.value) {
    dialogConfirm(
      $q,
      async () => {
        emit("update:statusEdit", false);
        await props.fetch("Information");
        edit.value = false;
        onEdit.value = false;
      },
      `ข้อมูลมีการแก้ไข`,
      `ยืนยันยกเลิกการแก้ไขใช่หรือไม่?`
    );
  } else {
    edit.value = false;
  }
};

/**
 * ฟังก์ชันค้นหาข้อมูลในรายการตัวเลือก
 * @param val คำค้นหา
 * @param update ฟังก์ชัน
 * @param refData ประเภทของตัวเลือก
 */
const filterSelector = (val: string, update: Function, refData: string) => {
  switch (refData) {
    case "prefixOps":
      update(() => {
        props.Ops.prefixOps = props.OpsFilter.prefixOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "genderOps":
      update(() => {
        props.Ops.genderOps = props.OpsFilter.genderOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "bloodOps":
      update(() => {
        props.Ops.bloodOps = props.OpsFilter.bloodOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "statusOps":
      update(() => {
        props.Ops.statusOps = props.OpsFilter.statusOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "religionOps":
      update(() => {
        props.Ops.religionOps = props.OpsFilter.religionOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "employeeClassOps":
      update(() => {
        props.Ops.employeeClassOps = props.OpsFilter.employeeClassOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "employeeTypeOps":
      update(() => {
        props.Ops.employeeTypeOps = props.OpsFilter.employeeTypeOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    default:
      break;
  }
};

/**
 * ฟังก์เลือกวันเดือนปีเกิด
 * @param modelData วันเดือนปีเกิด
 */
const handleDate = async (modelData: Date) => {
  informaData.value.dateOfBirth = modelData;
  await calRetire(modelData);
  onEdit.value = true;
};

/**
 * ฟังก์ชันคำนวนวันเกษียณอายุราชการ
 * @param birth  วันเดือนปีเกิด
 */
const calRetire = async (birth: Date) => {
  const body = {
    birthDate: dateToISO(birth),
  };
  showLoader();
  await http
    .post(config.API.profileCalRetire, body)
    .then((res: any) => {
      const data = res.data.result;
      informaData.value.age =
        data.age.year +
        " ปี " +
        data.age.month +
        " เดือน" +
        data.age.day +
        " วัน";
      changeRetireText(data.retireDate);
      age.value = true;
    })
    .catch((e: any) => {
      age.value = false;
      messageError($q, e);
      const retire = new Date(`${birth.getFullYear() + 60}-09-30`);
      changeRetireText(date2Thai(retire));
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 * บันทึกการแก้ไขข้อมูล
 */
const editData = async () => {
  dialogConfirm($q, async () => {
    if (age.value == false) {
      modalError($q, "พบข้อผิดพลาด", "วันเกิดไม่ถูกต้อง");
      return;
    }
    showLoader();
    const body: any = {
      citizenId: informaData.value.idCard,
      prefix: informaData.value.prefixId,
      firstName: informaData.value.firstname,
      lastName: informaData.value.lastname,
      gender: informaData.value.genderId,
      nationality: informaData.value.nationality,
      race: informaData.value.race,
      religion: informaData.value.religionId,
      birthDate: convertDateToAPI(informaData.value.dateOfBirth),
      bloodGroup: informaData.value.bloodGroupId,
      relationship: informaData.value.relationshipId,
      telephoneNumber: informaData.value.telephone,
    };
    showLoader();
    await http
      .put(
        config.API.placementInformationId(route.params.personalId.toString()),
        body
      )
      .then(async () => {
        edit.value = false;
        emit("update:statusEdit", false);
        await props.fetch("Information");
        await changeBirth(informaData.value.dateOfBirth ?? new Date());
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
};

/**
 * ฟังก์ชันการแก้ไขข้อมูล
 */
const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      props.notiNoEdit();
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
};

/**
 * ฟังก์ชันแก้ไขข้อมูล
 */
function checkEdit() {
  onEdit.value = true;
}

/**
 * ฟังก์ชันสำหรับคืนค่าชื่อคลาสตามค่าที่กำหนด
 * @param val ค่าที่ใช้กำหนดคลาส
 */
const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};

/**
 * ทำงานเมื่อมีการเรียกใช้ Components
 */
onMounted(async () => {
  emit("update:statusEdit", false);
});
</script>
<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md no-border">
    <q-form ref="myform" greedy @submit.prevent @validation-success="editData">
      <HeaderTop
        v-model:edit="edit"
        header="ข้อมูลส่วนตัว"
        icon="mdi-account"
        :history="false"
        :changeBtn="changeBtn"
        :disable="statusEdit"
        :cancel="onCancel"
      />

      <div class="row col-12 items-top q-col-gutter-x-sm q-col-gutter-y-sm">
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.idCard"
            maxlength="13"
            :rules="[
              (val:string) => !!val || `${'กรุณากรอก เลขประจำตัวประชาชน'}`,
              (val:string) =>
                val.length >= 13 ||
                `${'กรุณากรอกเลขประจำตัวประชาชนให้ครบ'}`,
            ]"
            label="เลขประจำตัวประชาชน"
            mask="#############"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            @update:modelValue="checkEdit"
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก คำนำหน้า'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="informaData.prefixId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.prefixOps"
            option-value="id"
            :label="`${'คำนำหน้า'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'prefixOps'
                      ) "
          />
        </div>

        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.firstname"
            :rules="[(val:string) => !!val || `${'กรุณากรอก ชื่อ'}`]"
            :label="`${'ชื่อ'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.lastname"
            :rules="[(val:string) => !!val || `${'กรุณากรอก นามสกุล'}`]"
            :label="`${'นามสกุล'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <datepicker
            v-model="informaData.dateOfBirth"
            :locale="'th'"
            autoApply
            :enableTimePicker="false"
            week-start="0"
            :max-date="new Date()"
            :disabled="!edit"
            @update:model-value="handleDate"
          >
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                :readonly="!edit"
                :borderless="!edit"
                :model-value="
                  informaData.dateOfBirth
                    ? date2Thai(informaData.dateOfBirth)
                    : ''
                "
                :rules="[(val:string) => !!val || `${'กรุณาเลือก วัน/เดือน/ปี เกิด'}`]"
                :label="`${'วัน/เดือน/ปี เกิด'}`"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    :style="
                      edit ? 'color: var(--q-primary)' : 'color: var(--q-grey)'
                    "
                  >
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :style="!edit ? '' : 'padding:0 12px;'"
            :model-value="informaData.age"
            :label="`${'อายุ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            @update:modelValue="checkEdit"
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก เพศ'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="informaData.genderId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.genderOps"
            option-value="id"
            :label="`${'เพศ'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'genderOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            @update:modelValue="checkEdit"
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก สถานภาพ'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="informaData.relationshipId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.statusOps"
            option-value="id"
            :label="`${'สถานภาพ'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'statusOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            @update:modelValue="checkEdit"
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :outlined="edit"
            dense
            lazy-rules
            v-model="informaData.bloodGroupId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.bloodOps"
            option-value="id"
            :label="`${'หมู่เลือด'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'bloodOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            @update:modelValue="checkEdit"
            :class="getClass(edit)"
            :outlined="edit"
            dense
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.nationality"
            :label="`${'สัญชาติ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            @update:modelValue="checkEdit"
            :class="getClass(edit)"
            :outlined="edit"
            dense
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.race"
            :label="`${'เชื้อชาติ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            @update:modelValue="checkEdit"
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก ศาสนา'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="informaData.religionId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.religionOps"
            option-value="id"
            :label="`${'ศาสนา'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'religionOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            @update:modelValue="checkEdit"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            type="tel"
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.telephone"
            :label="`${'เบอร์โทร'}`"
            mask="##########"
          />
        </div>
      </div>
    </q-form>
  </q-card>
</template>
