<template>
  <DefaultTable
    ref="tableRef"
    :columns="columns"
    :api-call="getProducts"
    :show-search-field="false"
    description="produtos"
  >
    <template #body-cell-actions="{ row }">
      <q-btn
        v-if="canEdit"
        flat
        dense
        round
        icon="mdi-file-edit-outline"
        color="primary"
        size="sm"
        @click.stop="handleEdit(row)"
      />
    </template>
  </DefaultTable>
</template>

<script setup>
import { ref } from "vue";
import { useQuasar } from "quasar";
import { formatToBRLCurrency } from "src/helpers/utils";
import { getProducts } from "src/api/product";
import { permissionStore } from "src/stores/permission";

import DefaultTable from "src/components/defaults/DefaultTable.vue";
import AddEditStockProductDialog from "../components/AddEditStockProductDialog.vue";

const $q = useQuasar();
const canEdit = permissionStore().getAccess("franchisor_products", "edit");
const tableRef = ref(null);

const columns = [
  {
    name:     "name",
    label:    "Produto",
    field:    "name",
    align:    "left",
    sortable: true,
  },
  {
    name:    "price_sale",
    label:   "Preço",
    field:   "price_sale",
    align:   "left",
    format:  (val) => formatToBRLCurrency(val),
  },
  {
    name:     "quantity",
    label:    "Estoque Atual",
    field:    "quantity",
    align:    "center",
    sortable: true,
  },
  {
    name:  "actions",
    label: "Ações",
    field: "actions",
    align: "center",
  },
];

defineExpose({ refresh: () => tableRef.value?.refresh() });

const handleEdit = (product) => {
  $q.dialog({
    component: AddEditStockProductDialog,
    componentProps: { product },
  }).onOk(() => {
    tableRef.value?.refresh();
  });
};
</script>
