<script setup lang="ts">
import { ref, onMounted } from "vue";
import type { QForm } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import type { DataOption } from "@/modules/05_placement/components/PersonalDetail/profileType";
import HeaderTop from "@/modules/05_placement/components/PersonalDetail/Information/top.vue";
import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";
import type { PropType } from "vue";
import type { Family } from "@/modules/05_placement/interface/index/Main";
import { FamilyDataDefualt } from "@/modules/05_placement/interface/index/Main";

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,
  },
});
const emit = defineEmits(["update:statusEdit"]);

const route = useRoute();
const $q = useQuasar();

const mixin = useCounterMixin();
const { date2Thai, success, messageError, showLoader, hideLoader } = mixin;
const edit = ref<boolean>(false);

const myform = ref<QForm | null>(null);
const familyData = ref<Family>(props.data);

const Ops = ref<any>({
  prefixOps: [],
});
const OpsFilter = ref<any>({
  prefixOps: [],
});

onMounted(async () => {
  await fetchPrefix();

  emit("update:statusEdit", false);
});

const filterSelector = (val: any, update: Function, refData: string) => {
  update(() => {
    Ops.value[`${refData}`] = OpsFilter.value[`${refData}`].filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
};

const refreshData = async () => {
  if (myform.value != null) {
    myform.value.reset();
  }
  emit("update:statusEdit", false);
  await props.fetch();
};

const fetchPrefix = async () => {
  showLoader();
  await http
    .get(config.API.prefix)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      Ops.value.prefixOps = option;
      OpsFilter.value.prefixOps = option;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const editData = async () => {
  showLoader();
  //   const body: ResponseObject = {
  //     couple: familyData.value.couple == "1",
  //     couplePrefixId: familyData.value.marryPrefixId,
  //     coupleFirstName: familyData.value.marryFirstName,
  //     coupleLastName: familyData.value.marryLastName,
  //     coupleLastNameOld: familyData.value.lastnameCOld,
  //     coupleCareer: familyData.value.marryOccupation,
  //     fatherPrefixId: familyData.value.fatherPrefixId,
  //     fatherFirstName: familyData.value.fatherFirstName,
  //     fatherLastName: familyData.value.fatherLastName,
  //     fatherCareer: familyData.value.fatherOccupation,
  //     motherPrefixId: familyData.value.motherPrefixId,
  //     motherFirstName: familyData.value.motherFirstName,
  //     motherLastName: familyData.value.motherLastName,
  //     motherCareer: familyData.value.motherOccupation,
  //     // childrens: familyData.value.childrens,
  //     createdFullName: "-",
  //     createdAt: new Date(),
  //   };

  const body = {
    couple: familyData.value.couple == "1",
    couplePrefixId: familyData.value.marryPrefixId,
    coupleFirstName: familyData.value.marryFirstName,
    coupleLastName: familyData.value.marryLastName,
    coupleLastNameOld: "",
    coupleCareer: familyData.value.marryOccupation,
    fatherPrefixId: familyData.value.fatherPrefixId,
    fatherFirstName: familyData.value.fatherFirstName,
    fatherLastName: familyData.value.fatherLastName,
    fatherCareer: familyData.value.fatherOccupation,
    motherPrefixId: 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((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      edit.value = false;
      emit("update:statusEdit", false);
      await props.fetch();
    });
};

const saveData = async () => {
  await myform.value?.validate().then(async (success: boolean) => {
    if (success) {
      await editData();
    } else {
    }
  });
};

const selectRadio = (e: boolean, i: any) => {
  if (e) {
    familyData.value.marryPrefixId = "";
    familyData.value.marryFirstName = "";
    familyData.value.marryLastName = "";
    // familyData.value.lastnameCOld = "";
    familyData.value.marryOccupation = "";
  }
};

const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false;
      props.notiNoEdit();
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>

<template>
  <q-card flat class="col-12 q-px-lg q-py-md q-mt-md text-dark">
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลครอบครัว"
      icon="mdi-account-group"
      :save="saveData"
      :history="false"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :cancel="refreshData"
    />
    <q-form ref="myform" class="col-12">
      <div class="row col-12 items-center 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"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก คำนำหน้า'}`]"
            :outlined="edit"
            dense
            lazy-rules
            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)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.fatherFirstName"
            :rules="[(val:string) => !!val || `${'กรุณากรอก ชื่อ'}`]"
            :label="`${'ชื่อ'}`"
          />
        </div>
        <div class="col-xs-6 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.fatherLastName"
            :rules="[(val:string) => !!val || `${'กรุณากรอก นามสกุล'}`]"
            :label="`${'นามสกุล'}`"
          />
        </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="`${'อาชีพ'}`"
          />
        </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"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก คำนำหน้า'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="familyData.motherPrefixId"
            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)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="familyData.motherFirstName"
            :rules="[(val:string) => !!val || `${'กรุณากรอก ชื่อ'}`]"
            :label="`${'ชื่อ'}`"
          />
        </div>
        <div class="col-xs-6 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.motherLastName"
            :rules="[(val:string) => !!val || `${'กรุณากรอก นามสกุล'}`]"
            :label="`${'นามสกุล'}`"
          />
        </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="`${'อาชีพ'}`"
          />
        </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
            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="`${'ชื่อ'}`"
          />
        </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="`${'นามสกุล'}`"
          />
        </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="`${'อาชีพ'}`"
          />
        </div>
      </div>
    </q-form>
  </q-card>
</template>

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