<template>
  <div>
    <q-banner
      rounded
      class="bg-blue-1 text-blue-10 q-mb-md"
      dense
    >
      <template #avatar>
        <q-icon name="mdi-robot-outline" color="blue-8" />
      </template>
      As cobranças do TBR (contas a pagar/receber) são geradas
      <span class="text-weight-medium">automaticamente todo mês</span>, com base no
      faturamento do mês fechado — não é necessária intervenção humana. A geração
      manual abaixo continua disponível caso você queira antecipar ou revisar.
    </q-banner>

    <DefaultTable
      v-model:rows="rows"
    :columns="columns"
    :show-search-field="true"
    :add-item="canAdd"
    no-api-call
    add-item-label="Gerar Contas a Receber"
    @on-add-item="onAddItem"
  >
    <template #body-cell-tbr_value="{ row }">
      <q-td>{{ formatToBRLCurrency(row.tbr_value) }}</q-td>
    </template>

    <template #body-cell-royalties_effective_value="{ row }">
      <q-td>{{ formatToBRLCurrency(row.royalties_effective_value) }}</q-td>
    </template>

    <template #body-cell-fnm_effective_value="{ row }">
      <q-td>{{ formatToBRLCurrency(row.fnm_effective_value) }}</q-td>
    </template>

    <template #body-cell-maintenance_effective_value="{ row }">
      <q-td>{{ formatToBRLCurrency(row.maintenance_effective_value) }}</q-td>
    </template>

    <template #body-cell-final_value="{ row }">
      <q-td>{{ formatToBRLCurrency(row.final_value) }}</q-td>
    </template>

    <template #body-cell-receivable_generated="{ row }">
      <q-td>
        <q-chip
          v-if="row.receivable_generated"
          color="positive"
          text-color="white"
          dense
          label="Gerado"
        />
        <q-chip v-else color="warning" text-color="white" dense label="Pendente" />
      </q-td>
    </template>
    </DefaultTable>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useQuasar } from "quasar";

import DefaultTable from "src/components/defaults/DefaultTable.vue";
import GenerateReceivableDialog from "src/pages/tbr/components/GenerateReceivableDialog.vue";

import api from "src/api";
import { formatToBRLCurrency, formatUnitName } from "src/helpers/utils";
import { permissionStore } from "src/stores/permission";

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

const columns = [
  { name: "id", label: "ID", field: "id", align: "left" },
  {
    name: "unit_id",
    label: "Unidade",
    field: (row) => formatUnitName(row.unit, `#${row.unit_id}`),
    align: "left",
  },
  {
    name: "contract_month_reference",
    label: "Mês Contrato",
    field: "contract_month_reference",
    align: "left",
  },
  {
    name: "tbr_value",
    label: "TBR",
    field: "tbr_value",
    align: "left",
  },
  {
    name: "royalties_effective_value",
    label: "Royalties",
    field: "royalties_effective_value",
    align: "left",
  },
  {
    name: "fnm_effective_value",
    label: "FNM",
    field: "fnm_effective_value",
    align: "left",
  },
  {
    name: "maintenance_effective_value",
    label: "Manutenção",
    field: "maintenance_effective_value",
    align: "left",
  },
  {
    name: "final_value",
    label: "Total",
    field: "final_value",
    align: "left",
  },
  {
    name: "royalties_applied_criteria",
    label: "Critério",
    field: "royalties_applied_criteria",
    align: "left",
  },
  {
    name: "receivable_generated",
    label: "Status",
    field: "receivable_generated",
    align: "left",
  },
];

async function loadData() {
  try {
    const { data } = await api.get("/tbr-calculation");
    rows.value = data.payload ?? [];
  } catch (err) {
    console.error(err);
    $q.notify({ type: "negative", message: "Falha ao carregar cálculos." });
  }
}

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

onMounted(loadData);
</script>
