<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import Form from "@/modules/12_evaluatePersonal/components/Meeting/Form.vue";
import type { FormData } from "@/modules/12_evaluatePersonal/interface/index/meeting";
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";
import type { formData } from "@/modules/09_leave/interface/request/workTime";

const route = useRoute();
const personalId = ref<string>(route.params.id as string);
console.log(personalId.value);

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

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

/**
 * get ข้อมูลเก่ากรณีแก้ไขข้อมูล
 */
const data = reactive<any>({
  rounded: "",
  dateMeeting: "",
  dateMeetingStart: Date,
  dateMeetingEnd: new Date(),
  consider: "",
  period: "",
  title: "",
  file: [],
});

/**
 * ดึงค่าจาก api
 */
const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.meetingById(personalId.value))
    .then((res) => {
      const dataApi = res.data.result;
      data.title = dataApi.title;
      data.rounded = dataApi.round;
      data.consider = dataApi.result;
      data.period = dataApi.duration;
      data.dateMeetingStart = dataApi.dateStart;
      data.dateMeetingEnd = dataApi.dateEnd;
      data.file = dataApi.file;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

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

function putData(formData: any) {
  showLoader();
  http
    .put(config.API.meetingById(personalId.value), {
      round: formData.rounded ?? "",
      title: formData.title,
      dateStart: dateToISO(formData.dateMeetingStart),
      dateEnd: dateToISO(formData.dateMeetingEnd),
      result: formData.consider,
      duration: formData.period,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      router.push(`/evaluate/meeting`);
    });
}
</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/meeting`)"
      />
      แก้ไขการประชุม
    </div>

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