<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

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

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

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

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

/**  props*/
const modal = defineModel<boolean>("modal", { required: true });
const isStatusEdit = defineModel<boolean>("isStatusEdit", { required: true });
const userId = defineModel<string>("userId", { required: true });
const props = defineProps({
  fetchlist: {
    type: Function,
    required: true,
  },
});

const isPwd = ref<boolean>(true);
const formData = reactive<FormUser>({
  username: "",
  password: "",
  firstName: "",
  lastName: "",
  email: "",
});

/**
 * function fetch ข้อมูลผู้ใช้งาน
 * @param id ผู้ใช้งาน
 */
function fetchUserDetail(id: string) {
  showLoader();
  http
    .get(config.API.managementUser + `/${id}`)
    .then((res) => {
      const data = res.data;
      formData.username = data.username;
      formData.firstName = data.firstName;
      formData.lastName = data.lastName;
      formData.email = data.email;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function บันทึกข้อมูลผู้ใช้งาน*/
function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    const url = isStatusEdit.value
      ? config.API.managementUser + `/${userId.value}`
      : config.API.managementUser;

    http[isStatusEdit.value ? "put" : "post"](url, formData)
      .then(() => {
        success($q, "บันทึกข้อมูลสำเร็จ");
        props.fetchlist?.();
        closeDialog();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** function ปิด Dialog */
function closeDialog() {
  modal.value = false;
  formData.username = "";
  formData.password = "";
  formData.firstName = "";
  formData.lastName = "";
  formData.email = "";
}

watch(
  () => modal.value,
  () => {
    if (modal.value && isStatusEdit.value) {
      fetchUserDetail(userId.value);
    }
  }
);
</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="isStatusEdit ? 'แก้ไขผู้ใช้งาน' : 'เพิ่มผู้ใช้งาน'"
          :close="closeDialog"
        />
        <q-separator />
        <q-card-section>
          <div class="row q-col-gutter-md">
            <div class="col-12">
              <q-input
                :readonly="isStatusEdit"
                v-model="formData.username"
                outlined
                dense
                :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อผู้ใช้งาน'}`,]"
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                label="ชื่อผู้ใช้งาน"
              >
              </q-input>
            </div>
            <div class="col-12" v-if="!isStatusEdit">
              <q-input
                v-model="formData.password"
                outlined
                dense
                :type="isPwd ? 'password' : 'text'"
                :rules="[(val:string) => !!val || `${'กรุณากรอกรหัสผู้ใช้งาน'}`,]"
                lazy-rules
                label="รหัสผู้ใช้งาน"
                hide-bottom-space
                class="inputgreen"
              >
                <template v-slot:append>
                  <q-icon
                    :name="isPwd ? 'visibility_off' : 'visibility'"
                    class="cursor-pointer"
                    @click="isPwd = !isPwd"
                  />
                </template>
              </q-input>
            </div>
            <div class="col-12">
              <q-input
                v-model="formData.firstName"
                outlined
                dense
                :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อ'}`,]"
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                label="ชื่อ"
              >
              </q-input>
            </div>
            <div class="col-12">
              <q-input
                v-model="formData.lastName"
                outlined
                dense
                :rules="[(val:string) => !!val || `${'กรุณากรอกนามสกุล'}`,]"
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                label="นามสกุล"
              >
              </q-input>
            </div>

            <div class="col-12">
              <q-input
                v-model="formData.email"
                outlined
                dense
                :rules="[(val:string) => !!val || `${'กรุณากรอก Email'}`,]"
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                label="Email"
                type="email"
              >
              </q-input>
            </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>
