<template>
  <div class="q-pa-md">
    <DefaultTable
      ref="tableRef"
      :columns="columns"
      :api-call="loadContracts"
      :show-search-field="true"
      :add-item="true"
      :female="false"
      title="Contratos"
      description="Contratos"
      @on-add-item="openCreateDialog"
    >
      <template #body-cell-contract_dates="{ row }">
        <q-td
          >{{ formatDateYMDtoDMY(row.start_date) }} -
          {{ formatDateYMDtoDMY(row.end_date) }}</q-td
        >
      </template>

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

      <template #body-cell-royalties="{ row }">
        <q-td>
          {{
            row.tbr_fixed_value_percentage != null
              ? `${(row.tbr_fixed_value_percentage * 100).toFixed(2)}%`
              : "-"
          }}
        </q-td>
      </template>

      <template #body-cell-fnm="{ row }">
        <q-td>
          {{
            row.marketing_fund_percentage != null
              ? `${(row.marketing_fund_percentage * 100).toFixed(2)}%`
              : "-"
          }}
        </q-td>
      </template>

      <template #body-cell-maintenance="{ row }">
        <q-td>
          {{
            row.maintance_tax_percentage != null
              ? `${(row.maintance_tax_percentage * 100).toFixed(2)}%`
              : "-"
          }}
        </q-td>
      </template>

      <template #body-cell-inhabitant_classification="{ row }">
        <q-td>{{
          row.municipality_size?.description ??
          row.inhabitant_classification?.description ??
          "-"
        }}</q-td>
      </template>

      <template #body-cell-actions="{ row: contract }">
        <q-td align="center">
          <div class="row no-wrap" style="gap: 4px">
            <q-btn
              flat
              round
              dense
              icon="mdi-eye-outline"
              @click="openViewDialog(contract)"
            />
            <q-btn
              flat
              round
              dense
              icon="mdi-file-edit-outline"
              @click="openEditDialog(contract)"
            />
            <q-btn
              flat
              round
              dense
              icon="mdi-trash-can-outline"
              color="negative"
              @click="confirmDelete(contract)"
            />
          </div>
        </q-td>
      </template>
    </DefaultTable>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useQuasar } from "quasar";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import {
  getFranchiseeContractsByUnit,
  deleteFranchiseeContract,
} from "src/api/franchisee_contract";
import { formatDateYMDtoDMY, formatToBRLCurrency } from "src/helpers/utils";
import CreateContractDialog from "src/pages/unit/components/CreateContractDialog.vue";
import EditContractDialog from "src/pages/unit/components/EditContractDialog.vue";
import EditContractTaxesDialog from "src/pages/unit/components/EditContractTaxesDialog.vue";
import ViewContractDialog from "src/pages/unit/components/ViewContractDialog.vue";

const props = defineProps({
  unitId: {
    type: Number,
    default: null,
  },
});

const $q = useQuasar();
const tableRef = ref(null);

const loadContracts = () => getFranchiseeContractsByUnit(props.unitId);

function openViewDialog(contract) {
  $q.dialog({
    component: ViewContractDialog,
    componentProps: { unitId: props.unitId, contract },
  });
}

function openCreateDialog() {
  $q.dialog({
    component: CreateContractDialog,
    componentProps: { unitId: props.unitId },
  }).onOk(() => {
    tableRef.value?.refresh();
  });
}

function openEditDialog(contract) {
  $q.dialog({
    component: EditContractDialog,
    componentProps: { unitId: props.unitId, contract },
  }).onOk((result) => {
    tableRef.value?.refresh();
    if (result?.openTaxes) {
      setTimeout(() => openTaxesDialog(result.contract), 300);
    }
  });
}

function openTaxesDialog(contract) {
  $q.dialog({
    component: EditContractTaxesDialog,
    componentProps: { contract },
  }).onOk(() => {
    tableRef.value?.refresh();
  });
}

function confirmDelete(contract) {
  $q.dialog({
    title: "Excluir contrato",
    message: `Deseja excluir o contrato #${contract.protocol}?`,
    ok: { color: "negative", label: "Excluir" },
    cancel: { color: "primary", outline: true, label: "Cancelar" },
  }).onOk(async () => {
    await deleteFranchiseeContract(contract.id);
    tableRef.value?.refresh();
  });
}

const columns = [
  {
    name: "protocol",
    label: "Contrato",
    field: "protocol",
    align: "left",
  },
  {
    name: "contract_dates",
    label: "Data Inicial - Final",
    field: "start_date",
    align: "left",
  },
  {
    name: "tbr_fixed_value",
    label: "TBR",
    field: "tbr_fixed_value",
    align: "left",
  },
  {
    name: "royalties",
    label: "Royalties",
    field: "tbr_fixed_value_percentage",
    align: "left",
  },
  {
    name: "fnm",
    label: "FNM",
    field: "marketing_fund_percentage",
    align: "left",
  },
  {
    name: "maintenance",
    label: "Taxa de Manutenção",
    field: "maintance_tax_percentage",
    align: "left",
  },
  {
    name: "inhabitant_classification",
    label: "Faixa de Habitantes",
    field: "inhabitant_classification",
    align: "left",
  },
  {
    name: "actions",
    label: "Ações",
    field: "actions",
    align: "center",
  },
];
</script>
