<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin overflow-hidden"
      style="width: 100%; max-width: 1400px"
    >
      <DefaultDialogHeader :title="'Editar Taxas'" @close="onDialogCancel" />

      <q-card-section>
        <div class="text-body2 q-mb-sm">Definir Valores</div>

        <div class="row q-col-gutter-sm">
          <DefaultSelect
            v-model="form.municipality_size_id"
            label="Faixa de Habitantes"
            color="secondary"
            label-color="secondary"
            :options="municipalitySizeOptions"
            emit-value
            map-options
            use-input
            fill-input
            hide-selected
            input-debounce="0"
            class="col-md-4 col-12"
          />

          <DefaultCurrencyInput
            v-model="form.tbr_fixed_value"
            label="TBR $"
            color="secondary"
            label-color="secondary"
            class="col-md-2 col-12"
          />

          <DefaultInput
            v-model="form.tax_base_royalts"
            label="Taxa Base Royalties"
            color="secondary"
            label-color="secondary"
            type="number"
            step="0.01"
            class="col-md-2 col-12"
          >
            <template #append>
              <span class="text-secondary">%</span>
            </template>
          </DefaultInput>

          <DefaultInput
            v-model="form.tax_base_fnm"
            label="Fundo Nacional de Marketing"
            color="secondary"
            label-color="secondary"
            type="number"
            step="0.01"
            class="col-md-2 col-12"
          >
            <template #append>
              <span class="text-secondary">%</span>
            </template>
          </DefaultInput>

          <DefaultInput
            v-model="form.tax_base_maintenance"
            label="Taxa de Manutenção"
            color="secondary"
            label-color="secondary"
            type="number"
            step="0.01"
            class="col-md-2 col-12"
          >
            <template #append>
              <span class="text-secondary">%</span>
            </template>
          </DefaultInput>
        </div>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn
          outline
          color="primary"
          label="Cancelar"
          @click="onDialogCancel"
        />
        <q-btn
          color="primary"
          label="Salvar"
          :loading="saving"
          @click="confirmSave"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

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

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

import { getMunicipalitySizes } from "src/api/tbr_calculation";
import { updateFranchiseeContract } from "src/api/franchisee_contract";

defineEmits([...useDialogPluginComponent.emits]);

const props = defineProps({
  contract: {
    type: Object,
    required: true,
  },
});

const { dialogRef, onDialogHide, onDialogCancel, onDialogOK } =
  useDialogPluginComponent();

const $q = useQuasar();
const saving = ref(false);
const municipalitySizeOptions = ref([]);

const form = reactive({
  municipality_size_id:
    props.contract.municipality_size_id ?? null,
  tbr_fixed_value: props.contract.tbr_fixed_value
    ? parseFloat(props.contract.tbr_fixed_value)
    : null,
  tax_base_royalts:
    props.contract.tbr_fixed_value_percentage != null
      ? parseFloat((props.contract.tbr_fixed_value_percentage * 100).toFixed(4))
      : null,
  tax_base_fnm:
    props.contract.marketing_fund_percentage != null
      ? parseFloat((props.contract.marketing_fund_percentage * 100).toFixed(4))
      : null,
  tax_base_maintenance:
    props.contract.maintance_tax_percentage != null
      ? parseFloat((props.contract.maintance_tax_percentage * 100).toFixed(4))
      : null,
});

async function loadData() {
  const sizes = await getMunicipalitySizes();
  municipalitySizeOptions.value = (sizes ?? []).map((s) => ({
    label: s.description,
    value: s.id,
  }));
}

function confirmSave() {
  $q.dialog({
    message: "Confirmar alteração nas Taxas?",
    ok: { label: "Confirmar", color: "primary" },
    cancel: { label: "Cancelar", color: "primary", outline: true },
  }).onOk(save);
}

async function save() {
  saving.value = true;
  try {
    await updateFranchiseeContract(props.contract.id, {
      municipality_size_id: form.municipality_size_id,
      tbr_fixed_value: form.tbr_fixed_value,
      tbr_fixed_value_percentage:
        form.tax_base_royalts != null ? form.tax_base_royalts / 100 : null,
      marketing_fund_percentage:
        form.tax_base_fnm != null ? form.tax_base_fnm / 100 : null,
      maintance_tax_percentage:
        form.tax_base_maintenance != null
          ? form.tax_base_maintenance / 100
          : null,
    });
    onDialogOK();
  } catch (error) {
    console.error(error);
  } finally {
    saving.value = false;
  }
}

onMounted(loadData);
</script>
