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

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

import type { FormRole } from "@/modules/02_users/interface/request/Main";

/** importComponents*/
import DialogHeader from "@/components/DialogHeader.vue";

/** use*/
const $q = useQuasar();
const router = useRouter();
const { showLoader, hideLoader, dialogConfirm, messageError, success } =
  useCounterMixin();

/**  props*/
const modal = defineModel<boolean>("modal", { required: true });
// ฟอร์มบทบาท
const formData = reactive<FormRole>({
  roleName: "", // ขื่อบทบาท
  roleDescription: "", // คำอธิบาย
});

/**
 * function บันทึกข้อมูลผู้ใช้งาน
 */
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .post(config.API.managementAuth, formData)
      .then((res) => {
        router.push(`/roles/${res.data.result}`);
        success($q, "บันทึกข้อมูลสำเร็จ");
        closeDialog();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * function ปิด Dialog
 */
function closeDialog() {
  modal.value = false;
  formData.roleName = "";
  formData.roleDescription = "";
}
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 25%">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader :tittle="'เพิ่มบทบาท'" :close="closeDialog" />
        <q-separator />
        <q-card-section>
          <div class="row q-col-gutter-md">
            <div class="col-12">
              <q-input
                v-model="formData.roleName"
                outlined
                dense
                :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อบทบาท'}`,]"
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                label="ชื่อบทบาท"
              />
            </div>
            <div class="col-12">
              <q-input
                v-model="formData.roleDescription"
                outlined
                dense
                :rules="[(val:string) => !!val || `${'กรุณากรอกคำอิบาย'}`,]"
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                label="คำอธิบาย"
                type="textarea"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
