<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 type { RequestAddressObject } 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 ข้อมูลที่อยู่
import FamilyPage from "@/modules/04_registryPerson/components/Dialog/03_Family.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 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,
  phone: null,
  lastName: "",
  firstName: "",
  prefix: "",
  rank: null,
});

const formDataAddress = reactive<RequestAddressObject>({
  currentZipCode: "",
  currentSubDistrictId: "",
  currentDistrictId: "",
  currentProvinceId: "",
  currentAddress: "",

  registrationZipCode: "",
  registrationSubDistrictId: "",
  registrationDistrictId: "",
  registrationProvinceId: "",
  registrationAddress: "",
});

const fatherData = reactive<FormPerson>({
  isLive: 1,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
});
const motherData = reactive<FormPerson>({
  isLive: 1,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
});
const coupleData = reactive<FormPerson>({
  isLive: 1,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
  lastNameOld: "",
  statusMarital: "",
});
const childData = ref<FormChildren[]>([]);

/** ปิด popup */
async function closeDialog() {
  modal.value = false;
  count.value = 0;
  childData.value = [];
}

/** อัพเดตข้อมูลส่วนตัว */
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") {
    formDataAddress.currentAddress = formDataAddress.registrationAddress;
    formDataAddress.currentProvinceId = formDataAddress.registrationProvinceId;
    formDataAddress.currentDistrictId = formDataAddress.registrationDistrictId;
    formDataAddress.currentSubDistrictId =
      formDataAddress.registrationSubDistrictId;
    formDataAddress.currentZipCode = formDataAddress.registrationZipCode;
    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 () => {})
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

/** อัพเดตข้อมูลครอบครัว */
async function upDateFamily() {
  await saveFather();
  await saveMother();
  await saveCouple();
  for (const child of childData.value) {
    await saveChildren(child);
  }
  count.value + 1;
}

async function saveFather() {
  const body = {
    profileId: profileId.value,
    fatherCitizenId: fatherData.citizenId,
    fatherPrefix: fatherData.prefix,
    fatherFirstName: fatherData.firstName,
    fatherLastName: fatherData.lastName,
    fatherCareer: fatherData.job,
    fatherLive: fatherData.isLive === 1 ? true : false,
  };
  http
    .post(config.API.profileFamily("", "father"), body)
    .then((res) => {})
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

async function saveMother() {
  const body = {
    profileId: profileId.value,
    motherCitizenId: motherData.citizenId,
    motherPrefix: motherData.prefix,
    motherFirstName: motherData.firstName,
    motherLastName: motherData.lastName,
    motherCareer: motherData.job,
    motherLive: motherData.isLive === 1 ? true : false,
  };
  http
    .post(config.API.profileFamily("", "mother"), body)
    .then((res) => {})
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

async function saveCouple() {
  const body = {
    profileId: profileId.value,
    coupleCitizenId: coupleData.citizenId,
    couplePrefix: coupleData.prefix,
    coupleFirstName: coupleData.firstName,
    coupleLastName: coupleData.lastName,
    coupleCareer: coupleData.job,
    coupleLive: coupleData.isLive === 1 ? true : false,
    relationship: coupleData.statusMarital,
    coupleLastNameOld: coupleData.lastNameOld,
  };
  http
    .post(config.API.profileFamily("", "couple"), body)
    .then((res) => {})
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

async function saveChildren(child: FormChildren) {
  const body = {
    profileId: profileId.value,
    childrenCitizenId: child.childrenCitizenId,
    childrenPrefix: child.childrenPrefix,
    childrenFirstName: child.childrenFirstName,
    childrenLastName: child.childrenLastName,
    childrenCareer: child.childrenCareer,
    childrenLive: child.childrenLive === 1 ? true : false,
  };

  return http
    .post(config.API.profileFamily("", "children"), body)
    .then((res) => {})
    .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 () => {
    showLoader();
    await upDateInfomation();
    await upDateAddress();
    await upDateFamily();
    if (count.value == 3) {
      await upDateStatus();
      success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
      await props.fetchData?.();
    }
    hideLoader();
  });
}

async function amiRequest() {
  const profile = await storeLinkage.amiRequest($q, 5000, idCard.value, "001");
  data.value = profile;

  data.value = profile;
  data.value = {
    titleCode: 3,
    titleDesc: "นาย",
    titleName: "นาย",
    titleSex: 1,
    firstName: "ชัยชนะ",
    middleName: "",
    lastName: "เรืองโรจน์",
    genderCode: 1,
    genderDesc: "ชาย",
    dateOfBirth: 25211228,
    nationalityCode: 99,
    nationalityDesc: "ไทย",
    ownerStatusDesc: "เจ้าบ้าน",
    statusOfPersonCode: 0,
    statusOfPersonDesc: "บุคคลนี้มีภูมิลำเนาอยู่ในบ้านนี้",
    dateOfMoveIn: 25580728,
    age: 45,

    fatherPersonalID: 3102100621479,
    fatherName: "บุญเชิด",
    fatherNationalityCode: 99,
    fatherNationalityDesc: "ไทย",

    motherPersonalID: 3102100621487,
    motherName: "พยอม",
    motherNationalityCode: 99,
    motherNationalityDesc: "ไทย",

    fullnameAndRank: "นายสุพลชัย พูลสวัสดิ์",
    englishTitleDesc: "MR.",
    englishFirstName: "SUPHONCHAI",
    englishMiddleName: "",
    englishLastName: "PHOONSAWAT",

    registrationAddress: "1220-1222 ถนนเพชรบุรี",
    registrationProvinceId: "24bf701c-33d6-436e-ad49-6f82bb3ae017",
    registrationDistrictId: "34bf701c-33d6-436e-ad49-6f82bb3b0586",
    registrationSubDistrictId: "44bf701c-33d6-436e-ad49-6f82bb3b5649",
    registrationZipCode: "10400",
    currentAddress: "1220-1222 ถนนเพชรบุรี",
    currentProvinceId: "24bf701c-33d6-436e-ad49-6f82bb3ae017",
    currentDistrictId: "34bf701c-33d6-436e-ad49-6f82bb3b0586",
    currentSubDistrictId: "44bf701c-33d6-436e-ad49-6f82bb3b5649",
    currentZipCode: "10400",
  };

  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;
  formInformations.birthDate = data.value.dateOfBirth;
  age.value = storeLinkCenter.calculateAge(data.value.age);
  formInformations.gender = data.value.genderDesc;

  formDataAddress.registrationAddress = data.value.registrationAddress;
  formDataAddress.registrationProvinceId = data.value.registrationProvinceId;
  formDataAddress.registrationDistrictId = data.value.registrationDistrictId;
  formDataAddress.registrationSubDistrictId =
    data.value.registrationSubDistrictId;
  formDataAddress.registrationZipCode = data.value.registrationZipCode;
  formDataAddress.currentAddress = data.value.currentAddress;
  formDataAddress.currentProvinceId = data.value.currentProvinceId;
  formDataAddress.currentDistrictId = data.value.currentDistrictId;
  formDataAddress.currentSubDistrictId = data.value.currentSubDistrictId;
  formDataAddress.currentZipCode = data.value.currentZipCode;

  //   formFamily.fatherFirstName = data.value.fatherName;
  //   formFamily.motherFirstName = data.value.motherName;
}

/**
 * function fetch ข้อมูลความสัมพันธ์
 */
async function fetchDataRelationship() {
  await http
    .get(config.API.orgRelationship)
    .then(async (res) => {
      const list = await res.data.result.map((e: any) => ({
        id: e.id,
        name: e.name,
      }));
      storeLinkCenter.optionRelationshipMain = list;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

watch(
  () => modal.value,
  async () => {
    if (modal.value) {
      showLoader();
      await fetchDataRelationship();
      await storeLinkCenter.fetchPerson();
      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.fetchDistrict(
          formDataAddress.currentProvinceId,
          "2",
          false
        );
        storeLinkCenter.fetchSubDistrict(
          formDataAddress.registrationDistrictId,
          "1",
          false
        );
        storeLinkCenter.fetchSubDistrict(
          formDataAddress.currentDistrictId,
          "2",
          false
        );
      }

      hideLoader();
    }
  }
);
</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 class="col-12">
              <q-separator />
            </div>
            <div class="col-12">
              <FamilyPage
                v-model:father-data="fatherData"
                v-model:mother-data="motherData"
                v-model:couple-data="coupleData"
                v-model:child-data="childData"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn label="อัพเดต" color="secondary" type="submit"
            ><q-tooltip>อัพเดต</q-tooltip></q-btn
          >
          <q-btn label="ยกเลิก" color="orange" @click="modal = false"
            ><q-tooltip>ยกเลิก</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
