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

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

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

import Form from "@/modules/11_discipline/components/6_BasicInformation/Director/Form.vue";

const $q = useQuasar();
const route = useRoute();
const personalId = ref<string>(route.params.id.toString());
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader, dialogConfirm, success } = mixin;

/**
 * get ข้อมูลเก่ากรณีแก้ไขข้อมูล
 */
const data = reactive<FormData>({
  personalId: "",
  prefix: "",
  firstname: "",
  lastname: "",
  position: "",
  phone: "",
  email: "",
  qualification: "",
});

/**
 * ดึงค่าจาก 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();
    });
}

/**
 * บันทึกข้อมูลที่เเก้ไข
 * @param id ระบุ บุคคล
 */
function onSubmit(formData: FormData) {
  dialogConfirm($q, () => putData(formData));
}

function putData(formData: FormData) {
  showLoader();
  http
    .put(config.API.directorbyId(personalId.value), {
      prefix: formData.prefix,
      firstName: formData.firstname,
      lastName: formData.lastname,
      position: formData.position,
      email: formData.email,
      phone: formData.phone,
      qualification: formData.qualification,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      router.push(`/discipline/director`);
    });
}

/**เมื่อเริ่มโหลดหน้า
 * เรียกใช้งาน fetchData เพื่อดึงข้อมูล
 */
onMounted(() => {
  fetchData();
});
</script>
<template>
  <div class="col-xs-12 col-sm-12 col-md-11">
    <div class="toptitle col-12 row items-center">
      <q-btn
        icon="mdi-arrow-left"
        unelevated
        round
        dense
        flat
        color="primary"
        class="q-mr-sm"
        @click="router.push(`/discipline/director`)"
      />
      แก้ไขรายชื่อกรรมการ
    </div>

    <Form :on-submit="onSubmit" :data="data" />
  </div>
</template>
