<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md">
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลส่วนตัว"
      icon="mdi-account"
      :save="saveData"
      :history="!statusAdd()"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :cancel="onCancel"
      :historyClick="clickHistory"
      :addEmployee="statusAdd()"
    />
    <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.cardid"
            @update:model-value="changeCardID"
            :rules="[
              (val:string) => !!val || `${'กรุณากรอก เลขบัตรประจำตัวประชาชน'}`,
              (val:string) =>
                val.length >= 13 ||
                `${'กรุณากรอกเลขบัตรประจำตัวประชาชนให้ครบ'}`,
            ]"
            label="เลขบัตรประจำตัวประชาชน"
            maxlength="13"
            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-2 col-md-2">
          <datepicker
            v-model="informaData.birthDate"
            :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="date2Thai(informaData.birthDate)"
                :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-2 col-md-2">
          <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-2 col-md-2">
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :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-2 col-md-2">
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :outlined="edit"
            dense
            lazy-rules
            v-model="informaData.statusId"
            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-2 col-md-2">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.nationality"
            :label="`${'สัญชาติ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-2 col-md-2">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.ethnicity"
            :label="`${'เชื้อชาติ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-2 col-md-2">
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :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-2 col-md-2">
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :outlined="edit"
            dense
            lazy-rules
            v-model="informaData.bloodId"
            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'
                      ) "
            clearable
          />
        </div>
        <div class="col-xs-6 col-sm-2 col-md-2">
          <q-input
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            type="tel"
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaData.tel"
            :label="`${'เบอร์โทร'}`"
            :rules="[
              (val:string) => !!val || `${'กรุณากรอก เบอร์โทร'}`,
              (val:string) =>
                val.length >= 10 ||
                `${'กรุณากรอกเบอร์โทรให้ครบ'}`,
            ]"
            mask="##########"
          />
        </div>
        <div
          class="col-xs-6 col-sm-3 col-md-3"
          v-if="informaData.profileType == 'employee'"
        >
          <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.employeeType"
            emit-value
            map-options
            option-label="name"
            :options="Ops.employeeTypeOps"
            option-value="id"
            :label="`${'ประเภทการจ้าง'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'employeeTypeOps'
                      ) "
          />
        </div>
        <div
          class="col-xs-6 col-sm-3 col-md-3"
          v-if="informaData.profileType == 'employee'"
        >
          <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.employeeClass"
            emit-value
            map-options
            option-label="name"
            :options="Ops.employeeClassOps"
            option-value="id"
            :label="`${'ประเภทลูกจ้าง'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'employeeClassOps'
                      ) "
          />
        </div>
        <div class="col-12 q-pt-md q-pb-sm"><q-separator /></div>
        <div class="col-xs-12 q-col-gutter-x-sm items-center flex q-my-sm">
          <label class="text-weight-bold">• เปลี่ยนชื่อ-นามสกุล</label>
          <q-radio
            v-model="same"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="1"
            label="มี"
            dense
            :disable="!edit"
          />
          <q-radio
            v-model="same"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="0"
            label="ไม่มี"
            color="grey-9"
            dense
            :disable="!edit"
          />
        </div>
        <div class="row col-12">
          <OldName
            v-if="same == '1'"
            v-model:statusEdit="edit"
            :fetchDataInformation="fetchDataComponent"
            :perfixId="informaData.prefixId == null ? '' : informaData.prefixId"
            :firstname="
              informaData.firstname == null ? '' : informaData.firstname
            "
            :lastname="informaData.lastname == null ? '' : informaData.lastname"
          />
        </div>
      </div>
    </q-form>
  </q-card>
  <HistoryTable
    :rows="rowsHistory"
    :columns="columnsHistory"
    :filter="filterHistory"
    :visible-columns="visibleColumnsHistory"
    v-model:modal="modalHistory"
    v-model:inputfilter="filterHistory"
    v-model:inputvisible="visibleColumnsHistory"
    v-model:tittle="tittleHistory"
  >
    <template #columns="props">
      <q-tr :props="props">
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div
            v-if="col.name == 'birthDate' || col.name == 'createdAt'"
            class="table_ellipsis"
          >
            {{ date2Thai(col.value) }}
          </div>
          <div v-else class="table_ellipsis">
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";

import { useQuasar } from "quasar";
import type {
  Information,
  DataOption,
} from "@/modules/04_registry/components/profileType";
import { defaultInformation } from "@/modules/04_registry/components/profileType";
import type {
  RequestItemsHistoryObject,
  Columns,
} from "@/modules/04_registry/interface/request/Information";
import type { ResponseObject } from "@/modules/04_registry/interface/response/Information";
import type { InformationOps } from "@/modules/04_registry/interface/index/Main";
import OldName from "@/modules/04_registry/components/Information/OldName.vue";
import HeaderTop from "@/modules/04_registry/components/Information/top.vue";
import HistoryTable from "@/components/TableHistory.vue";
import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";
import { useProfileDataStore } from "@/modules/04_registry/store";
import type { QTableColumn, QForm } from "quasar";

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
  fetchDataProfile: {
    type: Function,
    default: () => console.log("not function"),
  },
  statusAdd: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:statusEdit"]);

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

const profileStore = useProfileDataStore();
const { changeRetireText, changeBirth } = profileStore;
const edit = ref<boolean>(false);
const defaultCitizenData = ref<string | null>("");
const informaData = ref<Information>(defaultInformation);
const rowsHistory = ref<RequestItemsHistoryObject[]>([]); //select data history
const tittleHistory = ref<string>("ประวัติแก้ไขข้อมูลส่วนตัว"); //
const filterHistory = ref<string>(""); //search data table history
const modalHistory = ref<boolean>(false); //modal ประวัติการแก้ไขข้อมูล
const myform = ref<QForm | null>(null);
const dateBefore = ref<Date>(new Date());
const same = ref<string>("0");
const Ops = ref<InformationOps>({
  prefixOps: [],
  prefixOldOps: [],
  genderOps: [],
  bloodOps: [],
  statusOps: [],
  religionOps: [],
  employeeClassOps: [
    { id: "perm", name: "ลูกจ้างประจำ" },
    { id: "temp", name: "ลูกจ้างชั่วคราว" },
  ],
  employeeTypeOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
});
const OpsFilter = ref<InformationOps>({
  prefixOps: [],
  prefixOldOps: [],
  genderOps: [],
  bloodOps: [],
  statusOps: [],
  religionOps: [],
  employeeClassOps: [
    { id: "perm", name: "ลูกจ้างประจำ" },
    { id: "temp", name: "ลูกจ้างชั่วคราว" },
  ],
  employeeTypeOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
});
const columnsHistory = ref<QTableColumn[]>([
  {
    name: "citizenId",
    align: "left",
    label: "เลขบัตรประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "prefix",
    align: "left",
    label: "คำนำหน้าชื่อ",
    sortable: true,
    field: "prefix",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "firstName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastName",
    align: "left",
    label: "นามสกุล",
    sortable: true,
    field: "lastName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "birthDate",
    align: "left",
    label: "วัน/เดือน/ปี เกิด",
    sortable: true,
    field: "birthDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "gender",
    align: "left",
    label: "เพศ",
    sortable: true,
    field: "gender",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "relationship",
    align: "left",
    label: "สถานภาพ",
    sortable: true,
    field: "relationship",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "bloodGroup",
    align: "left",
    label: "หมู่เลือด",
    sortable: true,
    field: "bloodGroup",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "nationality",
    align: "left",
    label: "สัญชาติ",
    sortable: true,
    field: "nationality",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "race",
    align: "left",
    label: "เชื้อชาติ",
    sortable: true,
    field: "race",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "religion",
    align: "left",
    label: "ศาสนา",
    sortable: true,
    field: "religion",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "telephoneNumber",
    align: "left",
    label: "เบอร์โทร",
    sortable: true,
    field: "telephoneNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "employeeType",
    align: "left",
    label: "ประเภทการจ้าง",
    sortable: true,
    field: "employeeType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "employeeClass",
    align: "left",
    label: "ประเภทลูกจ้าง",
    sortable: true,
    field: "employeeClass",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumnsHistory = ref<String[]>([
  "citizenId",
  "prefix",
  "firstName",
  "lastName",
  "birthDate",
  "gender",
  "relationship",
  "bloodGroup",
  "nationality",
  "race",
  "religion",
  "telephoneNumber",
  "employeeType",
  "employeeClass",
  "createdFullName",
  "createdAt",
]);

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

const statusAdd = () => props.statusAdd;

const defaultAdd = () => {
  if (props.statusAdd) {
    edit.value = props.statusAdd;
    informaData.value = {
      cardid: null,
      age: null,
      prefix: null,
      prefixId: null,
      firstname: null,
      lastname: null,
      birthDate: new Date(),
      genderId: null,
      bloodId: null,
      nationality: null,
      ethnicity: null,
      statusId: null,
      religionId: null,
      tel: null,
      employeeType: null,
      employeeClass: null,
      profileType: null,
    };
  }
};

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

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

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

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

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

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

const changeCardID = (value: string | number | null) => {
  if (value != null && typeof value == "string") {
    if (value.length == 13 && value != defaultCitizenData.value) {
      dialogMessage(
        $q,
        "ข้อมูลมีการแก้ไข?",
        "ยืนยันการเปลี่ยนเลขบัตรประชาชนใช่หรือไม่",
        "info",
        "ยืนยัน",
        "public",
        async () => {
          await checkCitizen(value);
        },
        async () => {
          informaData.value.cardid = defaultCitizenData.value;
        }
      );
    }
  }
};

const checkCitizen = async (id: string) => {
  showLoader();
  await http
    .get(config.API.profileCitizenId(id))
    .then((res) => {
      const data = res.data.result.citizen;

      if (!data) {
        dialogMessage(
          $q,
          "ข้อความแจ้งเตือน",
          "เลขบัตรประจำตัวประชาชนนี้มีการใช้งานแล้ว",
          "warning",
          undefined,
          "orange",
          undefined,
          undefined,
          true
        );
        informaData.value.cardid = defaultCitizenData.value;
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 */
const clickHistory = async () => {
  modalHistory.value = true;
  showLoader();
  await http
    .get(config.API.profileInforHisId(route.params.id.toString()))
    .then((res) => {
      let data = res.data.result;
      rowsHistory.value = [];
      data.map((e: RequestItemsHistoryObject) => {
        rowsHistory.value.push({
          citizenId: e.citizenId,
          prefix: e.prefix,
          firstName: e.firstName,
          lastName: e.lastName,
          birthDate: new Date(e.birthDate),
          gender: e.gender,
          relationship: e.relationship,
          bloodGroup: e.bloodGroup,
          nationality: e.nationality,
          race: e.race,
          religion: e.religion,
          telephoneNumber: e.telephoneNumber,
          employeeType:
            e.employeeType == "gov"
              ? "งบประมาณเงินอุดหนุนรัฐบาล"
              : e.employeeType == "bkk"
              ? "งบประมาณกรุงเทพมหานคร"
              : "-",
          employeeClass:
            e.employeeClass == "perm"
              ? "ลูกจ้างประจำ"
              : e.employeeClass == "temp"
              ? "ลูกจ้างชั่วคราว"
              : "-",
          createdFullName: e.createdFullName,
          createdAt: new Date(e.createdAt),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .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.birthDate = modelData;
  await calRetire(modelData);
};

const fetchDataComponent = async (modelData: Date) => {
  await props.fetchDataProfile();
  await fetchData();
};

const calRetire = async (birth: Date) => {
  const body = {
    birthDate: dateToISO(birth),
  };
  if (dateToISO(dateBefore.value) != 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);
        dateBefore.value = birth;
      })
      .catch((e: any) => {
        messageError($q, e);
        const retire = new Date(`${birth.getFullYear() + 60}-09-30`);
        informaData.value.birthDate = dateBefore.value;
        changeRetireText(date2Thai(retire));
      })
      .finally(() => {
        hideLoader();
      });
  }
};

const fetchData = async () => {
  if (route.params.id) {
    showLoader();
    await http
      .get(config.API.profileInforId(route.params.id.toString()))
      .then(async (res: any) => {
        const data: ResponseObject = res.data.result;
        defaultCitizenData.value = data.citizenId;
        informaData.value.cardid = data.citizenId;
        informaData.value.prefix = "";
        informaData.value.prefixId = data.prefixId;
        informaData.value.firstname = data.firstName;
        informaData.value.lastname = data.lastName;
        informaData.value.birthDate = new Date(data.birthDate);
        informaData.value.genderId = data.genderId;
        informaData.value.bloodId = data.bloodGroupId;
        informaData.value.nationality = data.nationality;
        informaData.value.ethnicity = data.race;
        informaData.value.statusId = data.relationshipId;
        informaData.value.religionId = data.religionId;
        informaData.value.tel = data.telephoneNumber;
        informaData.value.age = data.age;
        informaData.value.employeeType = data.employeeType;
        informaData.value.employeeClass = data.employeeClass;
        informaData.value.profileType = data.profileType;
        dateBefore.value = new Date(data.birthDate);
        same.value = data.changeName == true ? "1" : "0";
        await calRetire(new Date(dateToISO(new Date(data.birthDate))));
        if (
          data.profileType == "officer" &&
          columnsHistory.value.length >= 15
        ) {
          columnsHistory.value.splice(13, 1);
          columnsHistory.value.splice(12, 1);
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        //   hideLoader();
        await props.fetchDataProfile();
      });
  }
};

const editData = async () => {
  const body: any = {
    citizenId: informaData.value.cardid,
    prefixId: informaData.value.prefixId,
    firstName: informaData.value.firstname,
    lastName: informaData.value.lastname,
    genderId: informaData.value.genderId,
    nationality: informaData.value.nationality,
    race: informaData.value.ethnicity,
    religionId: informaData.value.religionId,
    birthDate: dateToISO(informaData.value.birthDate) ?? dateToISO(new Date()),
    bloodGroupId: informaData.value.bloodId,
    relationshipId: informaData.value.statusId,
    telephoneNumber: informaData.value.tel,
    createdAt: new Date(),
    age: null,
    employeeType: informaData.value.employeeType,
    employeeClass: informaData.value.employeeClass,
    profileType: informaData.value.profileType,
    createdFullName: "-",
  };
  showLoader();
  await http
    .put(config.API.profileInforId(route.params.id.toString()), body)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      edit.value = false;
      emit("update:statusEdit", false);
      await fetchData();
      await changeBirth(informaData.value.birthDate ?? new Date());
    });
};

const addData = async () => {
  //     showLoader();
  //   await http
  //     .put(config.API.profileInforId(route.params.id.toString()), body)
  //     .then((res) => {
  //       success($q, "บันทึกข้อมูลสำเร็จ");
  //     })
  //     .catch((e) => {
  //       messageError($q, e);
  //     })
  //     .finally(async () => {
  //       edit.value = false;
  //       emit("update:statusEdit", false);
  //       await fetchData();
  //       await changeBirth(informaData.value.birthDate ?? new Date());
  //     });
};

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

const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false;
    } 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>
