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

import http from "@/plugins/http";
import config from "@/app.config";
import { useDataStore } from "@/stores/data";
import { useCounterMixin } from "@/stores/mixin";

import type { FormChildren } from "@/modules/10_registry/interface/index/Family";

import DialogHistory from "@/modules/10_registry/Dialog/DialogHistory.vue";
import SkeletonFamily from "@/modules/10_registry/components/skeleton/Family.vue";

const $q = useQuasar();
const dataStore = useDataStore();
const { messageError, date2Thai } = useCounterMixin();

const link = ref<string>(""); // ลิงก์สำหรับดึงข้อมูลครอบครัว
const idFamily = ref<string>(""); // ID ของครอบครัว
const rowsHistory = ref<any[]>([]); // ข้อมูลประวัติครอบครัว
const rowsHistoryData = ref<any[]>([]); // ข้อมูลประวัติครอบครัวสำหรับค้นหา
const typeForm = ref<string>(""); // ประเภทของข้อมูลที่แสดง (father, mother, couple, children)
const modalHistory = ref<boolean>(false); // สถานะการแสดงประวัติครอบครัว
const fatherData = reactive({
  isLive: null,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
  profileId: "",
});
const motherData = reactive({
  isLive: null,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
  profileId: "",
});
const coupleData = reactive({
  isLive: null,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
  lastNameOld: "",
  statusMarital: "",
  profileId: "",
});
const childData = ref<FormChildren[]>([]);

const visibleColumnsHistory = ref<string[]>([
  "citizenId",
  "prefix",
  "firstName",
  "lastName",
  "job",
  "isLive",
  "lastNameOld",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "prefix",
    align: "left",
    label: "คำนำหน้า",
    sortable: true,
    field: "prefix",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "firstName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "lastName",
    align: "left",
    label: "นามสกุล",
    sortable: true,
    field: "lastName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "lastNameOld",
    align: "left",
    label: "นามสกุลเดิม",
    sortable: true,
    field: "lastNameOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "job",
    align: "left",
    label: "อาชีพ",
    sortable: true,
    field: "job",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isLive",
    align: "left",
    label: "สถานภาพการมีชีวิต",
    sortable: true,
    field: "isLive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => (val ? "มีชีวิต" : "ถึงแก่กรรม"),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const checkFatherData = ref<boolean>(false); // สถานะการมีข้อมูลบิดา
const checkMotherData = ref<boolean>(false); // สถานะการมีข้อมูลมารดา
const checkCoupleData = ref<boolean>(false); // สถานะการมีข้อมูลคู่สมรส
const checkChildData = ref<boolean>(false); // สถานะการมีข้อมูลบุตร

const isLoadingHistory = ref<boolean>(false); // สถานะการโหลดประวัติข้อมูล
const isLoading = reactive({
  father: false,
  mother: false,
  couple: false,
});

/**
 * ฟังก์ชันดึงข้อมูลสมาชิกในครอบครัว
 * @param type ประเภทข้อมูล (father, mother, couple, children)
 */
async function getData(type: string) {
  (isLoading as any)[type] = true;

  await http
    .get(config.API.dataUserFamilyByType(link.value, type))
    .then((res) => {
      const data = res.data.result;
      if (data) {
        if (type == "father") {
          checkFatherData.value = data ? true : false;
          fatherData.isLive = data.fatherLive;
          fatherData.citizenId = data.fatherCitizenId;
          fatherData.prefix = data.fatherPrefix ? data.fatherPrefix : "";
          fatherData.firstName = data.fatherFirstName;
          fatherData.lastName = data.fatherLastName;
          fatherData.job = data.fatherCareer;
          fatherData.profileId = data.profileId;
        } else if (type == "mother") {
          checkMotherData.value = data ? true : false;
          motherData.isLive = data.motherLive;
          motherData.citizenId = data.motherCitizenId;
          motherData.prefix = data.motherPrefix ? data.motherPrefix : "";
          motherData.firstName = data.motherFirstName;
          motherData.lastName = data.motherLastName;
          motherData.job = data.motherCareer;
          motherData.profileId = data.profileId;
        } else if (type == "couple") {
          checkCoupleData.value = data ? true : false;
          coupleData.isLive = data.coupleLive;
          coupleData.citizenId = data.coupleCitizenId;
          coupleData.prefix = data.couplePrefix ? data.couplePrefix : "";
          coupleData.firstName = data.coupleFirstName;
          coupleData.lastName = data.coupleLastName;
          coupleData.job = data.coupleCareer;
          coupleData.lastNameOld = data.coupleLastNameOld;
          coupleData.statusMarital = data.relationship;
          coupleData.profileId = data.profileId;
        } else {
          checkChildData.value = data.length !== 0 ? true : false;
          childData.value = data;
        }
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      (isLoading as any)[type] = false;
    });
}

/**
 * ฟังก์ชันเปิดประวัติการแก้ไขข้อมูล
 * @param type ประเภทข้อมูล (father, mother, couple, children)
 * @param id ID ของครอบครัว (ใช้สำหรับบุตร)
 */
function onHistory(type: string, id: string) {
  modalHistory.value = true;
  typeForm.value = type;
  idFamily.value = id ? id : "user";
}

/** ฟังก์ชันดึงประวัติการแก้ไขข้อมูล */
async function getHistory() {
  isLoadingHistory.value = true;
  rowsHistory.value = [];
  rowsHistoryData.value = [];
  const url =
    dataStore.officerType == "OFFICER"
      ? config.API.dataUserFamilyHistory(typeForm.value, "", idFamily.value)
      : config.API.dataUserFamilyHistory(
          typeForm.value,
          "-employee",
          idFamily.value
        );

  await http
    .get(url)
    .then((res) => {
      const data = res.data.result;
      const listData = data.map((e: any) => ({
        ...e,
        citizenId: e[`${typeForm.value}CitizenId`],
        prefix: e[`${typeForm.value}Prefix`],
        firstName: e[`${typeForm.value}FirstName`],
        lastName: e[`${typeForm.value}LastName`],
        job: e[`${typeForm.value}Career`],
        isLive: e[`${typeForm.value}Live`],
        lastNameOld:
          typeForm.value === "couple" ? e.coupleLastNameOld : undefined,
      }));
      rowsHistory.value = listData;
      rowsHistoryData.value = listData;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      isLoadingHistory.value = false;
    });
}

onMounted(async () => {
  link.value = await dataStore.getProFileType();
  getData("father");
  getData("mother");
  getData("couple");
  getData("children");
});
</script>
<template>
  <div class="col-12">
    <q-toolbar class="q-px-none">
      <span class="text-blue-6 text-weight-bold text-body1"
        >ข้อมูลครอบครัว
      </span>
    </q-toolbar>
    <div class="row q-col-gutter-y-sm">
      <div class="col-12">
        <q-card bordered class="q-pa-md">
          <div class="row">
            <span class="text-blue-6 text-weight-bold text-body1">• บิดา</span>
            <q-space />
            <q-btn
              icon="mdi-history"
              color="info"
              flat
              dense
              round
              :isLoading="isLoading.father"
              size="14px"
              @click="onHistory('father', '')"
            >
              <q-tooltip>ประวัติการแก้ไขข้อมูลบิดา</q-tooltip>
            </q-btn>
            <SkeletonFamily v-if="isLoading.father" :type="'father'" />
            <div class="col-12" v-else>
              <q-card bordered class="bg-grey-1 q-pa-sm">
                <div class="row">
                  <div class="col-12 col-sm-12 col-md-12 q-gutter-y-sm">
                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        เลขประจำตัวประชาชน
                      </div>
                      <div class="col-7">
                        {{ fatherData.citizenId ? fatherData.citizenId : "-" }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        ชื่อ-นามสกุล
                      </div>
                      <div class="col-7">
                        {{
                          fatherData.firstName
                            ? `${fatherData.prefix}${fatherData.firstName} ${fatherData.lastName}`
                            : "-"
                        }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        สถานภาพการมีชีวิต
                      </div>
                      <div class="col-7">
                        {{
                          fatherData.isLive === true
                            ? "มีชีวิตอยู่"
                            : fatherData.isLive === false
                            ? "ถึงแก่กรรม"
                            : "-"
                        }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        อาชีพ
                      </div>
                      <div class="col-7">
                        {{ fatherData.job ? fatherData.job : "-" }}
                      </div>
                    </div>
                  </div>
                </div>
              </q-card>
            </div>
          </div>
        </q-card>
      </div>
      <!-- แม่ -->
      <div class="col-12">
        <q-card bordered class="q-pa-md">
          <div class="row">
            <span class="text-blue-6 text-weight-bold text-body1">• มารดา</span>
            <q-space />
            <q-btn
              icon="mdi-history"
              color="info"
              flat
              dense
              round
              size="14px"
              :isLoading="isLoading.mother"
              @click="onHistory('mother', '')"
            >
              <q-tooltip>ประวัติการแก้ไขข้อมูลมารดา</q-tooltip>
            </q-btn>
            <SkeletonFamily v-if="isLoading.mother" :type="'mother'" />
            <div v-else class="col-12">
              <q-card bordered class="bg-grey-1 q-pa-sm">
                <div class="row">
                  <div class="col-12 col-sm-12 col-md-12 q-gutter-y-sm">
                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        เลขประจำตัวประชาชน
                      </div>
                      <div class="col-7">
                        {{ motherData.citizenId ? motherData.citizenId : "-" }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        ชื่อ-นามสกุล
                      </div>
                      <div class="col-7">
                        {{
                          motherData.firstName
                            ? `${motherData.prefix}${motherData.firstName} ${motherData.lastName}`
                            : "-"
                        }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        สถานภาพการมีชีวิต
                      </div>
                      <div class="col-7">
                        {{
                          motherData.isLive === true
                            ? "มีชีวิตอยู่"
                            : motherData.isLive === false
                            ? "ถึงแก่กรรม"
                            : "-"
                        }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        อาชีพ
                      </div>
                      <div class="col-7">
                        {{ motherData.job ? motherData.job : "-" }}
                      </div>
                    </div>
                  </div>
                </div>
              </q-card>
            </div>
          </div>
        </q-card>
      </div>

      <!-- คู่สมรส -->
      <div class="col-12">
        <q-card bordered class="q-pa-md">
          <div class="row">
            <span class="text-blue-6 text-weight-bold text-body1"
              >• คู่สมรส</span
            >
            <q-space />
            <q-btn
              icon="mdi-history"
              color="info"
              flat
              dense
              round
              :isLoading="isLoading.couple"
              size="14px"
              @click="onHistory('couple', '')"
            >
              <q-tooltip>ประวัติการแก้ไขข้อมูลคู่สมรส</q-tooltip>
            </q-btn>
            <SkeletonFamily v-if="isLoading.couple" :type="'couple'" />
            <div v-else class="col-12">
              <q-card bordered class="bg-grey-1 q-pa-sm">
                <div class="row">
                  <div class="col-12 col-sm-12 col-md-6 q-gutter-y-sm">
                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        สถานภาพการสมรส
                      </div>
                      <div class="col-7">
                        {{
                          coupleData.statusMarital
                            ? coupleData.statusMarital
                            : "-"
                        }}
                      </div>
                    </div>
                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        เลขประจำตัวประชาชน
                      </div>
                      <div class="col-7">
                        {{ coupleData.citizenId ? coupleData.citizenId : "-" }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        ชื่อ-นามสกุล
                      </div>
                      <div class="col-7">
                        {{
                          coupleData.firstName
                            ? `${coupleData.prefix}${coupleData.firstName} ${coupleData.lastName}`
                            : "-"
                        }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        นามสกุลเดิม
                      </div>
                      <div class="col-7">
                        {{
                          coupleData.lastNameOld ? coupleData.lastNameOld : "-"
                        }}
                      </div>
                    </div>
                  </div>
                  <div class="col-12 col-sm-12 col-md-6 q-gutter-y-sm">
                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        สถานภาพการมีชีวิต
                      </div>
                      <div class="col-7">
                        {{
                          coupleData.isLive === true
                            ? "มีชีวิตอยู่"
                            : coupleData.isLive === false
                            ? "ถึงแก่กรรม"
                            : "-"
                        }}
                      </div>
                    </div>
                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        อาชีพ
                      </div>
                      <div class="col-7">
                        {{ coupleData.job ? coupleData.job : "-" }}
                      </div>
                    </div>
                  </div>
                </div>
              </q-card>
            </div>
          </div>
        </q-card>
      </div>

      <!-- ลูก -->
      <div v-if="childData.length !== 0" class="col-12 q-gutter-y-sm">
        <q-card
          v-for="(item, index) in childData"
          bordered
          class="q-pa-md"
          :key="item.id"
        >
          <div class="row">
            <span class="text-blue-6 text-weight-bold text-body1"
              >• บุตรคนที่ {{ index + 1 }}</span
            >
            <q-space />
            <q-btn
              icon="mdi-history"
              color="info"
              flat
              dense
              round
              size="14px"
              @click="onHistory('children', item.id)"
            >
              <q-tooltip>ประวัติการแก้ไขข้อมูลบุตร</q-tooltip>
            </q-btn>
            <div class="col-12">
              <q-card bordered class="bg-grey-1 q-pa-sm">
                <div class="row">
                  <div class="col-12 col-sm-12 col-md-12 q-gutter-y-sm">
                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        เลขประจำตัวประชาชน
                      </div>
                      <div class="col-7">
                        {{
                          item.childrenCitizenId ? item.childrenCitizenId : "-"
                        }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        ชื่อ-นามสกุล
                      </div>
                      <div class="col-7">
                        {{
                          item.childrenFirstName
                            ? `${item.childrenPrefix}${item.childrenFirstName} ${item.childrenLastName}`
                            : "-"
                        }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        สถานภาพการมีชีวิต
                      </div>
                      <div class="col-7">
                        {{
                          item.childrenLive === true
                            ? "มีชีวิตอยู่"
                            : item.childrenLive === false
                            ? "ถึงแก่กรรม"
                            : "-"
                        }}
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-5 text-grey-6 text-weight-medium">
                        อาชีพ
                      </div>
                      <div class="col-7">
                        {{ item.childrenCareer ? item.childrenCareer : "-" }}
                      </div>
                    </div>
                  </div>
                </div>
              </q-card>
            </div>
          </div>
        </q-card>
      </div>
    </div>
  </div>

  <DialogHistory
    v-model:modal="modalHistory"
    mother
    :title="`ประวัติการแก้ไขข้อมูล${
      typeForm === 'father'
        ? 'บิดา'
        : typeForm === 'mother'
        ? 'มารดา'
        : typeForm === 'couple'
        ? 'คู่สมรส'
        : 'บุตร'
    }`"
    :getData="getHistory"
    :rows="rowsHistory"
    :rows-data="rowsHistoryData"
    :visibleColumns="visibleColumnsHistory"
    :columns="
      typeForm === 'couple'
        ? columnsHistory
        : columnsHistory?.filter((e) => e.name !== 'lastNameOld')
    "
    :is-loading="isLoadingHistory"
  />
</template>

<style scoped>
.cardStyle {
  border-radius: 8px !important;
  border: 1px solid #eeeded;
  box-shadow: 3px 3px 20px -10px rgba(151, 150, 150, 0.261) !important;
}
</style>
