<template>
  <DefaultTable
    v-model:rows="rows"
    description="faixas"
    title="Faixas"
    :add-item="canAdd"
    :columns="columns"
    :female="true"
    :no-api-call="true"
    :show-search-field="true"
    @on-add-item="onAdd"
  >
    <template #body-cell-actions="{ row }">
      <q-td align="center">
        <div class="row no-wrap" style="gap: 4px">
          <q-btn
            dense
            flat
            icon="mdi-eye-outline"
            round
            size="sm"
            @click="onView(row)"
          />

          <q-btn
            v-if="canEdit"
            dense
            flat
            icon="mdi-file-edit-outline"
            round
            size="sm"
            @click="onEdit(row)"
          />
        </div>
      </q-td>
    </template>
  </DefaultTable>
</template>

<script setup>
import { getInhabitantClassifications } from "src/api/inhabitant_classification";
import { onMounted, ref } from "vue";
import { useQuasar } from "quasar";

import AddEditInhabitantClassificationDialog from "src/pages/tbr/components/AddEditInhabitantClassificationDialog.vue";
import ViewInhabitantClassificationDialog from "src/pages/tbr/components/ViewInhabitantClassificationDialog.vue";

import DefaultTable from "src/components/defaults/DefaultTable.vue";
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: "description",
    label: "Descrição",
    field: "description",
    align: "left",
  },
  { name: "start", label: "Início", field: "start", align: "left" },
  { name: "end", label: "Fim", field: "end", align: "left" },
  {
    name: "tbr_percentage",
    label: "%",
    field: "tbr_percentage",
    align: "left",
    format: (val) => `${(val * 100).toFixed(2)}%`,
  },
  { name: "actions", label: "Ações", field: "actions", align: "center" },
];

const loadData = async () => {
  rows.value = await getInhabitantClassifications();
};

const onAdd = () => {
  $q.dialog({ component: AddEditInhabitantClassificationDialog }).onOk(() =>
    loadData(),
  );
};

const onEdit = (row) => {
  $q.dialog({
    component: AddEditInhabitantClassificationDialog,
    componentProps: { item: row },
  }).onOk(() => loadData());
};

const onView = (row) => {
  $q.dialog({
    component: ViewInhabitantClassificationDialog,
    componentProps: { item: row },
  });
};

onMounted(loadData);
</script>
