<template>
  <DefaultTable
    v-model:rows="rows"
    :columns="columns"
    title="Configurações TBR"
    description="configurações"
    :female="false"
    :no-api-call="true"
    :show-search-field="true"
    :add-item="canAdd"
    @on-add-item="onAdd"
  >
    <template #body-cell-tbr_value="{ row }">
      <q-td>{{ formatToBRLCurrency(row.tbr_value) }}</q-td>
    </template>

    <template #body-cell-royalties="{ row }">
      <q-td>{{ formatPercentage(row.royalties_percentage) }}</q-td>
    </template>

    <template #body-cell-fnm="{ row }">
      <q-td>{{ formatPercentage(row.fnm_percentage) }}</q-td>
    </template>

    <template #body-cell-maintenance="{ row }">
      <q-td>{{ formatPercentage(row.maintenance_percentage) }}</q-td>
    </template>

    <template #body-cell-actions="{ row }">
      <q-td align="center">
        <div class="row no-wrap" style="gap: 4px">
          <q-btn
            v-if="canEdit"
            flat
            round
            dense
            icon="mdi-file-edit-outline"
            size="sm"
            @click="onEdit(row)"
          />
        </div>
      </q-td>
    </template>
  </DefaultTable>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import AddEditTbrDialog from "src/pages/tbr/components/AddEditTbrDialog.vue";
import { getTbrs } from "src/api/tbr";
import { formatToBRLCurrency, formatPercentage } from "src/helpers/utils";
import { permissionStore } from "src/stores/permission";

const $q = useQuasar();
const permissions = permissionStore();
const canAdd = permissions.getAccess("franchisor_tbr", "add");
const canEdit = permissions.getAccess("franchisor_tbr", "edit");
const rows = ref([]);

const columns = [
  { name: "id", label: "ID", field: "id", align: "left" },
  { name: "year", label: "Ano", field: "year", align: "left" },
  { name: "tbr_value", label: "TBR", field: "tbr_value", align: "left" },
  {
    name: "royalties",
    label: "Royalties",
    field: "royalties_percentage",
    align: "left",
  },
  { name: "fnm", label: "FNM", field: "fnm_percentage", align: "left" },
  {
    name: "maintenance",
    label: "Manutenção",
    field: "maintenance_percentage",
    align: "left",
  },
  { name: "actions", label: "Ações", field: "actions", align: "center" },
];

async function loadData() {
  rows.value = await getTbrs();
}

function onAdd() {
  $q.dialog({ component: AddEditTbrDialog }).onOk(() => loadData());
}

function onEdit(row) {
  $q.dialog({ component: AddEditTbrDialog, componentProps: { tbr: row } }).onOk(
    () => loadData(),
  );
}

onMounted(loadData);
</script>
