<script>
import Swal from "sweetalert2";
import {ObjectsGlobal} from "@/components/session/token/SessionUser/Objects/ObjectsGlobal.vue";
import {SessionUser} from "@/components/session/token/SessionUser.vue";
import CustomerSearchFieldPos from "@/components/forms/department/pos/input/customerSearchFieldPos.vue";
import {createApp} from "vue";

// Define a function to show the SweetAlert2 modal with the Vue component
const showCustomerSearchModal = (onSuccessFunction = null) => {
  // Create a container element for the Vue component
  const div = document.createElement('div')

  // Dynamically create and mount the Vue component
  // And add a prop to the component "onCustomerSelected"
  const app = createApp(CustomerSearchFieldPos, {
    onCustomerSelected: async (customer) => {
      if (!customer || !customer.customerNumber) {
        Swal.fire({
          icon: 'error',
          title: 'Ingen kunde valgt',
          timer: 2000,
        });
        return;
      }
      // Handle the customer selection here
      console.log('Selected customer:', customer)
      // Call the onSuccess function with the selected customer
      if (onSuccessFunction) {
        await onSuccessFunction(customer.customerNumber);
      }
      // Close the modal
      Swal.close()
    }
  })


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

  // Show SweetAlert2 dialog with the Vue component rendered inside
  Swal.fire({
    title: 'Search for a Customer',
    html: div, // Include the Vue component’s container
    showCancelButton: true,
    showConfirmButton: false,
    heightAuto: true,
    didDestroy: () => {
      // Clean up the Vue app when the modal is closed
      app.unmount()
    }
  })
}



const showChangeOrderCustomerForm = async (id) => {
  function noCustomerSelected() {
    Swal.fire({
      icon: 'error',
      title: 'Ingen kunde valgt',
      timer: 2000,
    })
  }
  function noInvoiceCollectionSelected() {
    Swal.fire({
      icon: 'error',
      title: 'Ingen faktura samling valgt',
      timer: 2000,
    })
  }
  function changeOrderInvoiceCollectionId(order_id, new_collection_id) {
    // Change the invoice collection
    return SessionUser.objects.orders.set.invoice_collection_id(
        parseInt(order_id),
        parseInt(new_collection_id)
    );
  }
  function changeOrderCustomerId(order_id, new_customer_id) {
    // Change the customer
    return SessionUser.objects.orders.set.customer_id(
        parseInt(order_id),
        parseInt(new_customer_id)
    );
  }
  function saveChanges (order_id, new_customer_id, new_collection_id) {
    // Change the customer
    changeOrderCustomerId(order_id, new_customer_id).then((response) => {
      console.log("Customer changed successfully:", response);
      // Change the invoice collection
      changeOrderInvoiceCollectionId(order_id, new_collection_id).then((response) => {
        console.log("Invoice collection changed successfully:", response);
        Swal.fire({
          icon: 'success',
          title: 'Faktura samling ændret',
          timer: 2000,
        })
      }).catch((error) => {
        console.error("Error changing invoice collection:", error);
        Swal.fire({
          icon: 'error',
          title: 'Fejl ved ændring af faktura samling',
          timer: 2000,
        });
      })
    }).catch((error) => {
      console.error("Error changing customer:", error);
      Swal.fire({
        icon: 'error',
        title: 'Fejl ved ændring af kunde',
        timer: 2000,
      });
    }).finally(() => {
      // Wait 2 seconds before reloading the page
      // This is to give the user time to see the success / error message
      setTimeout(() => {
        // Reload the page
        window.location.reload();
      }, 2000);
    })
  }
  async function chooseInvoiceCollection(order_id, new_customer_id) {
    // Select the new invoice collection
    await SessionUser.objects.collectedOrderInvoices.functions.showInvoiceCollectionPickerForm(new_customer_id, (invoice_collection_id) => {
      // Make sure it's valid
      if (!invoice_collection_id) {
        noInvoiceCollectionSelected();
        return;
      }
      // Change the invoice collection in the database.
      saveChanges(order_id, new_customer_id, invoice_collection_id);
    });
  }
  // Show the customer search modal
  // Define the new data.
  let new_customer_id = null;
  // Let the user select a customer
  showCustomerSearchModal(async (customer_number) => {
        // Store the new customer id
        new_customer_id = customer_number;
        // Make sure it's valid
        if (!new_customer_id) {
          noCustomerSelected();
          return;
        }
        // Show the invoice collection picker form
        console.log('Displaying invoice collection picker form for customer:', new_customer_id);
        await chooseInvoiceCollection(id, new_customer_id);
      }
  );

}

const showChangeOrderInvoiceCollectionForm = async (id) => {
  let customer_number = null;
  // Get the customer number from the order
  await SessionUser.objects.orders.functions.get_customer_id(id).then((response) => {
    customer_number = response;
    console.log("Customer number:", customer_number);
  }).catch((error) => {
    console.error(error);
  });
  if (!customer_number) {
    console.error("Ingen kunde fundet");
    return;
  }
  // Select the invoice collection
  await SessionUser.objects.collectedOrderInvoices.functions.showInvoiceCollectionPickerForm(
      customer_number,
      (invoice_collection_id) => {
        if (!invoice_collection_id) {
          Swal.fire({
            icon: 'error',
            title: 'Ingen faktura samling valgt',
            timer: 2000,
          });
          return;
        }
        // Handle the invoice collection selection here
        console.log("Selected invoice collection:", invoice_collection_id);
        console.log("Changing invoice collection for order:", id, " customer:", customer_number);
        console.log("New invoice collection:", invoice_collection_id);
        // Change the invoice collection
        SessionUser.objects.orders.set.invoice_collection_id(
            parseInt(id),
            parseInt(invoice_collection_id)
        )
            .then((response) => {
              console.log("Invoice collection changed successfully:", response);
              Swal.fire({
                icon: 'success',
                title: 'Faktura samling ændret',
                timer: 2000,
              })
            })
            .catch((error) => {
              console.error("Error changing invoice collection:", error);
              Swal.fire({
                icon: 'error',
                title: 'Fejl ved ændring af faktura samling',
                timer: 2000,
              });
            })
      }
  ).finally(() => {
    // Wait 2 seconds before reloading the page
    // This is to give the user time to see the success / error message
    setTimeout(() => {
      // Reload the page
      window.location.reload();
    }, 2000);
  })
}

    /**
     * The Orders object
     */
    export const Orders = {
      meta: {
        title: "Transaktioner",
        icon: "fas fa-list",
        description: "Oversigt over transaktioner",
        endpoint: "/orders",
        labels: {
          single: "transaktion",
          multiple: "transaktioner"
        }
      },
      columns: {
        id: {
          label: "ID",
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        customer_id: {
          label: "E-conomic kunde ID",
          type: "number",
          sortable: true,
          creation: {
            required: true
          }
        },
        cashier_id: {
          label: "Kasserer ID",
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        department_id: {
          label: "Afdeling ID",
          type: "number",
          sortable: true,
          creation: {
            required: true
          }
        },
        reference: {
          label: "Reference",
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        reg_1: {
          label: "Reg. 1",
          type: "string",
          sortable: true,
          creation: {
            required: true
          }
        },
        reg_2: {
          label: "Reg. 2",
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        reg_3: {
          label: "Reg. 3",
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        notes: {
          label: "Noter",
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        invoice_collection_id: {
          label: "Faktura samling ID",
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        wash_id: {
          label: "Vask ID",
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        created_at: {
          label: "Oprettet",
          type: "date",
          sortable: true,
          creation: {
            required: false
          }
        },
        completed_at: {
          label: "Fuldført",
          type: "date",
          sortable: true,
          creation: {
            required: false
          }
        },
      },
      add: async (customer_id, cashier_id, department_id, reference, reg_1, reg_2, reg_3, notes, invoice_collection_id) => {
        return ObjectsGlobal.add.object(
            Orders.meta.endpoint,
            {
              customer_id: parseInt(customer_id),
              cashier_id: parseInt(cashier_id),
              department_id: parseInt(department_id),
              reference: reference === null ? "" : reference,
              reg_1: reg_1,
              reg_2: reg_2,
              reg_3: reg_3,
              notes: notes === null ? "" : notes,
              invoice_collection_id: parseInt(invoice_collection_id),
            }
        );
      },
      set: {
        customer_id: async (id, customer_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "customer_id",
              parseInt(customer_id)
          )
        },
        cashier_id: async (id, cashier_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "cashier_id",
              parseInt(cashier_id)
          )
        },
        department_id: async (id, department_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "department_id",
              parseInt(department_id)
          )
        },
        reference: async (id, reference) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "reference",
              reference
          )
        },
        reg_1: async (id, reg_1) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "reg_1",
              reg_1
          )
        },
        reg_2: async (id, reg_2) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "reg_2",
              reg_2
          )
        },
        reg_3: async (id, reg_3) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "reg_3",
              reg_3
          )
        },
        notes: async (id, notes) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "notes",
              notes
          )
        },
        invoice_collection_id: async (id, invoice_collection_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "invoice_collection_id",
              parseInt(invoice_collection_id)
          )
        },
        wash_id: async (id, wash_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "wash_id",
              wash_id
          )
        },
        created_at: async (id, created_at) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "created_at",
              created_at
          )
        },
        completed_at: async (id, completed_at) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "completed_at",
              completed_at
          )
        },
      },
      get: {
        all: async () => {
          return ObjectsGlobal.get.objects(Orders.meta.endpoint);
        },
        single: async (id) => {
          return ObjectsGlobal.get.object(Orders.meta.endpoint, id);
        }
      },
      functions: {
        /**
         * Mark the order as completed
         * @param id
         * @returns {Promise<void>}
         */
        mark_as_completed: async (id) => {
          return SessionUser.request(
              Orders.meta.endpoint + "/mark_as_completed",
              "POST",
              {
                id: id
              },
          )
        },
        /**
         * Get the order department id
         * @param id
         */
        get_department_id: async (id) => {
          return SessionUser.request(
              '/order',
              'GET',
              {
                id: id
              }
          ).then((response) => {
            //console.log(response.data.data.department_id);
            return parseInt(response.data.data.department_id);
          }).catch((error) => {
            console.error(error);
          });
        },
        /**
         * Get the order customer number
         * @param id (order id)
         */
        get_customer_id: async (id) => {
          return SessionUser.request(
              '/order',
              'GET',
              {
                id: id
              }
          ).then((response) => {
            //console.log(response.data.data.customer_id);
            return parseInt(response.data.data.customer_id);
          }).catch((error) => {
            console.error(error);
          });
        },
        /**
         * Change the order customer
         * @param id (order id)
         * @param customer_id (e-conomic customer number)
         */
        change_customer: async (id, customer_id) => {
          return SessionUser.objects.orders.set.customer_id(id, customer_id);
        },
        /**
         * Show the change customer form
         * @param id (order id)
         */
        showChangeCustomerForm: showChangeOrderCustomerForm,
        /**
         * Show the change invoice collection form
         * @param id (order id)
         */
        showChangeInvoiceCollectionForm: showChangeOrderInvoiceCollectionForm,
      },
      /**
       * Show the create object form
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showCreateObjectForm: (onAfterSubmit = null) => {
        return ObjectsGlobal.showCreateObjectForm(Orders, 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(
            Orders,
            id,
            column,
            value,
            onAfterSubmit
        );
      }
    };
</script>