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

      <q-card-section>
        <div class="text-body2 q-mb-sm">Dados da Unidade</div>

        <div class="row q-col-gutter-sm">
          <DefaultInput
            :model-value="unitData.name"
            label="Nome da Unidade"
            color="secondary"
            label-color="secondary"
            class="col-md-6 col-12"
            readonly
          />

          <DefaultInput
            :model-value="unitData.cnpj"
            label="CNPJ"
            color="secondary"
            label-color="secondary"
            class="col-md-3 col-12"
            :mask="masks.Brasil.cnpj"
            :rules="[inputRules.cnpj]"
            readonly
          />

          <DefaultInput
            :model-value="unitData.id"
            label="ID"
            color="secondary"
            label-color="secondary"
            class="col-md-3 col-12"
            disable
          />

          <DefaultInput
            :model-value="unitData.franchisee_name"
            label="Nome do Franqueado"
            color="secondary"
            label-color="secondary"
            class="col-md-4 col-12"
            disable
          />

          <DefaultInput
            :model-value="unitData.franchisee_document"
            label="CPF"
            color="secondary"
            label-color="secondary"
            class="col-md-4 col-12"
            :mask="masks.Brasil.cpf"
            :rules="[inputRules.cpf]"
            disable
          />

          <DefaultInput
            :model-value="unitData.franchisee_birthday"
            label="Data de Nascimento"
            color="secondary"
            label-color="secondary"
            class="col-md-4 col-12"
            disable
          />
        </div>
      </q-card-section>

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

        <div class="row q-col-gutter-sm">
          <DefaultInputDatePicker
            v-model:untreated-date="contractForm.start_date"
            label="Data de Início"
            color="secondary"
            label-color="secondary"
            class="col-md-3 col-12"
          />

          <DefaultInputDatePicker
            v-model:untreated-date="contractForm.end_date"
            label="Data de Fim"
            color="secondary"
            label-color="secondary"
            class="col-md-3 col-12"
          />

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

          <DefaultInput
            v-model="contractForm.invoice_due_date"
            label="Dia de Vencimento do Boleto"
            color="secondary"
            label-color="secondary"
            type="number"
            class="col-md-3 col-12"
          >
          </DefaultInput>

          <DefaultSelect
            v-model="contractForm.municipality_size_id"
            label="Faixa de Habitante"
            color="secondary"
            label-color="secondary"
            :options="municipalitySizeOptions"
            emit-value
            map-options
            use-input
            fill-input
            hide-selected
            input-debounce="0"
            class="col-md-3 col-12"
          />

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

          <DefaultInput
            v-model="contractForm.tax_base_fnm"
            label="Taxa Base FMN"
            color="secondary"
            label-color="secondary"
            type="number"
            class="col-md-3 col-12"
          >
            <template #append>
              <span class="text-secondary">%</span>
            </template>
          </DefaultInput>

          <DefaultInput
            v-model="contractForm.tax_base_maintenance"
            label="Taxa Base Manutenção"
            color="secondary"
            label-color="secondary"
            type="number"
            class="col-md-3 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="save" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

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

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";
import DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import masks from "src/helpers/masks";
import { useInputRules } from "src/composables/useInputRules";

import { getUnit } from "src/api/unit";
import { getLatestTbr } from "src/api/tbr";
import { getMunicipalitySizes } from "src/api/tbr_calculation";
import { createFranchiseeContract } from "src/api/franchisee_contract";

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

const props = defineProps({
  unitId: {
    type: Number,
    required: true,
  },
});

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

const saving = ref(false);
const municipalitySizeOptions = ref([]);
const { inputRules } = useInputRules();

const unitData = reactive({
  id: null,
  name: null,
  cnpj: null,
  franchisee_name: null,
  franchisee_document: null,
  franchisee_birthday: null,
});

const contractForm = reactive({
  start_date: null,
  end_date: null,
  tbr_fixed_value: null,
  invoice_due_date: null,
  municipality_size_id: null,
  tax_base_royalts: null,
  tax_base_fnm: null,
  tax_base_maintenance: null,
});

async function loadData() {
  const [unit, latestTbr, sizes] = await Promise.all([
    getUnit(props.unitId),
    getLatestTbr(),
    getMunicipalitySizes(),
  ]);

  unitData.id = unit.id;
  unitData.name = unit.name;
  unitData.cnpj = unit.cnpj;
  unitData.franchisee_name = unit.name_responsible;

  const firstPartner = unit.partners?.[0];
  if (firstPartner) {
    unitData.franchisee_document = firstPartner.cpf;
    unitData.franchisee_birthday = firstPartner.birth_date;
  }

  if (latestTbr) {
    contractForm.tbr_fixed_value = parseFloat(latestTbr.tbr_value);
    contractForm.tax_base_royalts = parseFloat(
      (latestTbr.royalties_percentage * 100).toFixed(4),
    );
    contractForm.tax_base_fnm = parseFloat(
      (latestTbr.fnm_percentage * 100).toFixed(4),
    );
    contractForm.tax_base_maintenance = parseFloat(
      (latestTbr.maintenance_percentage * 100).toFixed(4),
    );
  }

  municipalitySizeOptions.value = (sizes ?? []).map((s) => ({
    label: s.description,
    value: s.id,
  }));
}

async function save() {
  saving.value = true;
  try {
    await createFranchiseeContract({
      unit_id: props.unitId,
      start_date: contractForm.start_date,
      end_date: contractForm.end_date,
      tbr_fixed_value: contractForm.tbr_fixed_value,
      invoice_due_date: contractForm.invoice_due_date,
      municipality_size_id: contractForm.municipality_size_id,
      tbr_fixed_value_percentage:
        contractForm.tax_base_royalts != null
          ? contractForm.tax_base_royalts / 100
          : null,
      marketing_fund_percentage:
        contractForm.tax_base_fnm != null
          ? contractForm.tax_base_fnm / 100
          : null,
      maintance_tax_percentage:
        contractForm.tax_base_maintenance != null
          ? contractForm.tax_base_maintenance / 100
          : null,
    });
    onDialogOK();
  } catch (error) {
    console.error(error);
  } finally {
    saving.value = false;
  }
}

onMounted(loadData);
</script>
