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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useDataLinkCenter } from "@/modules/04_registryPerson/stores/LinkCenter";
import { useProfileDataStore } from "@/modules/04_registryPerson/stores/profile";
import { useRequestEditStore } from "@/modules/04_registryPerson/stores/RequestEdit";
import type { FormPerson } from "@/modules/04_registryPerson/interface/index/family";

import Header from "@/components/DialogHeader.vue"; //ส่วนหัว popup

const $q = useQuasar();
const mixin = useCounterMixin();
const storeLinkCenter = useDataLinkCenter();
const storeProfile = useProfileDataStore();
const storeRequestEdit = useRequestEditStore();

const {
  showLoader,
  hideLoader,
  messageError,
  dialogConfirm,
  modalError,
  success,
} = mixin;

const modal = defineModel<boolean>("modal", { required: true }); // ตัวแปร popup
const profileId = defineModel<string>("profileId", { required: true }); //id บุคคล
const idCard = defineModel<string>("idCard", { required: true }); //เลขบัตร ปชช

const props = defineProps({
  fetchData: Function,
  requestId: String,
});

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

/** ปิด popup */
async function closeDialog() {
  modal.value = false;

  coupleData.isLive = 1;
  coupleData.citizenId = "";
  coupleData.prefix = "";
  coupleData.firstName = "";
  coupleData.lastName = "";
  coupleData.job = "";
  coupleData.lastNameOld = "";
  coupleData.statusMarital = "";
}

function onSubmit() {
  dialogConfirm($q, async () => {
    const body = {
      coupleCitizenId: coupleData.citizenId,
      couplePrefix: coupleData.prefix,
      coupleFirstName: coupleData.firstName,
      coupleLastName: coupleData.lastName,
      coupleCareer: coupleData.job,
      coupleLive: coupleData.isLive === 1 ? true : false,
      relationship: coupleData.statusMarital,
      coupleLastNameOld: coupleData.lastNameOld,
    };
    showLoader();
    http
      .patch(
        config.API.requestInformationbyType(
          "couple",
          storeRequestEdit.profileId
        ),
        body
      )
      .then(async (res) => {
        await upDateStatus();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** ส่ง สถานะ ดำเนินการเเล้ว */
async function upDateStatus() {
  await http
    .patch(config.API.requestEdit + `${props.requestId}`, {
      status: "COMPLETE",
      remark: "",
    })
    .then(async () => {
      await props.fetchData?.();
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function  ค้นหาข้อมูลใน select
 * @param val  คำค้นหา
 * @param update  function
 */
function filterSelectorRelation(val: any, update: Function) {
  update(() => {
    storeLinkCenter.optionRelationship =
      storeLinkCenter.optionRelationshipMain.filter(
        (v: any) => v.name.indexOf(val) > -1
      );
  });
}
watch(
  () => modal.value,
  () => {
    if (modal.value) {
      storeLinkCenter.fetchPerson();
      storeLinkCenter.fetchDataRelationship();
      // coupleData.citizenId = idCard.value;
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <Header tittle="คู่สมรส" :close="closeDialog" />
        <q-separator />

        <q-card-section class="scroll" style="max-height: 80vh">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <div class="row q-col-gutter-x-xs">
                <div class="col-xs-6 col-sm-6 col-md-2">
                  <q-select
                    outlined
                    bg-color="white"
                    lazy-rules
                    hidden-space
                    dense
                    class="inputgreen"
                    label="สถานภาพการสมรส"
                    v-model="coupleData.statusMarital"
                    use-input
                    input-debounce="0"
                    emit-value
                    map-options
                    :options="storeLinkCenter.optionRelationship"
                    option-label="name"
                    option-value="name"
                    @filter="(inputValue:string,
                    doneFn:Function) => filterSelectorRelation(inputValue, doneFn) "
                  />
                </div>
              </div>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-2">
              <q-input
                outlined
                bg-color="white"
                dense
                readonly
                v-model="coupleData.citizenId"
                :label="`${'เลขประจำตัวประชาชน'}`"
                maxlength="13"
                class="inputgreen"
                mask="#############"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-2">
              <q-select
                outlined
                bg-color="white"
                lazy-rules
                hidden-space
                dense
                class="inputgreen"
                label="คำนำหน้าชื่อ"
                v-model="coupleData.prefix"
                use-input
                input-debounce="0"
                emit-value
                map-options
                :options="storeLinkCenter.OpsPerson.prefixOps"
                option-label="name"
                option-value="name"
                @filter="(inputValue:string,
                    doneFn:Function) => storeProfile.filterSelector(inputValue, doneFn,'prefixOps'
                    ) "
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-2">
              <q-input
                outlined
                dense
                bg-color="white"
                class="inputgreen"
                lazy-rules
                v-model="coupleData.firstName"
                label="ชื่อ"
                hidden-space
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-2">
              <q-input
                outlined
                dense
                class="inputgreen"
                bg-color="white"
                hide-bottom-space
                lazy-rules
                v-model="coupleData.lastName"
                label="นามสกุล"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-2">
              <q-input
                outlined
                dense
                class="inputgreen"
                bg-color="white"
                lazy-rules
                v-model="coupleData.lastNameOld"
                label="นามสกุลเดิม"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-2">
              <q-input
                outlined
                dense
                class="inputgreen"
                bg-color="white"
                v-model="coupleData.job"
                label="อาชีพ"
              />
            </div>
            <div class="col-12">
              <div class="row q-my-xs">
                <div class="q-mr-sm">สถานภาพการมีชีวิต</div>
                <div>
                  <q-radio
                    class="q-mr-sm"
                    v-model="coupleData.isLive"
                    checked-icon="task_alt"
                    unchecked-icon="panorama_fish_eye"
                    :val="1"
                    label="ยังมีชีวิตอยู่"
                    dense
                    :color="!coupleData.isLive ? 'grey' : 'primary'"
                  />
                  <q-radio
                    v-model="coupleData.isLive"
                    checked-icon="task_alt"
                    unchecked-icon="panorama_fish_eye"
                    :val="0"
                    :color="!coupleData.isLive ? 'grey' : 'red'"
                    label="ถึงแก่กรรม"
                    dense
                  />
                </div>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn
            label="บันทึกลงทะเบียนประวัติ"
            color="secondary"
            type="submit"
          />
          <q-btn label="ยกเลิก" color="orange" @click="modal = false"
            ><q-tooltip>ยกเลิก</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
