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

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

import Form from "@/modules/07_appealComplain/views/Form.vue";
import type {
  FormProfile,
  FormDataType,
} from "@/modules/07_appealComplain/interface/response/mainType";
const router = useRouter();
const $q = useQuasar();
const mixin = useCounterMixin();

const { findOrgName, success, messageError, showLoader, hideLoader } = mixin;

const formProfile = reactive<FormProfile>({
  profileId: "",
  fullname: "",
  citizenId: "",
  oc: "",
  position: "",
});

/** ดึงข้อมูลจาก keycloak*/
function getProFile() {
  showLoader();
  http
    .get(config.API.profilePosition())
    .then((res) => {
      const data = res.data.result;
      formProfile.profileId = data.profileId;
      formProfile.fullname = `${data.prefix}${data.firstName} ${data.lastName}`;
      formProfile.citizenId = data.citizenId;
      formProfile.oc = findOrgName(data);
      formProfile.position = data.position;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * บันทึกข้อมูล
 * @param data ฟอร์มข้อมูล
 */
function onSubmit(data: FormDataType) {
  const formData = new FormData();
  formData.append("profileId", data.profileId);
  formData.append("citizenId", data.citizenId);
  formData.append("fullname", data.fullname);
  formData.append("title", data.title);
  formData.append("description", data.description);
  formData.append("type", data.type);
  formData.append("year", "");
  formData.append("caseType", "");
  formData.append("caseNumber", "");
  if (data.files) {
    formData.append("file", data.files);
  }
  formData.append("oc", data.oc);
  formData.append("position", data.position);
  showLoader();
  http
    .post(config.API.appealAdd(), formData)
    .then((res) => {
      /** รอรับ id จาก response */
      router.push(`/appeal-complain/${res.data.result}`);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

onMounted(() => {
  getProFile();
});
</script>

<template>
  <div class="col-12 row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        <q-btn
          icon="mdi-arrow-left"
          unelevated
          round
          dense
          flat
          color="primary"
          class="q-mr-sm"
          @click="router.push('/appeal-complain')"
        />
        เพิ่มอุทธรณ์/ร้องทุกข์
      </div>
      <Form :on-submit="onSubmit" :form-profile="formProfile" />
    </div>
  </div>
</template>
