<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import type {
  FormData,
  FormRef,
} from "@/modules/11_discipline/interface/request/director";
import http from "@/plugins/http";
import config from "@/app.config";

const $q = useQuasar();
const mixin = useCounterMixin();
const {
  messageError,
  showLoader,
  dialogMessageNotify,
  dialogConfirm,
  success,
  hideLoader,
} = mixin;
/**
 * รับ props มาจาก page หลัก
 */
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
});
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const emit = defineEmits(["formDataReturn"]);
/**
 * ข้อมูลรหัสบัตรประชาชน
 */
//
const idCard = ref<string>("");
const idCardRef = ref<any>(null);

/**
 * ข้อมูลทั้งก้อน form
 */
const formData = reactive<FormData>({
  personalId: "",
  prefix: "",
  firstname: "",
  lastname: "",
  position: "",
  phone: "",
  email: "",
});

/**
 * เช็คข้อมูลจาก props
 * เมื่อมีข้อมูล
 * เก็บข้อมูลลง formData
 */
watch(props.data, async () => {
  // console.log("data==>", props.data)
  formData.prefix = props.data.prefix;
  formData.firstname = props.data.firstname;
  formData.lastname = props.data.lastname;
  formData.position = props.data.position;
  formData.phone = props.data.phone;
  formData.email = props.data.email;

});

/**
 * เพิ่มบุคลากร
 */
function addEmployee() {
  if (idCard.value.length === 13) {
    console.log("idCard===>", idCard.value);
    showLoader();
    http
      .post(config.API.profileSearchPersonal(), {
        fieldName: "idcard",
        keyword: idCard.value,
      })
      .then((res) => {
        const dataApi = res.data.result;
        if (dataApi.length > 0) {
          const dataList = dataApi[0];
          formData.prefix = dataList.prefix;
          formData.firstname = dataList.firstName;
          formData.lastname = dataList.lastName;
          formData.position = dataList.position;
          formData.phone = dataList.phone;
          formData.email = dataList.email;
        } else {
          dialogMessageNotify($q, "ไม่มีข้อมูลบุคคลากรที่ต้องการค้นหา");
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
      });
  }
  if (idCard.value.length !== 13) {
    hideLoader();
    dialogMessageNotify($q, "กรุณากรอกเลขบัตรประชาชนให้ครบ 13 หลัก");
  } else {
    console.log("nodata");
  }
}

/**
 * ตรวจสอบข้อมูลก่อนส่งไปยัง api
 */
const prefixRef = ref<object | null>(null);
const firstnameRef = ref<object | null>(null);
const lastnameRef = ref<object | null>(null);
const positionRef = ref<object | null>(null);
const phoneRef = ref<object | null>(null);
const emailRef = ref<object | null>(null);
const formRef: FormRef = {
  prefix: prefixRef,
  firstname: firstnameRef,
  lastname: lastnameRef,
  position: positionRef,
  phone: phoneRef,
  email: emailRef,
};

/** ฟังชั่นตรวจสอบความถูกต้องก่อน บันทึก */
function onValidate() {
  const hasError = [];
  for (const key in formRef) {
    if (Object.prototype.hasOwnProperty.call(formRef, key)) {
      const property = formRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    props.onSubmit(formData);
  }
}

function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}
</script>
<template>
  <form @submit.prevent.stop="onValidate">
    <q-card bordered>
      <div class="col-12 row q-pa-md">
        <div class="row q-col-gutter-md">
          <div class="row col-12" v-if="data === null">
            <q-card
              bordered
              class="row col-12"
              style="border: 1px solid #d6dee1"
            >
              <div
                class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-sm q-px-md"
              >
                ค้นหาบุคคลากรที่อยู่ในระบบ
              </div>
              <div class="col-12"><q-separator /></div>
              <div class="col-xs-12 q-pa-sm row">
                <div class="col-6">
                  <q-input
                    :class="inputEdit(isReadonly)"
                    dense
                    outlined
                    v-model="idCard"
                    label="รหัสบัตรประชาชน"
                    ref="idCardRef"
                    for="idCardRef"
                    hide-bottom-space
                    :rules="[(val: string) => !!val || `${'กรุณากรอกรหัสบัตรประชาชน'}`]"
                  />
                </div>
                <div class="col-2">
                  <q-btn
                    unelevated
                    dense
                    color="primary"
                    class="q-px-md q-py-sm q-ml-sm"
                    @click="addEmployee"
                    label="เพิ่มบุคลากร"
                    id="addCustomer"
                  />
                </div>
              </div>
            </q-card>
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.prefix"
              label="คำนำหน้า"
              ref="prefixRef"
              for="prefixRef"
              hide-bottom-space
              :rules="[(val: string) => val !== null && val !== '' || `${'กรุณากรอกคำนำหน้า'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.firstname"
              label="ชื่อ"
              ref="firstnameRef"
              for="firstnameRef"
              hide-bottom-space
              :rules="[(val: string) => val !== null && val !== '' || `${'กรุณากรอกชื่อ'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.lastname"
              label="นามสกุล"
              ref="lastnameRef"
              for="lastnameRef"
              hide-bottom-space
              :rules="[(val: string) => !!val || `${'กรุณากรอกนามสกุล'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.position"
              label="ตำแหน่ง"
              ref="positionRef"
              for="positionRef"
              hide-bottom-space
              :rules="[(val: string) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.phone"
              label="เบอร์โทร"
              ref="phoneRef"
              for="phoneRef"
              type="tel"
              mask="##########"
              hide-bottom-space
              :rules="[(val: string) => !!val || `${'กรุณากรอกเบอร์โทร'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.email"
              label="อีเมล"
              ref="emailRef"
              hide-bottom-space
              for="emailRef"
              :rules="[(val: string) => !!val || `${'กรุณากรอกอีเมล'}`]"
            />
          </div>
        </div>
      </div>
      <q-separator />
      <div class="row col-12 q-pa-sm">
        <q-space />
        <q-btn
          for="ButtonOnSubmit"
          id="formSubmit"
          color="secondary"
          label="บันทึก"
          type="submit"
          ><q-tooltip>บับทึกข้อมูล</q-tooltip></q-btn
        >
      </div>
    </q-card>
  </form>
</template>
