<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useRouter } from "vue-router";
import type { QForm } from "quasar";

import { useProfileDataStore } from "@/modules/08_registryEmployee/store";
import type {
  Information,
  DataOption,
  DataOptioninfo
} from "@/modules/04_registry/components/profileType";
import type { InformationOps } from "@/modules/04_registry/interface/index/Main";
import HeaderTop from "@/modules/08_registryEmployee/components/AddEmployee/HeaderTop.vue";

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

const profileStore = useProfileDataStore();
const { changeRetireText, changeBirth } = profileStore;

const informaData = ref<Information>({
  cardid: null,
  age: null,
  prefix: null,
  prefixId: null,
  firstname: null,
  lastname: null,
  birthDate: null,
  genderId: null,
  bloodId: null,
  nationality: null,
  ethnicity: null,
  statusId: null,
  religionId: null,
  tel: null,
  employeeType: null,
  employeeClass: null,
  profileType: null,
});

const myform = ref<QForm | null>(null);
const dateBefore = ref<Date>(new Date());
// รายการข้อมูลทั้งหมด
const Ops = ref<InformationOps>({
  prefixOps: [],
  prefixOldOps: [],
  genderOps: [],
  bloodOps: [],
  statusOps: [],
  religionOps: [],
  employeeClassOps: [],
  employeeTypeOps: [],
});
// ข้อมูลเมื่อเลือกแล้ว
const OpsFilter = ref<InformationOps>({
  prefixOps: [],
  prefixOldOps: [],
  genderOps: [],
  bloodOps: [],
  statusOps: [],
  religionOps: [],
  employeeClassOps: [],
  employeeTypeOps: [],
});

// call function get รายการข้อมูลต่างๆ
onMounted(async () => {
  await fetchPerson();
});

/*** get รายการข้อมูลเกี่ยวกับบุคคล (dropdown list) */
const fetchPerson = async () => {
  showLoader();
  await http
    .get(config.API.person)
    .then((res) => {
      const data = res.data.result;
      let optionbloodGroups: DataOption[] = [];
      data.bloodGroups.map((r: DataOptioninfo) => {
        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: DataOptioninfo) => {
        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: DataOptioninfo) => {
        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: DataOptioninfo) => {
        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: DataOptioninfo) => {
        optionreligions.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      Ops.value.religionOps = optionreligions;
      OpsFilter.value.religionOps = optionreligions;
    })
    .catch((e: any) => { })
    .finally(() => {
      hideLoader();
    });
};

// รูป profile
const inputImage = ref<any>(null);
const image = ref<any>(null);
const fileData = ref<any>(null);
const uploadImage = async (e: any) => {
  const input = e.target.files;
  if (input.length > 0) {
    const url = URL.createObjectURL(input[0]);
    image.value = url;
    fileData.value = input[0];
  }
};

// คลิกแก้ไขรูป profile
const addNewImage = async () => {
  inputImage.value.click();
};

// ตรวจสอบเลขประจำตัวประชาชน
const defaultCitizenData = ref<string>("");
const changeCardID = async (value: string | number | null) => {
  if (value != null && typeof value == "string") {
    if (value.length == 13 && value != defaultCitizenData.value) {
      await checkCitizen(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();
    });
};

// filter list ข้อมูลต่างๆ
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;

    default:
      break;
  }
};

// เช็ควันที่ที่สามารถเลือกวันเกิดได้โดย max date น้อยกว่าวันปัจจุบัน เพื่อให้ฟังก์ชั่นการเช็คทำงานได้ปกติ
const calculateMaxDate = () => {
  const today = new Date();
  today.setDate(today.getDate() - 1);
  return today;
};

// เช็คเรื่องการเกษียณ
const handleDate = async (modelData: Date) => {
  informaData.value.birthDate = modelData;
  await calRetire(modelData);
};

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);
        informaData.value.birthDate = null;
        informaData.value.age = "";
      })
      .finally(() => {
        hideLoader();
      });
  }
};

// หลังจากกดปุ่มบันทึกเช็ค validate ก่อน
const saveData = async () => {
  if (myform.value != null) {
    await myform.value.validate().then(async (saveDataTest: Boolean) => {
      if (saveDataTest) {
        dialogConfirm($q, () => addData()); // validate ผ่านส่งไปบันทึกที่ api
      }
    });
  }
};

// post เพิ่มข้อมูลทะเบียนประวัติไปที่ api
const addData = async () => {
  const formData = new FormData();
  if (fileData.value != null) formData.append("File", fileData.value); //แก้ไขรูป
  if (informaData.value.cardid != undefined)
    formData.append("citizenId", informaData.value.cardid);
  if (informaData.value.prefixId != undefined)
    formData.append("prefix", informaData.value.prefixId);
  if (informaData.value.firstname != undefined)
    formData.append("firstName", informaData.value.firstname);
  if (informaData.value.lastname != undefined)
    formData.append("lastName", informaData.value.lastname);
  if (informaData.value.genderId != undefined)
    formData.append("genderId", informaData.value.genderId);
  if (informaData.value.nationality != undefined)
    formData.append("nationality", informaData.value.nationality);
  if (informaData.value.ethnicity != undefined)
    formData.append("race", informaData.value.ethnicity);
  if (informaData.value.religionId != undefined)
    formData.append("religionId", informaData.value.religionId);
  if (informaData.value.birthDate != undefined)
    formData.append(
      "birthDate",
      dateToISO(informaData.value.birthDate) ?? dateToISO(new Date())
    );
  if (informaData.value.bloodId != undefined)
    formData.append("bloodGroupId", informaData.value.bloodId);
  if (informaData.value.statusId != undefined)
    formData.append("relationshipId", informaData.value.statusId);
  if (informaData.value.tel != undefined)
    formData.append("telephoneNumber", informaData.value.tel);
  if (informaData.value.employeeType != undefined)
    formData.append("employeeType", informaData.value.employeeType);
  if (informaData.value.employeeClass != undefined)
    formData.append("employeeClass", informaData.value.employeeClass);

  showLoader();
  await http
    .post(config.API.receiveData(), formData)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await changeBirth(informaData.value.birthDate ?? new Date());
      await clickBack();
      hideLoader();
    });
  hideLoader();
};

// ปุ่ม back
const clickBack = () => {
  router.push("/receive");
};
</script>

<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md">
    <HeaderTop header="ข้อมูลส่วนตัว" icon="mdi-account" />
    <q-form ref="myform" class="col-12 q-pt-md">
      <div class="row">
        <div class="row col-12 q-col-gutter-x-sm q-mb-xs">
          <div class="col-xs-6 col-sm-3 col-md-3">
            <q-input hide-bottom-space outlined v-model="informaData.cardid" dense @update:model-value="changeCardID"
              lazy-rules :rules="[
                (val: string) => !!val || `${'กรุณากรอก เลขประจำตัวประชาชน'}`,
                (val: string) =>
                  val.length >= 13 ||
                  `${'กรุณากรอกเลขประจำตัวประชาชนให้ครบ'}`,
              ]" label="เลขประจำตัวประชาชน" maxlength="13" mask="#############" />
            <!-- :rules="[(val:any) =>val.length != 13 ||`${'กรุณากรอกเลขประจำตัวประชาชนให้ครบ'}`,]" -->
          </div>
          <div class="col-xs-6 col-sm-3 col-md-3">
            <selector hide-bottom-space outlined :rules="[(val: string) => !!val || `${'กรุณาเลือก คำนำหน้าชื่อ'}`]" 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 hide-bottom-space outlined dense lazy-rules v-model="informaData.firstname"
              :rules="[(val: string) => !!val || `${'กรุณากรอก ชื่อ'}`]" :label="`${'ชื่อ'}`" />
          </div>
          <div class="col-xs-6 col-sm-3 col-md-3">
            <q-input hide-bottom-space outlined dense lazy-rules v-model="informaData.lastname"
              :rules="[(val: string) => !!val || `${'กรุณากรอก นามสกุล'}`]" :label="`${'นามสกุล'}`" />
          </div>
        </div>
        <div class="row col-12 q-col-gutter-x-sm q-mb-xs">
          <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="calculateMaxDate()" @update:model-value="handleDate">
              <template #year="{ year }">
                {{ year + 543 }}
              </template>
              <template #year-overlay-value="{ value }">
                {{ parseInt(value + 543) }}
              </template>
              <template #trigger>
                <q-input hide-bottom-space outlined dense lazy-rules :model-value="informaData.birthDate == null
                  ? null
                  : date2Thai(informaData.birthDate)
                  " :rules="[(val: string) => !!val || `${'กรุณาเลือก วัน/เดือน/ปี เกิด'}`]"
                  :label="`${'วัน/เดือน/ปี เกิด'}`">
                  <template v-slot:prepend>
                    <q-icon name="event" class="cursor-pointer" style="color: var(--q-primary)">
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
          </div>
          <div class="col-xs-6 col-sm-2 col-md-2">
            <q-input hide-bottom-space dense lazy-rules readonly borderless style="padding:0 12px;"
              :model-value="informaData.age" :label="`${'อายุ'}`" />
          </div>
          <div class="col-xs-6 col-sm-2 col-md-2">
            <selector hide-bottom-space outlined 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-bottom-space outlined 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 hide-bottom-space outlined dense lazy-rules v-model="informaData.nationality"
              :label="`${'สัญชาติ'}`" />
          </div>
          <div class="col-xs-6 col-sm-2 col-md-2">
            <q-input hide-bottom-space outlined dense lazy-rules v-model="informaData.ethnicity"
              :label="`${'เชื้อชาติ'}`" />
          </div>
        </div>
        <div class="row col-12 q-col-gutter-x-sm q-mb-xs">
          <div class="col-xs-6 col-sm-2 col-md-2">
            <selector hide-bottom-space outlined 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-bottom-space outlined 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 dense lazy-rules type="tel" v-model="informaData.tel"
              :label="`${'เบอร์โทร'}`" mask="##########" />
          </div>
        </div>
      </div>
    </q-form>
    <div class="col-12 q-pt-md q-pb-sm"><q-separator /></div>
    <div class="row col-12">
      <q-space />
      <q-btn unelevated dense class="q-px-md items-center" color="light-blue-10" label="บันทึก" @click="saveData" />
    </div>
  </q-card>

  <!-- Header  -->
  <q-page-sticky position="top" expand class="bg-grey-2 text-white" style="z-index: 99; padding: 0% 1% 0% 1%">
    <div class="row col-12 q-gutter-sm q-pb-sm text-dark no-wrap items-center">
      <q-btn flat round class="bg-teal-1 full-height" color="primary" icon="mdi-chevron-left" dense
        @click="router.push(`/receive`)">
      </q-btn>
      <q-avatar size="65px" rounded class="containerimage">
        <img v-if="image == null" src="@/assets/avatar_user.jpg" class="bg-grey-3" style="object-fit: cover" />
        <img :src="image" class="bg-grey-3" style="object-fit: cover" />
        <div class="overlay absolute-bottom text-subtitle2 text-center cursor-pointer" @click="addNewImage()">
          <q-icon name="mdi-camera" size="18px" color="blue">
            <q-tooltip>อัปเดตรูปภาพ</q-tooltip>
          </q-icon>

          <input type="file" style="display: none" ref="inputImage" accept="image/*" @change="uploadImage" />
        </div>
      </q-avatar>

      <div class="row items-center text-dark q-ml-md">
        <div class="column">
          <div class="text-bold q-pb-xs text-name">
            เพิ่มข้อมูลทะเบียนประวัติ
          </div>
          <div class="text-bold q-pb-xs text-sub">ข้าราชการกทม. สามัญ</div>
        </div>
      </div>
      <q-space />
    </div>
  </q-page-sticky>
  <!-- End Header  -->
</template>