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

import { useRoute } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useProfileDataStore } from "@/modules/04_registryPerson/stores/profile";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableColumn } from "quasar";
import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type {
  FormPerson,
  FormChildren,
} from "@/modules/04_registryPerson/interface/index/family";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHistory from "@/modules/04_registryPerson/components/detail/DialogHistory.vue";

const $q = useQuasar();
const route = useRoute();
const store = useProfileDataStore();
const { filterSelector } = store;
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  pathRegistryEmp,
  dialogRemove,
} = useCounterMixin();

/** props*/
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));

/** TableHisoty*/
const visibleColumns = ref<string[]>([
  "statusMarital",
  "citizenId",
  "prefix",
  "firstName",
  "lastName",
  "job",
  "isLive",
  "lastNameOld",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const columns = ref<QTableColumn[]>([
  {
    name: "statusMarital",
    align: "left",
    label: "สถานภาพการสมรส",
    sortable: true,
    field: "statusMarital",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    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",
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => date2Thai(val, false, true),
  },
]);

/** ข้อมูล*/
const fatherData = reactive<FormPerson>({
  isLive: null,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
});
const motherData = reactive<FormPerson>({
  isLive: null,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  lastNameOld: "",
  job: "",
});
const coupleData = reactive<FormPerson>({
  isLive: null,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
  lastNameOld: "",
  statusMarital: "",
  isCouple: false, // ใช้สำหรับการแสดงผลใน UI
});
const childData = ref<FormChildren[]>([]);

const modal = ref<boolean>(false);
const modalHistory = ref<boolean>(false);
const filterHistory = ref<string>("");
const titleForm = ref<string>("");
const typeForm = ref<string>("");
const historyId = ref<string>("");
const isEdit = ref<boolean>(false);
const childernId = ref<string>("");

const optionRelationshipMain = ref<DataOption[]>([]);
const optionRelationship = ref<DataOption[]>([]);

const fromData = reactive({
  isLive: 1,
  citizenId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  job: "",
  lastNameOld: "",
  statusMarital: "",
});

/** function fetch ข้อมูลบิดา*/
async function fetchDataFather() {
  await http
    .get(
      config.API.profileFamily(empType.value, "father") + `/${profileId.value}`
    )
    .then(async (res) => {
      const data = await res.data.result;

      if (data) {
        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;
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function fetch ข้อมูลมารดา*/
async function fetchDataMother() {
  await http
    .get(
      config.API.profileFamily(empType.value, "mother") + `/${profileId.value}`
    )
    .then(async (res) => {
      const data = await res.data.result;
      if (data) {
        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.lastNameOld = data.motherLastNameOld;
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function fetch ข้อมูลคู่สมรส*/
async function fetchDataCouple() {
  await http
    .get(
      config.API.profileFamily(empType.value, "couple") + `/${profileId.value}`
    )
    .then(async (res) => {
      const data = await res.data.result;
      if (data) {
        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.isCouple = data.couple;
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function fetch ข้อมูลบุตร*/
async function fetchDataChildren() {
  await http
    .get(
      config.API.profileFamily(empType.value, "children") +
        `/${profileId.value}`
    )
    .then(async (res) => {
      const data = await res.data.result;
      childData.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 *  function บันทึกข้อมูล
 * @param type  ประเภทของข้อมูล
 */
function onSubmit(type: string) {
  dialogConfirm($q, async () => {
    showLoader();
    const formBody = {
      profileId:
        !isEdit.value && empType.value === "" ? profileId.value : undefined,
      profileEmployeeId:
        !isEdit.value && empType.value !== "" ? profileId.value : undefined,
      [`${type}CitizenId`]: fromData.citizenId,
      [`${type}Prefix`]: fromData.prefix,
      [`${type}FirstName`]: fromData.firstName,
      [`${type}LastName`]: fromData.lastName,
      [`${type}Career`]: fromData.job,
      [`${type}Live`]: fromData.isLive === 1 ? true : false,
      relationship: type === "couple" ? fromData.statusMarital : undefined,
      coupleLastNameOld: type === "couple" ? fromData.lastNameOld : undefined,
      motherLastNameOld: type === "mother" ? fromData.lastNameOld : undefined,
    };

    const editId =
      type === "couple"
        ? profileId.value
        : type === "children"
        ? childernId.value
        : "";

    const url =
      isEdit.value && (type === "children" || type === "couple")
        ? config.API.profileFamily(empType.value, type) + `/${editId}`
        : config.API.profileFamily(empType.value, type);
    const method =
      isEdit.value && (type === "children" || type === "couple")
        ? "patch"
        : "post";
    try {
      await http[method](url, formBody);
      type === "father"
        ? await fetchDataFather()
        : type === "mother"
        ? await fetchDataMother()
        : type === "couple"
        ? await fetchDataCouple()
        : await fetchDataChildren();
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    } catch (e) {
      messageError($q, e);
    } finally {
      hideLoader();
    }
  });
}

/** function ปิด popup*/
function closeDialog() {
  modal.value = false;
  modalHistory.value = false;
  // เคลียร์ formData
  fromData.isLive = 1;
  fromData.citizenId = "";
  fromData.prefix = "";
  fromData.firstName = "";
  fromData.lastName = "";
  fromData.job = "";
  fromData.lastNameOld = "";
  fromData.statusMarital = "";
  filterHistory.value = "";
}

/**
 * function แก้ไขข้อมูล
 * @param type  ประเภทของบุคคล
 * @param isStatusEdit สถานะแก้ไข
 * @param data ข้อมูลเดิม
 */
function onOpenDialogForm(
  type: string,
  isStatusEdit: boolean = false,
  data: any = undefined
) {
  modal.value = true;
  typeForm.value = type;
  isEdit.value = isStatusEdit;

  if (type === "father") {
    titleForm.value = "บิดา";

    fromData.isLive =
      fatherData.isLive === null ? 1 : fatherData.isLive ? 1 : 0;
    fromData.citizenId = fatherData.citizenId;
    fromData.prefix = fatherData.prefix;
    fromData.firstName = fatherData.firstName;
    fromData.lastName = fatherData.lastName;
    fromData.job = fatherData.job;
  } else if (type === "mother") {
    titleForm.value = "มารดา";

    fromData.isLive =
      motherData.isLive === null ? 1 : motherData.isLive ? 1 : 0;
    fromData.citizenId = motherData.citizenId;
    fromData.prefix = motherData.prefix;
    fromData.firstName = motherData.firstName;
    fromData.lastName = motherData.lastName;
    fromData.lastNameOld = motherData.lastNameOld as string;
    fromData.job = motherData.job;
  } else if (type === "couple") {
    titleForm.value = "คู่สมรส";
    fromData.isLive = 1;
    if (isStatusEdit) {
      fromData.isLive =
        coupleData.isLive === null ? 1 : coupleData.isLive ? 1 : 0;
      fromData.citizenId = coupleData.citizenId;
      fromData.prefix = coupleData.prefix;
      fromData.firstName = coupleData.firstName;
      fromData.lastName = coupleData.lastName;
      fromData.job = coupleData.job;
      fromData.lastNameOld = coupleData.lastNameOld as string;
      fromData.statusMarital = coupleData.statusMarital as string;
    }
  } else if (type === "children") {
    titleForm.value = "บุตร";

    if (isStatusEdit) {
      childernId.value = data.id;
      fromData.isLive =
        data.childrenLive === null ? 1 : data.childrenLive ? 1 : 0;
      fromData.citizenId = data.childrenCitizenId;
      fromData.prefix = data.childrenPrefix;
      fromData.firstName = data.childrenFirstName;
      fromData.lastName = data.childrenLastName;
      fromData.job = data.childrenCareer;
    }
  }
}

/**
 * function ดูประวัติการแก้ไขข้อมูล
 * @param type  ประเภทของบุคคล
 * @param id
 */
async function onOpenDialogHistory(type: string, id: string = "") {
  typeForm.value = type;
  historyId.value = type === "children" ? id : profileId.value;
  modalHistory.value = true;
}

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

/**
 * function  ค้นหาข้อมูลใน select
 * @param val  คำค้นหา
 * @param update  function
 */
function filterSelectorRelation(val: string, update: Function) {
  update(() => {
    optionRelationship.value = optionRelationshipMain.value.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.profileFamilyHistory(
        historyId.value,
        empType.value,
        typeForm.value
      )
    );

    const data = await res.data.result.map((e: any) => ({
      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
          : typeForm.value === "mother"
          ? e.motherLastNameOld
          : undefined,
      lastUpdateFullName: e.lastUpdateFullName,
      lastUpdatedAt: e.lastUpdatedAt,
      statusMarital: typeForm.value === "couple" ? e.relationship : undefined,
    }));

    return data;
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

function handleDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    try {
      await http.patch(
        config.API.profileFamilyUpdateDelete(empType.value, "children") +
          `${id}`
      );
      await fetchDataChildren();
      success($q, "ลบข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** ทำงานเมื่อ Components ถูกเรียกใช้งาน*/
onMounted(async () => {
  showLoader();
  await Promise.all([
    fetchDataFather(),
    fetchDataMother(),
    fetchDataCouple(),
    fetchDataChildren(),
    fetchDataRelationship(),
  ])
    .then(() => {
      hideLoader();
    })
    .catch(() => {
      hideLoader();
    });
});
</script>

<template>
  <div class="row q-col-gutter-sm">
    <!-- • บิดา -->
    <div class="col-12">
      <q-toolbar style="padding: 0px">
        <q-toolbar-title class="text-weight-bold text-primary text-subtitle1">
          • บิดา
        </q-toolbar-title>
        <div class="row q-col-gutter-sm">
          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
            round
            flat
            color="edit"
            icon="edit"
            dense
            @click="onOpenDialogForm('father')"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip></q-btn
          >
          <q-btn
            round
            flat
            dense
            color="deep-purple"
            icon="mdi-history"
            @click="onOpenDialogHistory('father')"
          >
            <q-tooltip>ประวัติการแก้ไขข้อมูลบิดา</q-tooltip></q-btn
          >
        </div>
      </q-toolbar>

      <q-card bordered class="bg-grey-1 q-gutter-md q-ma-none q-pb-md">
        <div class="row items-start">
          <div class="col-2 text-grey-6 text-weight-medium">
            <div>เลขประจำตัวประชาชน</div>
          </div>
          <div class="col">
            {{ fatherData.citizenId ? fatherData.citizenId : "-" }}
          </div>
        </div>
        <div class="row items-start">
          <div class="col-2 text-grey-6 text-weight-medium">ชื่อ - นามสกุล</div>
          <div class="col-6">
            {{
              fatherData.prefix || fatherData.firstName || fatherData.lastName
                ? fatherData.prefix +
                  fatherData.firstName +
                  " " +
                  fatherData.lastName
                : "-"
            }}
          </div>
          <div class="col-1 text-grey-6 text-weight-medium">อาชีพ</div>
          <div class="col">
            {{ fatherData.job ? fatherData.job : "-" }}
          </div>
        </div>
        <div class="row items-start">
          <div class="col-2 text-grey-6 text-weight-medium">
            สถานภาพการมีชีวิต
          </div>
          <div class="col-10">
            {{
              fatherData.isLive === true
                ? "มีชีวิตอยู่"
                : fatherData.isLive === false
                ? "ถึงแก่กรรม"
                : "-"
            }}
          </div>
        </div>
      </q-card>
    </div>

    <!-- • มารดา -->
    <div class="col-12">
      <q-toolbar style="padding: 0px">
        <q-toolbar-title class="text-weight-bold text-primary text-subtitle1">
          • มารดา
        </q-toolbar-title>
        <div class="row q-col-gutter-sm">
          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
            round
            flat
            color="edit"
            icon="edit"
            dense
            @click="onOpenDialogForm('mother')"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip></q-btn
          >
          <q-btn
            round
            flat
            dense
            color="deep-purple"
            icon="mdi-history"
            @click="onOpenDialogHistory('mother')"
          >
            <q-tooltip>ประวัติการแก้ไขข้อมูลมารดา</q-tooltip></q-btn
          >
        </div>
      </q-toolbar>

      <q-card bordered class="bg-grey-1 q-gutter-md q-ma-none q-pb-md">
        <div class="row items-start">
          <div class="col-2 text-grey-6 text-weight-medium">
            <div>เลขประจำตัวประชาชน</div>
          </div>
          <div class="col">
            {{ motherData.citizenId ? motherData.citizenId : "-" }}
          </div>
        </div>
        <div class="row items-start">
          <div class="col-2 text-grey-6 text-weight-medium">ชื่อ - นามสกุล</div>
          <div class="col-6">
            {{
              motherData.prefix || motherData.firstName || motherData.lastName
                ? motherData.prefix +
                  motherData.firstName +
                  " " +
                  motherData.lastName
                : "-"
            }}
          </div>
          <div class="col-1 text-grey-6 text-weight-medium">นามสกุลเดิม</div>
          <div class="col">
            {{ motherData.lastNameOld ? motherData.lastNameOld : "-" }}
          </div>
        </div>
        <div class="row items-start">
          <div class="col-2 text-grey-6 text-weight-medium">
            สถานภาพการมีชีวิต
          </div>
          <div class="col-6">
            {{
              motherData.isLive === true
                ? "มีชีวิตอยู่"
                : motherData.isLive === false
                ? "ถึงแก่กรรม"
                : "-"
            }}
          </div>
          <div class="col-1 text-grey-6 text-weight-medium">อาชีพ</div>
          <div class="col">
            {{ motherData.job ? motherData.job : "-" }}
          </div>
        </div>
      </q-card>
    </div>

    <!-- • คู่สมรส -->
    <div class="col-12">
      <q-toolbar style="padding: 0px">
        <div class="row q-col-gutter-sm">
          <div class="text-weight-bold text-primary text-subtitle1">
            • คู่สมรส
          </div>
          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
            round
            flat
            dense
            color="primary"
            icon="add"
            @click="onOpenDialogForm('couple')"
          >
            <q-tooltip>เพิ่มคู่สมรส</q-tooltip></q-btn
          >
        </div>
        <q-space />
        <div class="row q-col-gutter-sm" v-if="coupleData.isCouple">
          <q-btn
            round
            flat
            dense
            color="deep-purple"
            icon="mdi-history"
            @click="onOpenDialogHistory('couple')"
          >
            <q-tooltip>ประวัติการแก้ไขข้อมูลคู่สมรส</q-tooltip></q-btn
          >
        </div>
      </q-toolbar>

      <q-card bordered class="bg-grey-1 q-pb-md" v-if="coupleData.isCouple">
        <div class="col-12 row q-py-sm q-px-md bg-grey-2 items-start">
          <div class="text-weight-medium q-pr-md">คู่สมรส</div>
          <q-space />
          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
            round
            flat
            color="edit"
            icon="edit"
            dense
            @click="onOpenDialogForm('couple', true)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
        </div>
        <q-separator />
        <div class="col-12 q-pa-md q-col-gutter-md">
          <div class="row items-start">
            <div class="col-2 text-grey-6 text-weight-medium">
              <div>สถานภาพการสมรส</div>
            </div>
            <div class="col-10">
              {{ coupleData.statusMarital ?? "-" }}
            </div>
          </div>
          <div class="row items-start">
            <div class="col-2 text-grey-6 text-weight-medium">
              <div>เลขประจำตัวประชาชน</div>
            </div>
            <div class="col-10">
              {{ coupleData.citizenId ?? "-" }}
            </div>
          </div>
          <div class="row items-start">
            <div class="col-2 text-grey-6 text-weight-medium">
              ชื่อ - นามสกุล
            </div>
            <div class="col-6">
              {{
                coupleData.prefix || coupleData.firstName || coupleData.lastName
                  ? coupleData.prefix +
                    coupleData.firstName +
                    " " +
                    coupleData.lastName
                  : "-"
              }}
            </div>
            <div class="col-1 text-grey-6 text-weight-medium">นามสกุลเดิม</div>
            <div class="col">
              {{ coupleData.lastNameOld ? coupleData.lastNameOld : "-" }}
            </div>
          </div>
          <div class="row items-start">
            <div class="col-2 text-grey-6 text-weight-medium">
              สถานภาพการมีชีวิต
            </div>
            <div class="col-6">
              {{
                coupleData.isLive === true
                  ? "มีชีวิตอยู่"
                  : coupleData.isLive === false
                  ? "ถึงแก่กรรม"
                  : "-"
              }}
            </div>
            <div class="col-1 text-grey-6 text-weight-medium">อาชีพ</div>
            <div class="col">
              {{ coupleData.job ?? "-" }}
            </div>
          </div>
        </div>
      </q-card>
    </div>

    <!-- • บุตร -->
    <div class="col-12">
      <q-toolbar style="padding: 0px">
        <div class="row q-col-gutter-sm">
          <div class="text-weight-bold text-primary text-subtitle1">• บุตร</div>
          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
            round
            flat
            dense
            color="primary"
            icon="add"
            @click="onOpenDialogForm('children')"
          >
            <q-tooltip>เพิ่มบุตร</q-tooltip></q-btn
          >
        </div>
        <q-space />
      </q-toolbar>

      <div v-for="(item, index) in childData" :key="index">
        <q-card bordered class="bg-grey-1 q-pb-md q-mb-sm">
          <div class="col-12 row q-py-sm q-px-md bg-grey-2 items-start">
            <div class="text-weight-medium q-pr-md">
              บุตรคนที่ : {{ index + 1 }}
            </div>
            <q-space />
            <div class="row q-col-gutter-sm">
              <q-btn
                v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
                round
                flat
                color="edit"
                icon="edit"
                dense
                @click="onOpenDialogForm('children', true, item)"
              >
                <q-tooltip>แก้ไขข้อมูล</q-tooltip></q-btn
              >

              <q-btn
                v-if="checkPermission($route)?.attrIsDelete"
                color="red"
                flat
                dense
                round
                icon="delete"
                @click="handleDelete(item.id)"
              >
                <q-tooltip>ลบข้อมูล</q-tooltip>
              </q-btn>

              <q-btn
                round
                flat
                dense
                color="deep-purple"
                icon="mdi-history"
                @click="onOpenDialogHistory('children', item.id)"
              >
                <q-tooltip>ประวัติการแก้ไขข้อมูลบุตร</q-tooltip></q-btn
              >
            </div>
          </div>
          <q-separator />
          <div class="col-12 q-pa-md q-col-gutter-md">
            <div class="row items-start">
              <div class="col-2 text-grey-6 text-weight-medium">
                <div>เลขประจำตัวประชาชน</div>
              </div>
              <div class="col-10">
                {{ item.childrenCitizenId }}
              </div>
            </div>
            <div class="row items-start">
              <div class="col-2 text-grey-6 text-weight-medium">
                ชื่อ - นามสกุล
              </div>
              <div class="col-6">
                {{
                  item.childrenPrefix ||
                  item.childrenFirstName ||
                  item.childrenLastName
                    ? item.childrenPrefix +
                      item.childrenFirstName +
                      " " +
                      item.childrenLastName
                    : "-"
                }}
              </div>
              <div class="col-1 text-grey-6 text-weight-medium">อาชีพ</div>
              <div class="col">
                {{ item.childrenCareer }}
              </div>
            </div>
            <div class="row items-start">
              <div class="col-2 text-grey-6 text-weight-medium">
                สถานภาพการมีชีวิต
              </div>
              <div class="col">
                {{
                  item.childrenLive === true
                    ? "มีชีวิตอยู่"
                    : item.childrenLive === false
                    ? "ถึงแก่กรรม"
                    : "-"
                }}
              </div>
            </div>
          </div>
        </q-card>
      </div>
    </div>
  </div>

  <!-- แก้ไขข้อมูล -->
  <q-dialog v-model="modal" class="dialog" persistent>
    <q-card style="min-width: 80%">
      <q-form @submit.prevent greedy @validation-success="onSubmit(typeForm)">
        <DialogHeader
          :tittle="
            isEdit
              ? `แก้ไขข้อมูล${titleForm}`
              : typeForm === 'father' || typeForm === 'mother'
              ? `แก้ไขข้อมูล${titleForm}`
              : `เพิ่มข้อมูล${titleForm}`
          "
          :close="closeDialog"
        />
        <q-separator />
        <q-card-section>
          <div class="q-col-gutter-sm">
            <div class="row col" v-if="typeForm === 'couple'">
              <q-select
                outlined
                bg-color="white"
                lazy-rules
                hidden-space
                dense
                class="inputgreen"
                :rules="[(val:string) => !!val || 'กรุณาเลือกสถานภาพการสมรส']"
                label="สถานภาพการสมรส"
                v-model="fromData.statusMarital"
                use-input
                hide-selected
                fill-input
                input-debounce="0"
                emit-value
                map-options
                :options="optionRelationship"
                option-label="name"
                option-value="name"
                style="width: 220px"
                @filter="(inputValue:string,
                doneFn:Function) => filterSelectorRelation(inputValue, doneFn) "
              />
            </div>
            <div class="row q-col-gutter-md">
              <div class="col">
                <q-input
                  outlined
                  hide-bottom-space
                  bg-color="white"
                  dense
                  v-model="fromData.citizenId"
                  :label="`${'เลขประจำตัวประชาชน'}`"
                  maxlength="13"
                  :rules="
                    typeForm !== 'couple'
                      ? [
                          (val:string) => !!val || 'กรุณากรอกเลขบัตรประชาชน',
                          (val:string) =>
                            val.length === 13 ||
                            'กรุณากรอกเลขบัตรประชาชนให้ครบ 13 หลัก',
                        ]
                      : []
                  "
                  class="inputgreen"
                  mask="#############"
                />
              </div>
              <div class="col">
                <q-select
                  outlined
                  bg-color="white"
                  lazy-rules
                  hidden-space
                  dense
                  class="inputgreen"
                  :rules="
                    typeForm !== 'couple'
                      ? [(val:string) => !!val || 'กรุณาเลือกคำนำหน้าชื่อ']
                      : []
                  "
                  label="คำนำหน้าชื่อ"
                  v-model="fromData.prefix"
                  use-input
                  hide-selected
                  fill-input
                  input-debounce="0"
                  emit-value
                  map-options
                  :options="store.Ops.prefixOps"
                  option-label="name"
                  option-value="name"
                  @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'prefixOps'
                    ) "
                />
              </div>
              <div class="col">
                <q-input
                  outlined
                  dense
                  bg-color="white"
                  class="inputgreen"
                  lazy-rules
                  v-model="fromData.firstName"
                  :rules="
                    typeForm !== 'couple'
                      ? [(val:string) => !!val || 'กรุณากรอกชื่อ']
                      : []
                  "
                  label="ชื่อ"
                  hidden-space
                />
              </div>
              <div class="col">
                <q-input
                  outlined
                  dense
                  class="inputgreen"
                  bg-color="white"
                  lazy-rules
                  v-model="fromData.lastName"
                  :rules="
                    typeForm !== 'couple'
                      ? [(val:string) => !!val || 'กรุณากรอกนามสกุล']
                      : []
                  "
                  label="นามสกุล"
                />
              </div>
              <div
                class="col"
                v-if="typeForm === 'couple' || typeForm == 'mother'"
              >
                <q-input
                  outlined
                  dense
                  class="inputgreen"
                  bg-color="white"
                  lazy-rules
                  v-model="fromData.lastNameOld"
                  label="นามสกุลเดิม"
                />
              </div>
              <div class="col">
                <q-input
                  outlined
                  dense
                  class="inputgreen"
                  bg-color="white"
                  v-model="fromData.job"
                  label="อาชีพ"
                />
              </div>
            </div>
            <div class="row">
              <div class="q-mr-sm">สถานภาพการมีชีวิต</div>
              <div>
                <q-radio
                  class="q-mr-sm"
                  v-model="fromData.isLive"
                  checked-icon="task_alt"
                  unchecked-icon="panorama_fish_eye"
                  :val="1"
                  label="ยังมีชีวิตอยู่"
                  dense
                  color="primary"
                />
                <q-radio
                  v-model="fromData.isLive"
                  checked-icon="task_alt"
                  unchecked-icon="panorama_fish_eye"
                  :val="0"
                  color="primary"
                  label="ถึงแก่กรรม"
                  dense
                />
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" id="onSubmit" type="submit" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <DialogHistory
    v-model:modal="modalHistory"
    :title="`ประวัติการแก้ไขข้อมูล${
      typeForm === 'father'
        ? 'บิดา'
        : typeForm === 'mother'
        ? 'มารดา'
        : typeForm === 'couple'
        ? 'คู่สมรส'
        : 'บุตร'
    }`"
    :columns="
      typeForm === 'couple'
        ? columns
        : typeForm === 'mother'
        ? columns?.filter((e) => e.name !== 'statusMarital')
        : columns?.filter(
            (e) => e.name !== 'lastNameOld' && e.name !== 'statusMarital'
          )
    "
    :visible-columns="visibleColumns"
    :fetch-data="fetchDataHistory"
  />
</template>

<style scoped></style>
