<script setup>
import { defineProps, ref } from 'vue';
import { Colors } from "@/ThemeConfig.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import GetOrderInvoicePDFButton from "@/components/search/economic/getOrderInvoicePDFButton.vue";
import Swal from "sweetalert2";
import ActionSettingsWheelButton from "@/components/displays/buttons/ActionSettingsWheelButton.vue";
import ActionSettingsWheelItem from "@/components/displays/buttons/ActionSettingsWheelItem.vue";

const props = defineProps({
  collectedOrderInvoice: {
    type: Object,
    required: false,
  },
})
/** Define the variables */
const isCollapsed = ref(true);
const isDraft = ref((props.collectedOrderInvoice?.economic_invoice_draft_id !== null));
const isBooked = ref((props.collectedOrderInvoice?.economic_invoice_booked_id !== null));

/** Create the invoice */
const onCreateInvoiceDraft = async () => {
  // Create the invoice
  console.log('Create invoice');
  await SessionUser.objects.collectedOrderInvoices.functions.economic.invoice(parseInt(props.collectedOrderInvoice.id)).then((response) => {
    console.log('Invoice created successfully', response);
    Swal.fire({
      title: 'Fakturaen er oprettet',
      text: 'Fakturaen er oprettet i E-conomic',
      icon: 'success',
      showConfirmButton: false,
      timer: 2000
    }).then(() => {
      location.reload();
    });
  }).catch((error) => {
    console.log('Error creating invoice', error);
  }
  )
}

const onSplitInvoiceCollection = async () => {
  // Split the invoice collection
  console.log('Split invoice collection');
  // Show a confirmation dialog
  Swal.fire({
    title: 'Er du sikker?',
    text: 'Er du sikker på at du vil opdele fakturaen?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Ja, opdel fakturaen',
    cancelButtonText: 'Nej, annuller',
    showLoaderOnConfirm: true,
    preConfirm: () => {
      return new Promise((resolve) => {
        // Call the split invoice collection function
        splitInvoiceCollection().then(() => {
          resolve();
        }).catch((error) => {
          console.log('Error splitting invoice collection', error);
          Swal.showValidationMessage(
            `Request failed: ${error}`
          );
        });
      });
    },
    allowOutsideClick: () => !Swal.isLoading()
  })
}
const splitInvoiceCollection = async () => {
  await SessionUser.objects.collectedOrderInvoices.functions.split_invoice(parseInt(props.collectedOrderInvoice.id)).then((response) => {
    console.log('Invoice collection split successfully', response);
    Swal.fire({
      title: 'Fakturaen er opdelt',
      text: 'Fakturaen er opdelt i E-conomic',
      icon: 'success',
      showConfirmButton: false,
      timer: 2000
    }).then(() => {
      location.reload();
    });
  }).catch((error) => {
    console.log('Error splitting invoice collection', error);
    Swal.fire({
      icon: "error",
      title: "Fejl",
      text: "Der skete en fejl under opdeling af fakturaen",
      footer: error
    });
  });
}

const onAddVehicleSubscriptions = async () => {
  // Add vehicle subscriptions
  console.log('Add vehicle subscriptions');
  await SessionUser.objects.collectedOrderInvoices.functions.add_vehicle_subscriptions(parseInt(props.collectedOrderInvoice.id)).then((response) => {
    console.log('Vehicle subscriptions added successfully', response);
    Swal.fire({
      title: 'Abonnementer tilføjet',
      text: 'Abonnementer er tilføjet i E-conomic',
      icon: 'success',
      showConfirmButton: false,
      timer: 2000
    }).then(() => {
      location.reload();
    });
  }).catch((error) => {
    console.log('Error adding vehicle subscriptions', error);
  }
  )
}

const onAddFixedPricing = async () => {
  // Add fixed pricing
  console.log('Add fixed pricing');
  await SessionUser.objects.collectedOrderInvoices.functions.add_fixed_pricing(parseInt(props.collectedOrderInvoice.id)).then((response) => {
    console.log('Fixed pricing added successfully', response);
    Swal.fire({
      title: 'Fast pris tilføjet',
      text: 'Fast pris er tilføjet i E-conomic',
      icon: 'success',
      showConfirmButton: false,
      timer: 2000
    }).then(() => {
      location.reload();
    });
  }).catch((error) => {
    console.log('Error adding fixed pricing', error);
  }
  )
}

</script>

<template>
  <!-- If the invoice is a draft or booked -->
  <div
    v-if="isDraft || isBooked"
    class="message is-success"
  >
    <div class="message-body">
      <div class="columns is-vcentered">
        <div class="column is-narrow">
          <!-- Check-mark -->
          <span class="icon is-large has-text-success">
            <i class="fas fa-check-circle fa-3x"></i>
          </span>
        </div>
        <div class="column">
          <p class="title is-4">Fakturaen er {{ isDraft ? 'gemt som faktura kladde i' : 'bogført med' }} E-conomic</p>
          <p class="subtitle is-6" v-if="isDraft">Fakturaen er gemt som kladde i E-conomic, og kan bogføres der direkte.</p>
          <p class="subtitle is-6" v-else>Fakturaen er bogført i E-conomic, der er ingen yderligere handlinger nødvendige.</p>
        </div>
      </div>
    </div>
  </div>
  <!-- If the invoice is not a draft or booked -->
  <div v-else
    class="card"
  >
    <div class="card-content">
      <div class="media">
        <div class="media-left is-flex p-2">
          <figure class="image is-48x48">
            <span class="icon" :style="{ color: Colors.global.primaryColor }">
              <i class="fas fa-file-invoice-dollar fa-3x"></i>
            </span>
          </figure>
        </div>
        <div class="media-content">
          <p class="title is-4">E-conomic</p>
          <p class="subtitle is-6">Brug E-conomic til at oprette fakturaer</p>
        </div>
        <!-- Confirm button -->
        <div class="media-right">
          <div class="buttons">
            <button
                class="button is-small is-light"
                @click="onCreateInvoiceDraft"
            >
              <span class="icon">
                <i class="fas fa-file-invoice-dollar"></i>
              </span>
              <span>Opret faktura</span>
            </button>
            <!-- Split button -->
            <action-settings-wheel-button
              icon="fas fa-ellipsis-v"
              >
              <template #actions>
                <action-settings-wheel-item
                  :label="SessionUser.objects.global.language.split + ' - ' + SessionUser.objects.collectedOrderInvoices.meta.labels.single"
                  :icon="'fas fa-cut'"
                  @click="onSplitInvoiceCollection"
                />
                <action-settings-wheel-item
                  :label="SessionUser.objects.global.language.add + ' ' + SessionUser.objects.vehicles.meta.labels.multiple + ' - ' + SessionUser.objects.vehicles.columns.wash_subscription.label"
                  :icon="'fas fa-car'"
                  @click="onAddVehicleSubscriptions"
                />
                <action-settings-wheel-item
                  :label="SessionUser.objects.global.language.add + ' ' + SessionUser.objects.global.language.payment.fixed_pricing"
                  :icon="'fas fa-tag'"
                  @click="onAddFixedPricing"/>
              </template>
            </action-settings-wheel-button>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<style scoped>

</style>