<!-- หน้า รายละเอียดของ -->
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useQuasar } from "quasar";

import { useRoute, useRouter } from "vue-router";
import { useDataStore } from "@/stores/data";
import { usePersonalDataStore } from "@/modules/05_placement/storePersona";
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";
import http from "@/plugins/http";
import config from "@/app.config";

import {
  AddressDataDefualt,
  FamilyDataDefualt,
} from "@/modules/05_placement/interface/index/Main";
import type {
  Property,
  PointExam,
  Education,
  Family,
  Address,
  Certificate,
  optionData,
  InformationOps,
} from "@/modules/05_placement/interface/index/Main";
import type { Information } from "@/modules/05_placement/components/PersonalDetail/profileType";

import Informationvue from "@/modules/05_placement/components/PersonalDetail/Information/Information.vue";
import Addressvue from "@/modules/05_placement/components/PersonalDetail/Information/Address.vue";
import Familyvue from "@/modules/05_placement/components/PersonalDetail/Information/Family.vue";
import Certicate from "@/modules/05_placement/components/PersonalDetail/Information/Certicate.vue";
import EducationVue from "@/modules/05_placement/components/PersonalDetail/Information/Education.vue";
import ExamResult from "@/modules/05_placement/components/PersonalDetail/Information/ExamResult.vue";
import Qualification from "@/modules/05_placement/components/PersonalDetail/Information/Qualification.vue";
import Document from "@/modules/05_placement/components/PersonalDetail/Information/Document.vue";
import DialogCheckInformation from "@/modules/05_placement/components/PersonalDetail/DialogCheckInformation.vue";

const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const store = useDataStore();
const mixin = useCounterMixin();
const storePersonal = usePersonalDataStore();
const { showLoader, hideLoader, messageError } = mixin;
const { changeTab } = store;

const modalCheck = ref<boolean>(false);
const examId = ref<string>(
  route.params.personalId ? route.params.personalId.toString() : ""
);
const statusEdit = ref<boolean>(false); //การแก้ไข
const profileType = ref<string>(""); //ประเภทของบุคคล
//ผลการสอบ
const ExamDataDefualt: PointExam = {
  pointA: 0,
  pointB: 0,
  pointC: 0,
  pointTotalA: 0,
  pointTotalB: 0,
  pointTotalC: 0,
  point: 0,
  pointTotal: 0,
  examNumber: 0,
  examRound: 0,
  pass: "",
};
//ข้อมูลส่วนตัว
const InformationDataDefualt: Information = {
  idCard: "",
  prefix: "",
  prefixId: "",
  fullName: "",
  firstname: "",
  lastname: "",
  nationality: "",
  race: "",
  dateOfBirth: new Date(),
  age: "",
  telephone: "",
  gender: "",
  genderId: "",
  relationship: "",
  relationshipId: "",
  bloodGroup: "",
  bloodGroupId: "",
  religion: "",
  religionId: "",
};
//ชื่อ
const personalData = ref({
  id: "",
  fullName: "",
});
const QualificationData = ref<Property[]>([]);
const ExamData = ref<PointExam>(ExamDataDefualt); //ข้อมูลผลการสอบ
const InformationData = ref<Information>(InformationDataDefualt); //ข้อมูลส่วนตัว
const EducationData = ref<Education[]>([]); //ข้อมูลประวัติการศึกษา
const FamilyData = ref<Family>(FamilyDataDefualt); //ข้อมูลครอบครัว
const AddressData = ref<Address>(AddressDataDefualt); //ข้อมูลที่อยู่
const CertificateData = ref<Certificate[]>([]); //ข้อมูลใบอนุญาตประกอบอาชีพ
//สิทธิการแก้ไข
const isEdit = ref<boolean>(
  checkPermission(route)?.attrIsUpdate ? true : false
);

const Ops = ref<InformationOps>({
  prefixOps: [],
  genderOps: [],
  bloodOps: [],
  statusOps: [],
  religionOps: [],
  employeeClassOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
  employeeTypeOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
});

const OpsFilter = ref<InformationOps>({
  prefixOps: [],
  genderOps: [],
  bloodOps: [],
  statusOps: [],
  religionOps: [],
  employeeClassOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
  employeeTypeOps: [
    { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
    { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
  ],
});

/**
 * ฟังก์ชันดึงข้อมูลรายละเอียดทั้งหมด
 */
async function fetchData() {
  showLoader();
  storePersonal.loading = false;
  await http
    .get(config.API.placementPersonalId(examId.value))
    .then(async (res) => {
      const data = await res.data.result;
      storePersonal.fecthDataInformation(data);
      personalData.value.fullName = data.fullName;
      personalData.value.id = data.personalId;
      InformationData.value.idCard = data.idCard;
      InformationData.value.fullName = data.fullName;
      InformationData.value.firstname = data.firstname;
      InformationData.value.lastname = data.lastname;
      InformationData.value.nationality = data.nationality;
      InformationData.value.race = data.race;
      InformationData.value.genderId = guidCheck(data.gender) ?? "";
      InformationData.value.prefixId = guidCheck(data.prefix) ?? "";
      InformationData.value.relationshipId = guidCheck(data.relationship) ?? "";
      InformationData.value.religionId = guidCheck(data.religion) ?? "";
      InformationData.value.bloodGroupId = guidCheck(data.bloodGroup) ?? "";
      InformationData.value.dateOfBirth = new Date(data.dateOfBirth);
      InformationData.value.age = data.age;
      InformationData.value.telephone = data.telephone;

      AddressData.value.registAddress = data.registAddress ?? "";
      AddressData.value.currentAddress = data.currentAddress ?? "";
      AddressData.value.registSame = data.registSame ? "1" : "0";
      AddressData.value.registSubDistrict = data.registSubDistrict ?? "";
      AddressData.value.registSubDistrictId =
        guidCheck(data.registSubDistrictId) ?? "";
      AddressData.value.registZipCode = data.registZipCode ?? "";
      AddressData.value.registDistrict = data.registDistrict ?? "";
      AddressData.value.registDistrictId =
        guidCheck(data.registDistrictId) ?? "";
      AddressData.value.registProvince = data.registProvince ?? "";
      AddressData.value.registProvinceId =
        guidCheck(data.registProvinceId) ?? "";
      AddressData.value.currentSubDistrict = data.currentSubDistrict ?? "";
      AddressData.value.currentSubDistrictId =
        guidCheck(data.currentSubDistrictId) ?? "";
      AddressData.value.currentZipCode = data.currentZipCode ?? "";
      AddressData.value.currentDistrict = data.currentDistrict ?? "";
      AddressData.value.currentDistrictId =
        guidCheck(data.currentDistrictId) ?? "";
      AddressData.value.currentProvince = data.currentProvince ?? "";
      AddressData.value.currentProvinceId =
        guidCheck(data.currentProvinceId) ?? "";

      FamilyData.value.couple = data.couple ? "1" : "0";
      FamilyData.value.marryPrefix = data.marryPrefix ?? "";
      FamilyData.value.marryPrefixId = guidCheck(data.marryPrefix) ?? "";
      FamilyData.value.marryFirstName = data.marryFirstName ?? "";
      FamilyData.value.marryLastName = data.marryLastName ?? "";
      FamilyData.value.marryOccupation = data.marryOccupation ?? "";
      FamilyData.value.fatherPrefix = data.fatherPrefix ?? "";
      FamilyData.value.fatherPrefixId = guidCheck(data.fatherPrefix) ?? "";
      FamilyData.value.fatherFirstName = data.fatherFirstName ?? "";
      FamilyData.value.fatherLastName = data.fatherLastName ?? "";
      FamilyData.value.fatherOccupation = data.fatherOccupation ?? "";
      FamilyData.value.motherPrefix = data.motherPrefix ?? "";
      FamilyData.value.motherPrefixId = guidCheck(data.motherPrefix) ?? "";
      FamilyData.value.motherFirstName = data.motherFirstName ?? "";
      FamilyData.value.motherLastName = data.motherLastName ?? "";
      FamilyData.value.motherOccupation = data.motherOccupation ?? "";

      ExamData.value.pointA = data.pointA;
      ExamData.value.pointB = data.pointB;
      ExamData.value.pointC = data.pointC;
      ExamData.value.point = data.point;
      ExamData.value.pointTotalA = data.pointTotalA;
      ExamData.value.pointTotalB = data.pointTotalB;
      ExamData.value.pointTotalC = data.pointTotalC;
      ExamData.value.pointTotal = data.pointTotal;
      ExamData.value.examNumber = data.examNumber;
      ExamData.value.examRound = data.examRound;
      ExamData.value.pass = data.pass;

      QualificationData.value = data.isProperty;

      let listRow: Education[] = [];
      data.education.map((row: any) => {
        listRow.push({
          id: guidCheck(row.id) ?? "",
          educationLevel: row.educationLevel ?? "-",
          educationLevelId: guidCheck(row.educationLevelId) ?? "-",
          institute: row.institute ?? "-",
          degree: row.degree ?? "-",
          field: row.field ?? "-",
          gpa: row.gpa ?? "-",
          country: row.country ?? "-",
          duration: row.duration ?? "-",
          other: row.other ?? "-",
          fundName: row.fundName ?? "-",
          durationYear: row.durationYear ?? 0,
          finishDate: row.finishDate ?? new Date(),
          isDate: row.isDate ? "true" : "false",
          startDate: row.startDate ? new Date(row.startDate) : "",
          endDate: row.endDate ? new Date(row.endDate) : "",
          positionPath: row.positionPath ?? "-",
          isEducation: row.isEducation ? true : false,
        });
      });
      EducationData.value = listRow;

      let listCert: Certificate[] = [];

      data.certificates.map((row: any) => {
        listCert.push({
          id: guidCheck(row.id) ?? "",
          certificateNo: guidCheck(row.certificateNo) ?? "",
          issuer: row.issuer ?? "",
          issueDate: new Date(row.issueDate) ?? new Date(),
          expireDate: new Date(row.expireDate) ?? new Date(),
          certificateType: row.certificateType ?? "",
        });
      });
      CertificateData.value = listCert;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันดึงข้อมูลรายละเอียดตามประเภท
 * @param type ประเภทของข้อมูล
 */
async function fetchDataByType(type: string) {
  showLoader();
  await http
    .get(config.API.placementPersonalId(examId.value))
    .then(async (res) => {
      const data = await res.data.result;
      storePersonal.fecthDataInformation(data);
      personalData.value.fullName = data.fullName;
      personalData.value.id = data.personalId;

      if (type == "Information") {
        InformationData.value.idCard = data.idCard;
        InformationData.value.fullName = data.fullName;
        InformationData.value.firstname = data.firstname;
        InformationData.value.lastname = data.lastname;
        InformationData.value.nationality = data.nationality;
        InformationData.value.race = data.race;
        InformationData.value.genderId = guidCheck(data.gender) ?? "";
        InformationData.value.prefixId = guidCheck(data.prefix) ?? "";
        InformationData.value.relationshipId =
          guidCheck(data.relationship) ?? "";
        InformationData.value.religionId = guidCheck(data.religion) ?? "";
        InformationData.value.bloodGroupId = guidCheck(data.bloodGroup) ?? "";
        InformationData.value.dateOfBirth = new Date(data.dateOfBirth);
        InformationData.value.age = data.age;
        InformationData.value.telephone = data.telephone;
      } else if (type == "Address") {
        AddressData.value.registAddress = data.registAddress ?? "";
        AddressData.value.currentAddress = data.currentAddress ?? "";
        AddressData.value.registSame = data.registSame ? "1" : "0";
        AddressData.value.registSubDistrict = data.registSubDistrict ?? "";
        AddressData.value.registSubDistrictId =
          guidCheck(data.registSubDistrictId) ?? "";
        AddressData.value.registZipCode = data.registZipCode ?? "";
        AddressData.value.registDistrict = data.registDistrict ?? "";
        AddressData.value.registDistrictId =
          guidCheck(data.registDistrictId) ?? "";
        AddressData.value.registProvince = data.registProvince ?? "";
        AddressData.value.registProvinceId =
          guidCheck(data.registProvinceId) ?? "";
        AddressData.value.currentSubDistrict = data.currentSubDistrict ?? "";
        AddressData.value.currentSubDistrictId =
          guidCheck(data.currentSubDistrictId) ?? "";
        AddressData.value.currentZipCode = data.currentZipCode ?? "";
        AddressData.value.currentDistrict = data.currentDistrict ?? "";
        AddressData.value.currentDistrictId =
          guidCheck(data.currentDistrictId) ?? "";
        AddressData.value.currentProvince = data.currentProvince ?? "";
        AddressData.value.currentProvinceId =
          guidCheck(data.currentProvinceId) ?? "";
      } else if (type == "Family") {
        FamilyData.value.couple = data.couple ? "1" : "0";
        FamilyData.value.marryPrefix = data.marryPrefix ?? "";
        FamilyData.value.marryPrefixId = guidCheck(data.marryPrefix) ?? "";
        FamilyData.value.marryFirstName = data.marryFirstName ?? "";
        FamilyData.value.marryLastName = data.marryLastName ?? "";
        FamilyData.value.marryOccupation = data.marryOccupation ?? "";
        FamilyData.value.fatherPrefix = data.fatherPrefix ?? "";
        FamilyData.value.fatherPrefixId = guidCheck(data.fatherPrefix) ?? "";
        FamilyData.value.fatherFirstName = data.fatherFirstName ?? "";
        FamilyData.value.fatherLastName = data.fatherLastName ?? "";
        FamilyData.value.fatherOccupation = data.fatherOccupation ?? "";
        FamilyData.value.motherPrefix = data.motherPrefix ?? "";
        FamilyData.value.motherPrefixId = guidCheck(data.motherPrefix) ?? "";
        FamilyData.value.motherFirstName = data.motherFirstName ?? "";
        FamilyData.value.motherLastName = data.motherLastName ?? "";
        FamilyData.value.motherOccupation = data.motherOccupation ?? "";
      } else if (type == "Exam") {
        ExamData.value.pointA = data.pointA;
        ExamData.value.pointB = data.pointB;
        ExamData.value.pointC = data.pointC;
        ExamData.value.point = data.point;
        ExamData.value.pointTotalA = data.pointTotalA;
        ExamData.value.pointTotalB = data.pointTotalB;
        ExamData.value.pointTotalC = data.pointTotalC;
        ExamData.value.pointTotal = data.pointTotal;
        ExamData.value.examNumber = data.examNumber;
        ExamData.value.examRound = data.examRound;
        ExamData.value.pass = data.pass;
      } else if (type == "Certificate") {
        let listCert: Certificate[] = [];

        data.certificates.map((row: any) => {
          listCert.push({
            id: guidCheck(row.id) ?? "",
            certificateNo: guidCheck(row.certificateNo) ?? "",
            issuer: row.issuer ?? "",
            issueDate: new Date(row.issueDate) ?? new Date(),
            expireDate: new Date(row.expireDate) ?? new Date(),
            certificateType: row.certificateType ?? "",
          });
        });
        CertificateData.value = listCert;
      } else if (type == "Education") {
        let listRow: Education[] = [];
        data.education.map((row: any) => {
          listRow.push({
            id: guidCheck(row.id) ?? "",
            educationLevel: row.educationLevel ?? "",
            educationLevelId: guidCheck(row.educationLevelId) ?? "",
            institute: row.institute ?? "",
            degree: row.degree ?? "",
            field: row.field ?? "",
            gpa: row.gpa ?? "",
            country: row.country ?? "",
            duration: row.duration ?? "",
            other: row.other ?? "",
            fundName: row.fundName ?? "",
            durationYear: row.durationYear ?? 0,
            finishDate: row.finishDate ?? new Date(),
            isDate: row.isDate ? "true" : "false",
            startDate: row.startDate ? new Date(row.startDate) : new Date(),
            endDate: row.endDate ? new Date(row.endDate) : new Date(),
            positionPath: row.positionPath ?? "",
            isEducation: row.isEducation ? true : false,
          });
        });
        EducationData.value = listRow;
      } else if (type == "Qualification") {
        QualificationData.value = data.isProperty;
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันดึงข้อมูลเกี่ยวกับบุคคล
 */
async function fetchPerson() {
  showLoader();
  await http
    .get(config.API.profileNewMetaMain)
    .then((res) => {
      const data = res.data.result;

      //กรุ๊ปเลือด
      let optionbloodGroups: optionData[] = [];
      data.bloodGroups.map((r: any) => {
        optionbloodGroups.push({
          id: r.name ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.bloodOps = optionbloodGroups;
      OpsFilter.value.bloodOps = optionbloodGroups;

      //เพศ
      let optiongenders: optionData[] = [];
      data.genders.map((r: any) => {
        optiongenders.push({
          id: r.name ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.genderOps = optiongenders;
      OpsFilter.value.genderOps = optiongenders;

      //คำนำหน้าชื่อ
      let optionprefixs: optionData[] = [];
      data.prefixs.map((r: any) => {
        optionprefixs.push({
          id: r.name ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.prefixOps = optionprefixs;
      OpsFilter.value.prefixOps = optionprefixs;

      //สถานภาพ
      let optionrelationships: optionData[] = [];
      data.relationships.map((r: any) => {
        optionrelationships.push({
          id: r.name ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.statusOps = optionrelationships;
      OpsFilter.value.statusOps = optionrelationships;

      //ศาสนา
      let optionreligions: optionData[] = [];
      data.religions.map((r: any) => {
        optionreligions.push({
          id: r.name ?? "",
          name: r.name ?? "",
        });
      });
      Ops.value.religionOps = optionreligions;
      OpsFilter.value.religionOps = optionreligions;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันเช็ต id
 * @param id profile
 * @returns ถ้า ID เป็น   "00000000-0000-0000-0000-000000000000" ให้ return null
 *
 */
function guidCheck(id: string) {
  if (id == "00000000-0000-0000-0000-000000000000") {
    return null;
  }
  return id;
}

/** เปิด popup ตรวจสอบข้อมูลกับกรมการปกครอง */
function checkInformation() {
  modalCheck.value = true;
}

async function getAll() {
  await Promise.all([fetchData(), changeTab("information"), fetchPerson()]);
}
/**
 * ทำงานเมื่อมีการเรียกใช้ Components
 */
onMounted(async () => {
  getAll();
});
</script>

<template>
  <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 row q-pb-sm">
    <div class="header-text">
      <q-btn
        icon="mdi-arrow-left"
        unelevated
        round
        dense
        flat
        color="primary"
        class="q-mr-sm"
        @click="router.go(-1)"
      />
      รายละเอียด {{ personalData.fullName }}
    </div>
  </div>
  <div class="q-pb-lg">
    <div class="row q-mb-sm justify-end">
      <q-btn
        color="public"
        label="ตรวจสอบข้อมูลกับกรมการปกครอง"
        @click="checkInformation"
      >
      </q-btn>
    </div>
    <q-card class="row q-pb-lg" v-if="storePersonal.loading">
      <div id="information" name="1" class="col-12 q-pa-sm">
        <Informationvue
          v-model:statusEdit="statusEdit"
          v-model:data="InformationData"
          :fetch="fetchDataByType"
          :Ops="Ops"
          :OpsFilter="OpsFilter"
        />
        <div class="col-12 q-px-md"><q-separator size="4px" /></div>
        <Addressvue
          v-model:statusEdit="statusEdit"
          v-model:data="AddressData"
          :fetch="fetchDataByType"
        />
      </div>

      <div id="family" name="10" class="col-12 q-pa-sm">
        <div class="col-12 q-px-md"><q-separator size="4px" /></div>
        <Familyvue
          v-model:statusEdit="statusEdit"
          v-model:data="FamilyData"
          :fetch="fetchDataByType"
          :Ops="Ops"
          :OpsFilter="OpsFilter"
        />
      </div>

      <div id="certicate" name="2" class="col-12 q-pa-sm">
        <div class="col-12 q-px-md"><q-separator size="4px" /></div>
        <Certicate
          v-model:statusEdit="statusEdit"
          :profileType="profileType"
          v-model:data="CertificateData"
          :fetch="fetchDataByType"
        />
      </div>

      <div id="education" name="3" class="col-12 q-pa-sm">
        <div class="col-12 q-px-md"><q-separator size="4px" /></div>
        <EducationVue
          v-model:statusEdit="statusEdit"
          v-model:data="EducationData"
          :fetch="fetchDataByType"
        />
      </div>

      <div id="examresult" name="4" class="col-12 q-pa-sm">
        <div class="col-12 q-px-md"><q-separator size="4px" /></div>
        <ExamResult v-model:data="ExamData" />
      </div>

      <div id="qualification" name="5" class="col-12 q-pa-sm">
        <div class="col-12 q-px-md"><q-separator size="4px" /></div>
        <Qualification
          v-model:statusEdit="statusEdit"
          v-model:data="QualificationData"
          :fetch="fetchDataByType"
        />
      </div>

      <div id="document" name="6" class="col-12 q-pa-sm">
        <div class="col-12 q-px-md">
          <q-separator size="4px" />
        </div>
        <!-- v-model:data="QualificationData" -->
        <Document
          v-model:statusEdit="statusEdit"
          :fetch="fetchData"
          :datainformation="storePersonal.dataMain"
          :is-edit="isEdit"
        />
      </div>
    </q-card>
  </div>

  <DialogCheckInformation
    v-model:modal="modalCheck"
    :InformationData="InformationData"
    :address-data="AddressData"
    :family-data="FamilyData"
    :Ops="Ops"
    :Ops-filter="OpsFilter"
    :id-card="InformationData.idCard"
    :get-all="getAll"
  />
</template>

<style lang="scss" scoped>
.header-text {
  font-size: 24px;
  font-weight: 700;
  line-height: 32px;
  letter-spacing: 0.0025em;
  color: #35373c;
}

.information:target {
  padding-top: 84px;
}

.horizontal-line {
  background-color: #f4f4f4;
  height: 5px;
}
</style>
