<script>
import Swal from "sweetalert2";
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
import { ObjectsGlobal } from "@/components/session/token/SessionUser/Objects/ObjectsGlobal.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import {ref} from "vue";

import {createApp} from "vue";
import PickCustomerInvoiceCollectionModal from "@/components/displays/modals/PickCustomerInvoiceCollectionModal.vue";

// Define a function to show the modal with the Vue component
const showInvoiceCollectionPickerModal = async (customerNumber, onSuccessFunction = () => {}) => {
  // Create a container element for the Vue component
  const div = document.createElement('div')
  let selectedInvoiceCollectionId = null;

  // Dynamically create and mount the Vue component
  // And add a prop to the component "onCustomerSelected"
  const app = createApp(PickCustomerInvoiceCollectionModal, {
    customer_id: customerNumber,
    onInvoiceCollectionSelected: async (selected_invoice_collection_id) => {
      if (!selected_invoice_collection_id) {
        Swal.fire({
          icon: 'error',
          title: 'Ingen faktura samling valgt',
          timer: 2000,
        });
        return null;
      }
      // Handle the customer selection here
      console.log('Selected invoice collection ID:', selected_invoice_collection_id);
      // Return the selected invoice collection ID
      // Call the onSuccess function with the selected invoice collection ID
      onSuccessFunction(selected_invoice_collection_id);
      selectedInvoiceCollectionId = selected_invoice_collection_id;
      // Close the modal
      Swal.close()
    },
    onClose: () => {
      // Close the modal
      Swal.close()
      // Return
    }
  })


  // Mount the Vue app to the dynamically created `div`
  app.mount(div)

  // Show SweetAlert2 dialog with the Vue component rendered inside
  await Swal.fire({
    html: div, // Include the Vue component’s container
    showCancelButton: false,
    showConfirmButton: false,
    allowOutsideClick: false,
    heightAuto: true,
    didDestroy: () => {
      // Clean up the Vue app when the modal is closed
      app.unmount()
    }
  }).finally(() => {
    // Return the selected invoice collection ID
    return selectedInvoiceCollectionId;
  })
}

const showCreateCustomInvoiceCollectionForm = async (customerNumber) => {
  if (!customerNumber) {
    Swal.fire({
      icon: 'error',
      title: 'Ingen kunde valgt',
      timer: 2000,
    });
    return null;
  }
  // Ask for the date of the invoice collection
  const { value: date } = await Swal.fire({
    title: 'Opret ny faktura samling',
    input: 'text',
    inputLabel: 'Dato for faktura samling',
    inputPlaceholder: 'YYYY-MM-DD',
    showCancelButton: true,
    confirmButtonText: 'Opret',
    cancelButtonText: 'Annuller',
    inputValidator: (value) => {
      if (!value) {
        return 'Du skal indtaste en dato!'
      }
    }
  })
  if (date) {
    console.log('Creating new invoice collection... ', date, ' for customer: ', customerNumber);
  } else {
    console.log('Cancelled creating new invoice collection');
    return null;
  }
}

/**
 * The CollectOrderInvoices object
 */
export const CollectedOrderInvoices = {
  meta: {
    title: "Fakturaer",
    icon: "fas fa-list",
    description: "Oversigt over samlede ordrefakturaer",
    endpoint: "/collected-invoices",
    labels: {
      single: "faktura",
      multiple: "fakturaer",
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    customer_number: {
      label: "E-conomic kundenummer",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    name: {
      label: "Navn",
      type: "string",
      sortable: true,
      creation: {
        required: false
      }
    },
    notes: {
      label: "Noter",
      type: "string",
      sortable: true,
      creation: {
        required: false
      }
    },
    processor: {
      label: "Faktureringsprocessor",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    external_id: {
      label: "Eksternt ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    po_number: {
      label: "PO nummer",
      type: "string",
      sortable: true,
      creation: {
        required: false
      }
    },
    closed_at: {
      label: "Lukket",
      type: "date",
      sortable: true,
      creation: {
        required: false
      }
    },
    created_at: {
      label: "Oprettet",
      type: "date",
      sortable: true,
      creation: {
        required: false
      }
    },
    updated_at: {
      label: "Opdateret",
      type: "date",
      sortable: true,
      creation: {
        required: false
      }
    },
  },
  add: async (customer_number, name, description, closed_at = null) => {
    return ObjectsGlobal.add.object(
        CollectedOrderInvoices.meta.endpoint,
        {
          customer_number: parseInt(customer_number),
          name: name,
          description: description,
          closed_at: closed_at,
        }
    );
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "name",
        name
      )
    },
    notes: async (id, notes) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "notes",
        notes
      )
    },
    processor: async (id, processor = null) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "processor",
        processor ? parseInt(processor) : null
      )
    },
    external_id: async (id, external_id) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "external_id",
        parseInt(external_id)
      )
    },
    po_number: async (id, po_number) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "po_number",
        po_number
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(CollectedOrderInvoices.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(CollectedOrderInvoices.meta.endpoint, id);
    }
  },
  functions: {
    split_invoice: async (id) => {
      // Send the request
      return authenticatedRequest('/collected-invoices/split', 'POST', {
        id: parseInt(id)
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    showCreateNewCustom: showCreateCustomInvoiceCollectionForm,
    showInvoiceCollectionPickerForm: showInvoiceCollectionPickerModal,
    add_vehicle_subscriptions: async (id) => {
      // Send the request
      return authenticatedRequest('/collected-invoices/vehicle-subscriptions', 'POST', {
        id: parseInt(id)
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    add_fixed_pricing: async (id) => {
      // Send the request
      return authenticatedRequest('/collected-invoices/fixed-price', 'POST', {
        id: parseInt(id)
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    stripe: {
      book_invoice: async (id) => {
        // Send the request
        return authenticatedRequest('/collected-invoices/stripe/book', 'POST', {
          id: parseInt(id)
        }).then((response) => {
          console.log(response);
          return response;
        }).catch((error) => {
          console.log(error);
          throw error;
        });
      },
    },
    economic: {
      runCheckDrafts: async () => {
        // Send the request
        return authenticatedRequest('/collected-invoices/economic/run/check-drafts', 'POST', {}).then((response) => {
          console.log(response);
          return response;
        }).catch((error) => {
          console.log(error);
          throw error;
        });
      },
      runCheckErrors: async () => {
        // Send the request
        return authenticatedRequest('/collected-invoices/economic/run/check-errors', 'POST', {}).then((response) => {
          console.log(response);
          return response;
        }).catch((error) => {
          console.log(error);
          throw error;
        });
      },
      invoice: async (invoiceId) => {
        // Show loading Swal
        Swal.fire({
          title: 'Overfører til E-conomic...',
          text: 'Vent venligst, mens vi overfører fakturaen til E-conomic',
          icon: 'info',
          showConfirmButton: false,
          showCancelButton: false
        });
        // Send the request
        return authenticatedRequest('/collected-invoices/economic', 'POST', {
          id: parseInt(invoiceId)
        }).then((response) => {
          console.log(response);
          return response;
        }).catch((error) => {
          console.log(error);
          // Try to parse the error
          let errorMessage = error.message;
          if (error.response && error.response.data && error.response.data.data && error.response.data.data.message) {
            errorMessage = error.response.data.data.message;
          }
          Swal.fire({
            title: 'Fejl',
            text: 'Der skete en fejl under overførslen til E-conomic: ' + errorMessage,
            icon: 'error'
          });
          throw error;
        });
      }
    }
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(CollectedOrderInvoices, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        CollectedOrderInvoices,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};
</script>