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

import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import { FamilyDataDefualt } from "@/modules/05_placement/interface/index/Main";
import type { QForm } from "quasar";
import type { PropType } from "vue";
import type { Family } from "@/modules/05_placement/interface/index/Main";
import type { DataOption } from "@/modules/05_placement/components/PersonalDetail/profileType";

import HeaderTop from "@/modules/05_placement/components/PersonalDetail/Information/top.vue";

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const { success, messageError, showLoader, hideLoader, dialogConfirm } = mixin;

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
  notiNoEdit: {
    type: Function,
    default: () => console.log("not function"),
  },
  fetch: {
    type: Function,
    default: () => console.log("not function"),
  },
  data: {
    type: Object as PropType<Family>,
    default: FamilyDataDefualt,
  },
  Ops: {
    type: Object as PropType<any>,
  },
  OpsFilter: {
    type: Object as PropType<any>,
  },
});
const emit = defineEmits(["update:statusEdit"]);

const myform = ref<QForm | null>(null);
const edit = ref<boolean>(false); //การแก้ไขข้อมูล
const onEdit = ref<boolean>(false); //การแก้ไขข้อมูล
const familyData = ref<Family>(props.data); //ข้อมูลครอบครัว

/**
 * ฟังก์ชันแก้ไขข้อมูล
 */
function checkEdit() {
  onEdit.value = true;
}

/**
 * ฟังก์ชันค้นหาข้อมูลในรายการตัวเลือก
 * @param val คำค้นหา
 * @param update ฟังก์ชัน
 * @param refData ประเภทของตัวเลือก
 */
function filterSelector(val: string, update: Function, refData: string) {
  update(() => {
    props.Ops[`${refData}`] = props.OpsFilter[`${refData}`].filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

async function refreshData() {
  if (myform.value != null) {
    myform.value.reset();
  }
  if (onEdit.value) {
    dialogConfirm(
      $q,
      async () => {
        emit("update:statusEdit", false);
        await props.fetch("Family");
        edit.value = false;
        onEdit.value = false;
      },
      `ข้อมูลมีการแก้ไข`,
      `ยืนยันยกเลิกการแก้ไขใช่หรือไม่?`
    );
  } else {
    edit.value = false;
  }
}

async function editData() {
  dialogConfirm($q, async () => {
    showLoader();
    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
      )
      .then(async () => {
        emit("update:statusEdit", false);
        await props.fetch("Family");
        await success($q, "บันทึกข้อมูลสำเร็จ");
        edit.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * ฟังก์ชันเลือกคู่สมรส
 * @param e มี, ไม่มีคู่สมรส
 */
function selectRadio(e: boolean) {
  onEdit.value = true;
  if (e) {
    familyData.value.marryPrefixId = "";
    familyData.value.marryFirstName = "";
    familyData.value.marryLastName = "";
    familyData.value.marryOccupation = "";
  }
}

/**
 * ฟังก์ชันการแก้ไขข้อมูล
 */
async function changeBtn() {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      props.notiNoEdit();
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
}

/**
 * ฟังก์ชันสำหรับคืนค่าชื่อคลาสตามค่าที่กำหนด
 * @param val ค่าที่ใช้กำหนดคลาส
 */
function getClass(val: boolean) {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
}

/**
 * ทำงานเมื่อมีการเรียกใช้ Components
 */
onMounted(async () => {
  emit("update:statusEdit", false);
});
</script>

<template>
  <q-card flat class="col-12 q-px-lg q-py-md q-mt-md text-dark">
    <q-form ref="myform" greedy @submit.prevent @validation-success="editData">
      <HeaderTop
        v-model:edit="edit"
        header="ข้อมูลครอบครัว"
        icon="mdi-account-group"
        :history="false"
        :changeBtn="changeBtn"
        :disable="statusEdit"
        :cancel="refreshData"
      />

      <div class="row col-12 items-top q-col-gutter-x-xs q-col-gutter-y-xs">
        <div class="col-xs-12 text-weight-bold">• บิดา</div>
        <div class="col-xs-12 col-sm-3 col-md-3">
          <selector
            :hide-dropdown-icon="!edit"
            @update:modelValue="checkEdit"
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :outlined="edit"
            dense
            v-model="familyData.fatherPrefixId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.prefixOps"
            option-value="id"
            :label="`${'คำนำหน้า'}`"
            use-input
            input-debounce="0"
            @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'prefixOps'
                      ) "
          />
        </div>

        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            :outlined="edit"
            dense
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.fatherFirstName"
            :label="`${'ชื่อ'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            :outlined="edit"
            dense
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.fatherLastName"
            :label="`${'นามสกุล'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-xs-12 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.fatherOccupation"
            :label="`${'อาชีพ'}`"
            @update:modelValue="checkEdit"
          />
        </div>

        <div class="col-12 q-pt-md q-pb-sm"><q-separator /></div>
        <div class="col-xs-12 text-weight-bold">• มารดา</div>
        <div class="col-xs-12 col-sm-3 col-md-3">
          <selector
            :hide-dropdown-icon="!edit"
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :outlined="edit"
            dense
            v-model="familyData.motherPrefixId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.prefixOps"
            option-value="id"
            :label="`${'คำนำหน้า'}`"
            use-input
            @update:modelValue="checkEdit"
            input-debounce="0"
            @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'prefixOps'
                      ) "
          />
        </div>

        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            :outlined="edit"
            dense
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.motherFirstName"
            :label="`${'ชื่อ'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            :outlined="edit"
            dense
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.motherLastName"
            :label="`${'นามสกุล'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-xs-12 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.motherOccupation"
            :label="`${'อาชีพ'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-12 q-pt-md q-pb-sm"><q-separator /></div>
        <div class="col-xs-12 q-col-gutter-x-sm items-center flex q-my-sm">
          <label class="text-weight-bold">• คู่สมรส</label>
          <q-radio
            v-model="familyData.couple"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="1"
            label="มี"
            dense
            :disable="!edit"
            @update:model-value="selectRadio"
          />
          <q-radio
            v-model="familyData.couple"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="0"
            label="ไม่มี"
            dense
            :disable="!edit"
            @update:model-value="selectRadio"
          />
        </div>

        <div
          class="col-xs-12 col-sm-2 col-md-2"
          v-if="familyData.couple == '1'"
        >
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก คำนำหน้า'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="familyData.marryPrefixId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.prefixOps"
            option-value="id"
            :label="`${'คำนำหน้า'}`"
            use-input
            @update:modelValue="checkEdit"
            input-debounce="0"
            @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'prefixOps'
                      ) "
          />
        </div>

        <div class="col-xs-6 col-sm-3 col-md-3" v-if="familyData.couple == '1'">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.marryFirstName"
            :rules="[(val:string) => !!val || `${'กรุณากรอก ชื่อ'}`]"
            :label="`${'ชื่อ'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <div class="col-xs-6 col-sm-2 col-md-2" v-if="familyData.couple == '1'">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.marryLastName"
            :rules="[(val:string) => !!val || `${'กรุณากรอก นามสกุล'}`]"
            :label="`${'นามสกุล'}`"
            @update:modelValue="checkEdit"
          />
        </div>
        <!-- <div class="col-xs-6 col-sm-2 col-md-2" v-if="familyData.couple == '1'">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.lastnameCOld"
            :rules="[(val:string) => !!val || `${'กรุณากรอก นามสกุล(เดิม)'}`]"
            :label="`${'นามสกุล(เดิม)'}`"
          />
        </div> -->
        <div
          class="col-xs-12 col-sm-3 col-md-3"
          v-if="familyData.couple == '1'"
        >
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.marryOccupation"
            :label="`${'อาชีพ'}`"
            @update:modelValue="checkEdit"
          />
        </div>
      </div>
    </q-form>
  </q-card>
</template>

<style lang="scss" scoped>
.q-card {
  box-shadow: 0px 0px 0px 0px !important;
}
</style>
