<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";

import { useCounterMixin } from "@/stores/mixin";
import { useLinkageStore } from "@/stores/linkage";
import { useDataLinkCenter } from "@/modules/04_registryPerson/stores/LinkCenter";
import { useRequestEditStore } from "@/modules/04_registryPerson/stores/RequestEdit";

import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type { RequestregistrationAddressObject } from "@/modules/04_registryPerson/interface/request/Address";
import type { RequestObject } from "@/modules/04_registryPerson/interface/request/Profile";
import type {
  FormPerson,
  FormChildren,
} from "@/modules/04_registryPerson/interface/index/family";

import Header from "@/components/DialogHeader.vue"; //ส่วนหัว popup
import InformationPage from "@/modules/04_registryPerson/components/Dialog/01_Information.vue"; //form ข้อมูลส่วนตัว
import AddressPage from "@/modules/04_registryPerson/components/Dialog/02_Address.vue"; //form ข้อมูลที่อยู่

const modal = defineModel<boolean>("modal", { required: true }); // ตัวแปร popup
const idCard = defineModel<string>("idCard", { required: true }); //เลขบัตร ปชช
const profileId = defineModel<string>("profileId", { required: true }); //id บุคคล

const $q = useQuasar();
const mixin = useCounterMixin();
const storeLinkage = useLinkageStore();
const storeRequestEdit = useRequestEditStore();
const storeLinkCenter = useDataLinkCenter();
const {
  showLoader,
  hideLoader,
  messageError,
  dialogConfirm,
  modalError,
  success,
} = mixin;

const props = defineProps({
  fetchData: Function,
  requestId: String,
});

const data = ref<any>(null);
const presentAddress = ref<string>("0"); // ตัวแปรเก็บที่ อยู่ปัจจุบัน ใช่/ไม่
const count = ref<number>(0); // ตัวแปร นับ count
const age = ref<string | null>(""); //อายุ
const fullName = ref<string | null>(""); //ชื่อเต็ม
const formInformations = reactive<RequestObject>({
  bloodGroup: null,
  relationship: null,
  gender: null,
  religion: null,
  citizenId: "",
  nationality: null,
  ethnicity: null,
  birthDate: null,
  lastName: "",
  firstName: "",
  prefix: "",
  rank: null,
  prefixMain: "",
});

const formDataAddress = reactive<RequestregistrationAddressObject>({
  registrationZipCode: "",
  registrationSubDistrictId: "",
  registrationDistrictId: "",
  registrationProvinceId: "",
  registrationAddress: "",
});

/** ปิด popup */
async function closeDialog() {
  modal.value = false;

  formInformations.bloodGroup = null;
  formInformations.relationship = null;
  formInformations.gender = null;
  formInformations.religion = null;
  formInformations.citizenId = "";
  formInformations.nationality = null;
  formInformations.ethnicity = null;
  formInformations.birthDate = null;
  formInformations.lastName = "";
  formInformations.firstName = "";
  formInformations.prefix = "";
  formInformations.rank = null;
}

/** อัพเดตข้อมูลส่วนตัว */
async function upDateInfomation() {
  await http
    .put(config.API.profileNewProfileById(profileId.value, ""), {
      ...formInformations,
      undefined,
    })
    .then(async () => {
      count.value += 1;
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

/** อัพเดตข้อมูลที่อยู่ */
async function upDateAddress() {
  if (presentAddress.value === "1") {
    storeLinkCenter.OpsAddress.districtCOps =
      storeLinkCenter.OpsAddress.districtOps;
    storeLinkCenter.OpsAddress.subdistrictCOps =
      storeLinkCenter.OpsAddress.subdistrictOps;
  }
  await http
    .patch(config.API.profileNewAddressById(profileId.value, ""), {
      ...formDataAddress,
      id: undefined,
    })
    .then(async () => {
      count.value += 1;
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

/** ส่ง สถานะ ดำเนินการเเล้ว */
async function upDateStatus() {
  await http
    .patch(config.API.requestEdit + `${props.requestId}`, {
      status: "COMPLETE",
      remark: "",
    })
    .then(async () => {
      await props.fetchData?.();
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}
/** อัพเดตข้อมูล */
function onSubmit() {
  dialogConfirm($q, async () => {
    const body = {
      registrationZipCode: formDataAddress.registrationZipCode,
      registrationSubDistrictId: formDataAddress.registrationSubDistrictId,
      registrationDistrictId: formDataAddress.registrationDistrictId,
      registrationProvinceId: formDataAddress.registrationProvinceId,
      registrationAddress: formDataAddress.registrationAddress,

      // bloodGroup: formInformations.bloodGroup,
      relationship: formInformations.relationship,
      gender: formInformations.gender,
      // religion: formInformations.religion,
      nationality: formInformations.nationality,
      // ethnicity: formInformations.ethnicity,
      birthDate: formInformations.birthDate,
      lastName: formInformations.lastName,
      firstName: formInformations.firstName,
      prefix: formInformations.prefix,
      rank: formInformations.rank,
    };
    showLoader();
    http
      .patch(
        config.API.requestInformationbyType(
          "myprofile",
          storeRequestEdit.profileId
        ),
        body
      )
      .then(async (res) => {
        await upDateStatus();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

async function amiRequest() {
  const profile = await storeLinkage.amiRequest($q, 5000, idCard.value, "001");
  if (profile !== undefined) {
    data.value = profile;
  } else {
    data.value = {
      // titleCode: 3,
      // titleDesc: "นาย",
      titleName: "นาย", // use
      // titleSex: 1,
      firstName: "ชัยชนะ", // use
      middleName: "", // use
      lastName: "เรืองโรจน์", // use
      // genderCode: 1,
      genderDesc: "ชาย", // use
      dateOfBirth: 25211228, // use
      // nationalityCode: 99,
      nationalityDesc: "ไทย", // use
      // ownerStatusDesc: "เจ้าบ้าน",
      // statusOfPersonCode: 0,
      // statusOfPersonDesc: "บุคคลนี้มีภูมิลำเนาอยู่ในบ้านนี้",
      // dateOfMoveIn: 25580728,
      // age: 45,
    };

    const address = {
      // houseID: 12020203651,
      houseNo: "62/25", // use
      // houseType: 1,
      // houseTypeDesc: "บ้าน",
      villageNo: 5, // use
      // alleyWayCode: 0,
      alleyWayDesc: null, // use
      // alleyCode: 0,
      alleyDesc: null, // use
      // roadCode: 3,
      roadDesc: "เทอดพระเกียรติ", // use
      // subdistrictCode: 1,
      subdistrictDesc: "วัดชลอ", // use
      // districtCode: 2,
      districtDesc: "บางกรวย", // use
      // provinceCode: 12,
      provinceDesc: "นนทบุรี", // use
      // rcodeCode: "1296",
      // rcodeDesc: "ท้องถิ่นเทศบาลเมืองบางกรวย",
      // dateOfTerminate: 0,
      // alleyWayEnglishDesc: null,
      // alleyEnglishDesc: null,
      // roadEnglishDesc: "Terdpragied",
      // subdistrictEnglishDesc: "Wat Chalo",
      // districtEnglishDesc: "Bang Kruai",
      // provinceEnglishDesc: "Nonthaburi",
    };

    data.value = { ...data.value, ...address };
  }
  formInformations.citizenId = idCard.value;
  formInformations.prefix = data.value.titleName;
  fullName.value = data.value.fullnameAndRank;
  formInformations.firstName = data.value.firstName;
  formInformations.lastName = data.value.lastName;
  formInformations.nationality = data.value.nationalityDesc;

  // แปลง dateOfBirth เป็น format 1989-01-01
  formInformations.birthDate = data.value.dateOfBirth ? conventDateOfBirth(`${data.value.dateOfBirth}`) : null;
  age.value = storeLinkCenter.calculateAge(data.value.age);
  formInformations.gender = data.value.genderDesc;

  let registrationAddress = data.value.houseNo ? data.value.houseNo : "";
  registrationAddress += data.value.villageNo
    ? ` หมู่ ${data.value.villageNo}`
    : "";
  registrationAddress += data.value.alleyWayDesc
    ? ` ${data.value.alleyWayDesc}`
    : "";
  registrationAddress += data.value.roadDesc
    ? `ถนน ${data.value.roadDesc}`
    : "";
  formDataAddress.registrationAddress = registrationAddress;

  // ค้นหา จังหวัด อำเภอ ตำบล และรหัสไปรษณื
  formDataAddress.registrationProvinceId = await convertProvince(
    data.value.provinceDesc
  );
  formDataAddress.registrationDistrictId = await convertDistrict(
    data.value.districtDesc
  );
  formDataAddress.registrationSubDistrictId = await convertSubdistrict(
    data.value.subdistrictDesc
  );
  // formDataAddress.registrationZipCode = data.value.registrationZipCode;

  // console.log("province===>", data.value.provinceDesc);
  // console.log("district===>", data.value.districtDesc);
  // console.log("subdistrict===>", data.value.subdistrictDesc);
}

/**
 * ฟังก์ชันแปลง dateOfBirth เป็น format 1989-01-01
 * @param val dateOfBirth  '25211228'
 */
function conventDateOfBirth(val: string) {
  // Extract year, month, and day
  const year = parseInt(val.slice(0, 4), 10) - 543;
  const month = val.slice(4, 6);
  const day = val.slice(6, 8);

  // Format as YYYY-MM-DD
  return `${year}-${month}-${day}`;
}

/**
 * ฟังก์ชันแปลงชื่อจังหวัดเป็น ID
 * @param val ชื่อจังหวัด
 */
async function convertProvince(val: string) {
  const id = storeLinkCenter.OpsAddress.provinceOps.find(
    (e: DataOption) => e.name === val
  )?.id;

  // เรียกฟังก์ชันดึงข้อมูล เขต / อำเภอ
  await storeLinkCenter.fetchDistrict(id ? id : null, "1", false);

  return id ? id : null;
}

/**
 * ฟังก์ชันแปลงชื่อเขต / อำเภอ เป็น ID
 * @param val ชื่อเขต / อำเภอ
 */
async function convertDistrict(val: string) {
  const id = storeLinkCenter.OpsAddress.districtOps.find(
    (e: DataOption) => e.name === val
  )?.id;
  // เรียกฟังก์ชันดึงข้อมูล  แขวง/ตำบล
  await storeLinkCenter.fetchSubDistrict(id ? id : null, "1", false);

  return id ? id : null;
}

/**
 * ฟังก์ชันแปลงชื่อแขวง/ตำบล เป็น ID
 * @param val ชื่อแขวง/ตำบล
 */
async function convertSubdistrict(val: string) {
  const result = storeLinkCenter.OpsAddress.subdistrictOps.find(
    (e: DataOption) => e.name === val
  );
  formDataAddress.registrationZipCode = result ? result.zipCode : null;
  return result ? result.id : null;
}

watch(
  () => modal.value,
  async () => {
    if (modal.value) {
      showLoader();
      count.value = 0;
      await storeLinkCenter.fetchPerson();
      await storeLinkCenter.fetchProvince(false);
      await amiRequest();
      presentAddress.value = formDataAddress.registrationZipCode ? "0" : "1";
      // if (
      //   storeLinkCenter.OpsAddress.provinceOps.length === 0 ||
      //   storeLinkCenter.OpsAddress.districtOps.length === 0 ||
      //   storeLinkCenter.OpsAddress.districtCOps.length === 0 ||
      //   storeLinkCenter.OpsAddress.subdistrictOps.length === 0 ||
      //   storeLinkCenter.OpsAddress.subdistrictCOps.length === 0
      // ) {
      // await storeLinkCenter.fetchProvince(false);
      // storeLinkCenter.fetchDistrict(
      //   formDataAddress.registrationProvinceId,
      //   "1",
      //   false
      // );
      // storeLinkCenter.fetchSubDistrict(
      //   formDataAddress.registrationDistrictId,
      //   "1",
      //   false
      // );
      // }

      hideLoader();
    } else {
      age.value = "";
      formDataAddress.registrationAddress = "";
      formDataAddress.registrationProvinceId = null;
      formDataAddress.registrationDistrictId = null;
      formDataAddress.registrationSubDistrictId = null;
      formDataAddress.registrationZipCode = null;
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <Header tittle="ขอปรับปรุงข้อมูลจากกรมการปกครอง" :close="closeDialog" />
        <q-separator />
        <q-card-section class="scroll" style="max-height: 80vh">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <InformationPage
                v-model:form-informations="formInformations"
                v-model:age="age"
                :Ops="storeLinkCenter.OpsPerson"
              />
            </div>
            <div class="col-12">
              <q-separator />
            </div>
            <div class="col-12">
              <AddressPage
                v-model:form-data-address="formDataAddress"
                v-model:present-address="presentAddress"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn
            label="บันทึกลงทะเบียนประวัติ"
            color="secondary"
            type="submit"
          />
          <q-btn label="ยกเลิก" color="orange" @click="modal = false"
            ><q-tooltip>ยกเลิก</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
