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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useLinkageStore } from "@/stores/linkage";
import {
  AddressDataDefualt,
  FamilyDataDefualt,
} from "@/modules/05_placement/interface/index/Main";
import { useProfileDataStore } from "@/modules/05_placement/store";

import { defaultInformation } from "@/modules/05_placement/components/PersonalDetail/profileType";
import type { Information } from "@/modules/05_placement/components/PersonalDetail/profileType";
import type {
  Address as AddressType,
  Family,
  AddressData,
  AddressOps,
} from "@/modules/05_placement/interface/index/Main";

import Header from "@/components/DialogHeader.vue";
import FormInformationsPage from "@/modules/05_placement/components/PersonalDetail/CheckInformation/01_FormInformations.vue";
import FormAddressPage from "@/modules/05_placement/components/PersonalDetail/CheckInformation/02_FormAddress.vue";
import FormFamilyPage from "@/modules/05_placement/components/PersonalDetail/CheckInformation/03_FormFamily.vue";

const modal = defineModel<boolean>("modal", { required: true });
const idCard = defineModel<string>("idCard", { required: true });

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const profileStore = useProfileDataStore();
const { changeBirth } = profileStore;
const {
  showLoader,
  hideLoader,
  messageError,
  dialogConfirm,
  modalError,
  success,
  convertDateToAPI,
} = mixin;
const store = useLinkageStore();

const age = ref<boolean>(true); //อายุ

const props = defineProps({
  Ops: {
    type: Object as PropType<any>,
  },
  OpsFilter: {
    type: Object as PropType<any>,
  },
  AddressData: {
    type: Object as PropType<AddressType>,
    default: AddressDataDefualt,
  },
  InformationData: {
    type: Object as PropType<Information>,
    default: defaultInformation,
  },

  familyData: {
    type: Object as PropType<Family>,
    default: FamilyDataDefualt,
  },
  getAll: Function,
});

const addressData = ref<AddressType>(props.AddressData);
const familyData = ref<Family>(props.familyData); //ข้อมูลครอบครัว
/** ตัวแปร ข้อมูลส่วนตัว */
const formInformations = reactive<Information>(props.InformationData);

//ที่อยู่ปัจบัน
const currentAddress = reactive<AddressData>({
  subDistrictId: "",
  zipCode: "",
  districtId: "",
  provinceId: "",
});

const registAddress = reactive<AddressData>({
  subDistrictId: "",
  zipCode: "",
  districtId: "",
  provinceId: "",
});

//ตัวเลือกข้อมูลที่อยู่
const OpsAddress = ref<AddressOps>({
  provinceOps: [],
  districtOps: [],
  districtCOps: [],
  subdistrictOps: [],
  subdistrictCOps: [],
});
//ข้อมูลที่อยู่
const OpsFilterAddress = ref<AddressOps>({
  provinceOps: [],
  districtOps: [],
  districtCOps: [],
  subdistrictOps: [],
  subdistrictCOps: [],
});

function closeDialog() {
  modal.value = false;
  props.getAll?.();
}

function onSubmit() {
  dialogConfirm($q, async () => {
    if (age.value == false) {
      modalError($q, "พบข้อผิดพลาด", "วันเกิดไม่ถูกต้อง");
      return;
    } else {
      try {
        showLoader();
        await upDateInfomation();
        await upDateAddress();
        await upDateFamily();

        success($q, "บันทึกข้อมูลสำเร็จ");
        closeDialog();
        await props.getAll?.();
        await changeBirth(formInformations.dateOfBirth ?? new Date());
      } catch (err) {
        messageError($q, err);
      } finally {
        hideLoader();
      }
    }
  });
}

const data = ref<any>(null);
/** ดึงข้อมูลรายละเอียด */
async function amiRequest() {
  const profile = await store.amiRequest($q, 5000, idCard.value, "001");

  data.value = profile;
  formInformations.idCard = idCard.value;
  formInformations.prefix = data.value.titleName;
  formInformations.prefixId = data.value.titleName;
  formInformations.fullName = data.value.fullnameAndRank;
  formInformations.firstname = data.value.firstName;
  formInformations.lastname = data.value.lastName;
  formInformations.nationality = data.value.nationalityDesc;
  formInformations.race = props.InformationData.race;
  formInformations.dateOfBirth = data.value.dateOfBirth;
  formInformations.age = data.value.age;
  formInformations.telephone = props.InformationData.telephone;
  formInformations.gender = data.value.genderDesc;
  formInformations.genderId = data.value.genderDesc;
  formInformations.relationship = props.InformationData.relationship;
  formInformations.relationshipId = props.InformationData.relationshipId;
  formInformations.bloodGroup = props.InformationData.bloodGroup;
  formInformations.bloodGroupId = props.InformationData.bloodGroupId;
  formInformations.religion = props.InformationData.religionId;
  formInformations.religionId = props.InformationData.religionId;

  familyData.value.fatherFirstName = data.value.fatherName;
  familyData.value.motherFirstName = data.value.motherName;
}

/**
 * อัพเดตข้อมูลส่วนตัว
 */
async function upDateInfomation() {
  const body: any = {
    citizenId: formInformations.idCard,
    prefix: formInformations.prefixId,
    firstName: formInformations.firstname,
    lastName: formInformations.lastname,
    gender: formInformations.genderId,
    nationality: formInformations.nationality,
    race: formInformations.race,
    religion: formInformations.religionId,
    birthDate: convertDateToAPI(formInformations.dateOfBirth),
    bloodGroup: formInformations.bloodGroupId,
    relationship: formInformations.relationshipId,
    telephoneNumber: formInformations.telephone,
  };
  await http
    .put(
      config.API.placementInformationId(route.params.personalId.toString()),
      body
    )
    .catch((e) => {
      messageError($q, e);
    });
}

/**
 * อัพเดตข้อมูลที่อยู่
 */
async function upDateAddress() {
  const body = {
    registrationSame: addressData.value.registSame == "1",
    registrationAddress: addressData.value.registAddress,
    registrationSubDistrictId: registAddress.subDistrictId,
    registrationDistrictId: registAddress.districtId,
    registrationProvinceId: registAddress.provinceId,
    registrationZipCode: registAddress.zipCode,
    currentAddress:
      addressData.value.registSame == "1"
        ? addressData.value.registAddress
        : addressData.value.currentAddress,
    currentSubDistrictId:
      addressData.value.registSame == "1"
        ? registAddress.subDistrictId
        : currentAddress.subDistrictId,
    currentDistrictId:
      addressData.value.registSame == "1"
        ? registAddress.districtId
        : currentAddress.districtId,
    currentProvinceId:
      addressData.value.registSame == "1"
        ? registAddress.provinceId
        : currentAddress.provinceId,
    currentZipCode:
      addressData.value.registSame == "1"
        ? registAddress.zipCode
        : currentAddress.zipCode,
  };
  await http
    .put(
      config.API.placementAddressId(route.params.personalId.toString()),
      body
    )

    .catch((e) => {
      messageError($q, e);
    });
}

/** อัพเดตข้อมูลครอบครัว */
async function upDateFamily() {
  const body = {
    couple: familyData.value.couple == "1",
    couplePrefix: familyData.value.marryPrefixId,
    coupleFirstName: familyData.value.marryFirstName,
    coupleLastName: familyData.value.marryLastName,
    coupleLastNameOld: "",
    coupleCareer: familyData.value.marryOccupation,
    fatherPrefix: familyData.value.fatherPrefixId,
    fatherFirstName: familyData.value.fatherFirstName,
    fatherLastName: familyData.value.fatherLastName,
    fatherCareer: familyData.value.fatherOccupation,
    motherPrefix: familyData.value.motherPrefixId,
    motherFirstName: familyData.value.motherFirstName,
    motherLastName: familyData.value.motherLastName,
    motherCareer: familyData.value.motherOccupation,
  };
  await http
    .put(config.API.placementFamilyId(route.params.personalId.toString()), body)
    .catch((e) => {
      messageError($q, e);
    });
}

/** เช็คค่า modal เมื่อเป็น true ใช้งาน ฟังชั่น */
watch(
  () => modal.value,
  async () => {
    if (modal.value) {
      await amiRequest();
    }
  }
);
</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">
              <FormInformationsPage
                v-model:form-informations="formInformations"
                :Ops="props.Ops"
                :OpsFilter="props.OpsFilter"
                v-model:age="age"
              />
            </div>
            <div class="col-12">
              <q-separator />
            </div>
            <div class="col-12">
              <FormAddressPage
                v-model:regist-address="registAddress"
                v-model:ops-address="OpsAddress"
                v-model:ops-filter-address="OpsFilterAddress"
                v-model:current-address="currentAddress"
                v-model:address-data="addressData"
              />
            </div>
            <div class="col-12">
              <q-separator />
            </div>
            <div class="col-12">
              <FormFamilyPage
                :Ops="props.Ops"
                :Ops-filter="props.OpsFilter"
                v-model:family-data="familyData"
              />
            </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>
