<!-- card ข้อมูลส่วนตัว -->
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import type {
  Information,
  DataOption,
} from "@/modules/05_placement/components/PersonalDetail/profileType";
import { defaultInformation } from "@/modules/05_placement/components/PersonalDetail/profileType";

import type {
  InformationOps,
  optionData,
} from "@/modules/05_placement/interface/index/Main";
import HeaderTop from "@/modules/05_placement/components/PersonalDetail/Information/top.vue";

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

import type { QForm } from "quasar";
import type { PropType } from "vue";

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,
  },
});
const emit = defineEmits(["update:statusEdit"]);

const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  success,
  dateToISO,
  messageError,
  modalError,
  showLoader,
  hideLoader,
} = mixin;

const profileStore = useProfileDataStore();
const { changeRetireText, changeBirth } = profileStore;
const edit = ref<boolean>(false);
const informaData = ref<Information>(props.data);
const age = ref<boolean>(true);
const myform = ref<QForm | null>(null);
const Ops = ref<InformationOps>({
  prefixOps: [],
  genderOps: [],
  bloodOps: [],
  statusOps: [],
  religionOps: [],
  employeeClassOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
  employeeTypeOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
});
const OpsFilter = ref<InformationOps>({
  prefixOps: [],
  genderOps: [],
  bloodOps: [],
  statusOps: [],
  religionOps: [],
  employeeClassOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
  employeeTypeOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
});

onMounted(async () => {
  await fetchPerson();
  emit("update:statusEdit", false);
});

const onCancel = async () => {
  if (myform.value != null) {
    myform.value.reset();
  }
  await props.fetch();
};

/**
 * get รายการ ข้อมูลเกี่ยวกับบุคคล
 */
const fetchPerson = async () => {
  showLoader();
  await http
    .get(config.API.person)
    .then((res) => {
      const data = res.data.result;
      let optionbloodGroups: optionData[] = [];
      //   console.log(data);
      data.bloodGroups.map((r: any) => {
        optionbloodGroups.push({
          id: r.id ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.bloodOps = optionbloodGroups;
      OpsFilter.value.bloodOps = optionbloodGroups;

      let optiongenders: optionData[] = [];
      data.genders.map((r: any) => {
        optiongenders.push({
          id: r.id ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.genderOps = optiongenders;
      OpsFilter.value.genderOps = optiongenders;

      let optionprefixs: optionData[] = [];
      data.prefixs.map((r: any) => {
        optionprefixs.push({
          id: r.id ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.prefixOps = optionprefixs;
      OpsFilter.value.prefixOps = optionprefixs;

      let optionrelationships: optionData[] = [];
      data.relationships.map((r: any) => {
        optionrelationships.push({
          id: r.id ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.statusOps = optionrelationships;
      OpsFilter.value.statusOps = optionrelationships;

      let optionreligions: optionData[] = [];
      data.religions.map((r: any) => {
        optionreligions.push({
          id: r.id ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.religionOps = optionreligions;
      OpsFilter.value.religionOps = optionreligions;
    })
    .catch((e: any) => {})
    .finally(() => {
      hideLoader();
    });
};

const filterSelector = (val: any, update: Function, refData: string) => {
  switch (refData) {
    case "prefixOps":
      update(() => {
        Ops.value.prefixOps = OpsFilter.value.prefixOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "genderOps":
      update(() => {
        Ops.value.genderOps = OpsFilter.value.genderOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "bloodOps":
      update(() => {
        Ops.value.bloodOps = OpsFilter.value.bloodOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "statusOps":
      update(() => {
        Ops.value.statusOps = OpsFilter.value.statusOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "religionOps":
      update(() => {
        Ops.value.religionOps = OpsFilter.value.religionOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "employeeClassOps":
      update(() => {
        Ops.value.employeeClassOps = OpsFilter.value.employeeClassOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "employeeTypeOps":
      update(() => {
        Ops.value.employeeTypeOps = OpsFilter.value.employeeTypeOps.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    default:
      break;
  }
};

const handleDate = async (modelData: Date) => {
  informaData.value.dateOfBirth = modelData;
  await calRetire(modelData);
};

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;
      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 () => {
  if (age.value == false) {
    modalError($q, "พบข้อผิดพลาด", "วันเกิดไม่ถูกต้อง");
    return;
  }

  const body: any = {
    citizenId: informaData.value.idCard,
    prefixId: informaData.value.prefixId,
    firstName: informaData.value.firstname,
    lastName: informaData.value.lastname,
    genderId: informaData.value.genderId,
    nationality: informaData.value.nationality,
    race: informaData.value.race,
    religionId: informaData.value.religionId,
    birthDate: informaData.value.dateOfBirth,
    bloodGroupId: informaData.value.bloodGroupId,
    relationshipId: informaData.value.relationshipId,
    telephoneNumber: informaData.value.telephone,
  };
  showLoader();
  await http
    .put(
      config.API.placementInformationId(route.params.personalId.toString()),
      body
    )
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      edit.value = false;
      emit("update:statusEdit", false);
      await props.fetch();
      await changeBirth(informaData.value.dateOfBirth ?? new Date());
    });
};

const saveData = async () => {
  if (myform.value != null) {
    await myform.value.validate().then(async (success: boolean) => {
      if (success) {
        await editData();
      }
    });
  }
};

const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false;
      props.notiNoEdit();
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md no-border">
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลส่วนตัว"
      icon="mdi-account"
      :save="saveData"
      :history="false"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :cancel="onCancel"
    />
    <q-form ref="myform" class="col-12">
      <div class="row col-12 items-center 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="#############"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :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:any,
                      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="`${'ชื่อ'}`"
          />
        </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="`${'นามสกุล'}`"
          />
        </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
                lazy-rules
                :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
            :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:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'genderOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :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:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'statusOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :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.bloodGroupId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.bloodOps"
            option-value="id"
            :label="`${'หมู่เลือด'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'bloodOps'
                      ) "
          />
        </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.nationality"
            :rules="[(val:string) => !!val || `${'กรุณากรอก สัญชาติ'}`]"
            :label="`${'สัญชาติ'}`"
          />
        </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.race"
            :rules="[(val:string) => !!val || `${'กรุณากรอก เชื้อชาติ'}`]"
            :label="`${'เชื้อชาติ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :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:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'religionOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            type="tel"
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.telephone"
            :rules="[
              (val:string) => !!val || `${'กรุณากรอก เบอร์โทร'}`,
              (val:string) => val.length >= 10 || `${'กรุณากรอกข้อมูลเบอร์โทรให้ครบ'}`,
            ]"
            :label="`${'เบอร์โทร'}`"
            mask="##########"
          />
        </div>
      </div>
    </q-form>
  </q-card>
</template>
