<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import Form from "@/modules/12_evaluatePersonal/components/Director/Form.vue";
import type { FormData } from "@/modules/11_discipline/interface/request/director";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import router from "@/router";
import http from "@/plugins/http";
import config from "@/app.config";

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

/**เมื่อเริ่มโหลดหน้า
 * เรียกใช้งาน fetchData เพื่อดึงข้อมูล
 */
onMounted(() => {
  fetchData();
});

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

/**
 * ดึงค่าจาก api
 */
const fetchData = async () => {
  showLoader();
  await http
    // .get(config.API.evaluateDirectorById(personalId.value))
    .get(config.API.evaluateDirectorById(id.value))
    .then((res) => {
      const dataApi = res.data.result;
      data.personalId = 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;
    })
    .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.evaluateDirectorById(personalId.value), {
    .put(config.API.evaluateDirectorById(id.value), {
      Prefix: formData.prefix,
      FirstName: formData.firstname,
      LastName: formData.lastname,
      Position: formData.position,
      Email: formData.email,
      Phone: formData.phone,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      router.push(`/evaluate/director`);
    });
}
</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(`/evaluate/director`)"
      />
      แก้ไขรายชื่อกรรมการ
    </div>

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