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

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

import type { FormData } from "@/modules/11_discipline/interface/request/director";

import Header from "@/components/DialogHeader.vue";

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

const isReadonly = ref<boolean>(false);
const modal = defineModel<boolean>("modal", { required: true });
const personalId = defineModel<string>("personalId", { required: true });
const isEdit = defineModel<boolean>("isEdit", { required: true });

const props = defineProps({
  getList: Function,
});

const data = reactive<FormData>({
  personalId: "",
  prefix: "",
  firstname: "",
  lastname: "",
  position: "",
  phone: "",
  email: "",
  qualification: "",
});

function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/** ปิด popup เเละ clear */
function closeDialog() {
  modal.value = false;
  personalId.value = "";
  data.personalId = "";
  data.prefix = "";
  data.firstname = "";
  data.lastname = "";
  data.position = "";
  data.email = "";
  data.phone = "";
  data.qualification = "";
}

/** บันทึก กรรมการ */
function onSubmit() {
  showLoader();
  http
    .put(config.API.directorbyId(personalId.value), {
      prefix: data.prefix,
      firstName: data.firstname,
      lastName: data.lastname,
      position: data.position,
      email: data.email,
      phone: data.phone,
      qualification: data.qualification,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      props.getList?.();
      closeDialog();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ดึงค่าจาก api
 */
async function fetchData() {
  showLoader();
  await http
    .get(config.API.directorbyId(personalId.value))
    .then((res) => {
      const dataApi = res.data.result;
      personalId.value = dataApi.id;
      data.prefix = dataApi.prefix;
      data.firstname = dataApi.firstName;
      data.lastname = dataApi.lastName;
      data.position = dataApi.position;
      data.phone = dataApi.phone;
      data.email = dataApi.email;
      data.qualification = dataApi.qualification;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**เมื่อเริ่มโหลดหน้า
 * เรียกใช้งาน fetchData เพื่อดึงข้อมูล
 */
watch(
  () => modal.value,
  (n) => {
    if (n) {
      fetchData();
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 80%">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <Header
          :tittle="`${isEdit ? 'แก้ไข' : 'รายละเอียด'}รายชื่อกรรมการ`"
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-3">
              <q-input
                :class="inputEdit(isReadonly)"
                dense
                outlined
                :readonly="!isEdit"
                v-model="data.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
                :readonly="!isEdit"
                v-model="data.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
                :readonly="!isEdit"
                v-model="data.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
                :readonly="!isEdit"
                v-model="data.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
                :readonly="!isEdit"
                v-model="data.phone"
                label="เบอร์โทร"
                ref="phoneRef"
                for="phoneRef"
                type="tel"
                mask="##########"
                hide-bottom-space
              />
            </div>
            <div class="col-3">
              <q-input
                :class="inputEdit(isReadonly)"
                dense
                outlined
                v-model="data.email"
                :readonly="!isEdit"
                label="อีเมล"
                ref="emailRef"
                hide-bottom-space
                for="emailRef"
              />
            </div>
            <div class="col-12">
              <q-input
                :class="inputEdit(isReadonly)"
                label="คุณวุฒิ"
                type="textarea"
                dense
                :readonly="!isEdit"
                outlined
                v-model="data.qualification"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator v-if="isEdit" />

        <q-card-actions align="right" v-if="isEdit">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
