<template>
  <q-page padding>
    <DefaultTable
      :key="tableKey"
      :columns="columns"
      :mostrar-selecao-de-colunas="false"
      :mostrar-botao-fullscreen="false"
      :mostrar-toggle-inativos="false"
      style="padding-right: 16px"
      :api-route="getUsers"
      open-item
      add-item
      @on-row-click="onRowClick"
      @on-add-item="onAddItem"
    />
  </q-page>
</template>

<script setup>
import DefaultTable from "src/components/geral/DefaultTable.vue";
import { ref, defineAsyncComponent } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { permissionStore } from "src/stores/permission";
import { getUsers, createUser, updateUser } from "src/api/user";

const AddEditUserDialog = defineAsyncComponent(
  () => import("src/pages/users/components/AddEditUserDialog.vue"),
);

const permission_store = permissionStore();
const $q = useQuasar();
const tableKey = ref(0);
const { t } = useI18n();

const columns = [
  {
    name: "nome",
    label: t("users.name"),
    field: "name",
    align: "left",
    style: "width: 50%",
    required: true,
  },
  {
    name: "email",
    label: "email",
    field: "email",
    align: "left",
    style: "width: 20%",
    required: true,
  },
  {},
];

const onRowClick = ({ row }) => {
  if (permission_store.getAccess("config.user", "view") === false) {
    $q.loading.hide();
    $q.notify({
      type: "negative",
      message: t("permissions.view"),
    });
    return;
  }
  $q.dialog({
    component: AddEditUserDialog,
    componentProps: {
      user: row,
      title: () =>
        useI18n().t("users.user", { something: useI18n().t("general.edit") }),
    },
  }).onOk(async (payload) => {
    await updateUser(payload, row.id);
    tableKey.value = tableKey.value + 1;
  });
};

const onAddItem = () => {
  if (permission_store.getAccess("config.user", "add") === false) {
    $q.loading.hide();
    $q.notify({
      type: "negative",
      message: t("permissions.add"),
    });
    return;
  }
  $q.dialog({
    component: AddEditUserDialog,

    componentProps: {
      title: () =>
        useI18n().t("users.user", { something: useI18n().t("general.add") }),
    },
  }).onOk(async (payload) => {
    await createUser(payload);
    tableKey.value = tableKey.value + 1;
  });
};
</script>
