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

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

        <div class="row q-col-gutter-x-sm">
          <DefaultInput
            :model-value="unitData.id"
            class="col-md-3 col-12"
            color="secondary"
            disable
            label="ID"
            label-color="secondary"
          />

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

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

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

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

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

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

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

        <div class="row q-col-gutter-sm q-mt-xs">
          <DefaultCurrencyInput
            v-model="contractForm.tbr_fixed_value"
            class="col-md-3 col-12"
            color="secondary"
            disable
            label="TBR $"
            label-color="secondary"
          />

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

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

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

      <q-card-section>
        <div class="text-body2 q-mb-sm">
          Histórico de Reajuste de Valores e TBR
        </div>

        <q-table
          dense
          flat
          no-data-label="Nenhum histórico disponível"
          row-key="id"
          :columns="historyColumns"
          :loading="loadingHistory"
          :pagination="{ rowsPerPage: 5 }"
          :rows="tbrHistory"
        />
      </q-card-section>

      <q-card-actions align="right">
        <q-btn color="primary" label="Fechar" @click="onDialogCancel" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { getFranchiseeContractTaxHistory } from "src/api/franchisee_contract";
import { getInhabitantClassificationsForSelect } from "src/api/inhabitant_classification";
import { getUnitMe } from "src/api/unit";
import { onMounted, reactive, ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";

import masks from "src/helpers/masks";

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";

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

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

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

const loadingHistory = ref(false);
const inhabitantOptions = ref([]);
const tbrHistory = ref([]);

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

const contractForm = reactive({
  start_date: props.contract.start_date ?? null,
  end_date: props.contract.end_date ?? null,

  tbr_fixed_value: props.contract.tbr_fixed_value
    ? parseFloat(props.contract.tbr_fixed_value)
    : null,

  invoice_due_date: props.contract.invoice_due_date ?? null,

  inhabitant_classification_id:
    props.contract.inhabitant_classification_id ?? 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,
});

const historyColumns = [
  { name: "id", label: "Id", field: "id", align: "left" },
  {
    name: "year",
    label: "Ano",
    field: (row) => new Date(row.created_at).getFullYear(),
    align: "left",
  },
  {
    name: "inhabitant_classification",
    label: "Faixa de Habitantes",
    field: "inhabitant_classification",
    align: "left",
  },
  {
    name: "tbr_fixed_value",
    label: "TBR",
    field: "tbr_fixed_value",
    align: "left",
  },
  {
    name: "tbr_fixed_value_percentage",
    label: "Royalties",
    field: (row) =>
      row.tbr_fixed_value_percentage != null
        ? `${(row.tbr_fixed_value_percentage * 100).toFixed(0)}%`
        : "-",
    align: "left",
  },
  {
    name: "marketing_fund_percentage",
    label: "FNM",
    field: (row) =>
      row.marketing_fund_percentage != null
        ? `${(row.marketing_fund_percentage * 100).toFixed(0)}%`
        : "-",
    align: "left",
  },
  {
    name: "maintance_tax_percentage",
    label: "Manutenção",
    field: (row) =>
      row.maintance_tax_percentage != null
        ? `${(row.maintance_tax_percentage * 100).toFixed(0)}%`
        : "-",
    align: "left",
  },
];

async function loadData() {
  const [unit, classifications] = await Promise.all([
    getUnitMe(),
    getInhabitantClassificationsForSelect(),
  ]);

  unitData.id = unit.id;

  unitData.franchisee_name = unit.name_responsible;

  const firstPartner = unit.partners?.[0];

  if (firstPartner) {
    unitData.franchisee_document = firstPartner.cpf;
    unitData.franchisee_birthday = firstPartner.birth_date;
  }

  inhabitantOptions.value = classifications.map((c) => ({
    label: `${c.description} (${c.acronym})`,
    value: c.id,
  }));

  loadingHistory.value = true;

  try {
    tbrHistory.value = await getFranchiseeContractTaxHistory(props.contract.id);
  } finally {
    loadingHistory.value = false;
  }
}

onMounted(loadData);
</script>
