<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 420px; max-width: 90vw">
      <DefaultDialogHeader title="Marcar como pago" @close="onDialogCancel" />
      <q-form ref="formRef" @submit.prevent="onSubmit">
        <q-card-section class="q-pt-none">
          <div class="text-body2 q-mb-md">{{ receivable.history }}</div>
          <DefaultInputDatePicker
            v-model="paymentDate"
            v-model:untreated-date="paymentDateIso"
            label="Data do pagamento"
            lazy-rules="ondemand"
            :rules="[(value) => !!value || 'Informe a data do pagamento']"
          />
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="q-pa-md q-gutter-sm">
          <q-btn outline color="negative" label="Cancelar" no-caps @click="onDialogCancel" />
          <q-btn color="primary" label="Confirmar" type="submit" no-caps :loading="loading" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import { settleFranchiseeReceivable } from "src/api/franchisee_account_receive";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";

defineEmits([...useDialogPluginComponent.emits]);
const { receivable } = defineProps({ receivable: { type: Object, required: true } });
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const today = new Date();
const paymentDate = ref(today.toLocaleDateString("pt-BR"));
const paymentDateIso = ref([
  today.getFullYear(),
  String(today.getMonth() + 1).padStart(2, "0"),
  String(today.getDate()).padStart(2, "0"),
].join("-"));
const formRef = ref(null);
const { loading, execute: submitForm } = useSubmitHandler({
  formRef,
  onSuccess: (response) => onDialogOK(response),
});
const onSubmit = () => submitForm(() =>
  settleFranchiseeReceivable(receivable.id, { payment_date: paymentDateIso.value }),
);
</script>
