<script setup>

import ActionSettingsWheelButton from "@/components/displays/buttons/ActionSettingsWheelButton.vue";

const props = defineProps({
  orders: {
    type: Object,
    required: true,
  },
  invoiceView: {
    type: Boolean,
    default: false,
  },
  allowSelectMultiple: {
    type: Boolean,
    default: false,
  },
  isCustomerView: {
    type: Boolean,
    default: false,
  }
});
import {ref, watch} from 'vue';
import { departments, getDepartments, isLoading, getDepartmentName} from "@/components/pagination/departmentTabs.vue";
import {showPopper, removePopperIfOpen, popperBox} from "@/components/displays/PopperDefault.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import {orderBy, orderDirection, setOrder, loadList} from "@/components/pagination/paginatedList.vue";
import ActionSettingsWheelItem from "@/components/displays/buttons/ActionSettingsWheelItem.vue";
import OrderContentTable from "@/components/displays/superuser/tables/OrderContentTable.vue";
import InvoiceMultipleCollectionsModal from "@/components/displays/modals/InvoiceMultipleCollectionsModal.vue";
import Swal from "sweetalert2";
import ColorIndicator from "@/components/displays/buttons/ColorIndicator.vue";


const redirectDepartmentOrderPage = (orderId, departmentId) => {
  // Send the user to the order page (In a new tab)
  // `/admin/${departmentId}/modules/pos/orders/${orderId}`
  window.open(`/admin/${departmentId}/modules/pos/orders/${orderId}`, '_blank');
};

const redirectSuperUserInvoiceCollectionPage = (invoiceCollectionId) => {
  // Send the user to the invoice collection page (In a new tab)
  window.open(`/superuser/invoices/${invoiceCollectionId}`, '_blank');
};

// Get the departments (If the departments are not already loaded)
if (departments.value.length === 0) {
  getDepartments();
}

const isOrderInvoicedWithEconomic = (order) => {
  return order.economic_invoice_module.invoice_id !== null || order.economic_invoice_module.invoice_draft_id !== null;
};

const isOrderEconomicInvoiceBooked = (order) => {
  return order.economic_invoice_module.invoice_id !== null;
};

const isOrderInvoicedWithStripe = (order) => {
  return order.stripe_invoice_module !== undefined;
};

const isOrderInvoiced = (order) => {
  return isOrderInvoicedWithEconomic(order) || isOrderInvoicedWithStripe(order);
};

const doesOrderHaveInvoiceCollection = (order) => {
  return order.invoice_collection !== undefined && order.invoice_collection !== null;
};

const isOrderInvoiceCollectionClosed = (order) => {
  return order.invoice_collection.closed_at !== null;
};

const isOrderInvoiceCollectionBooked = (order) => {
  return order.invoice_collection.booked_invoice_id !== null;
};

const isOrderStripeInvoicePaid = (order) => {
  if (order.stripe_invoice_module) {
    return order.stripe_invoice_module.paid;
  }
  return false;
};

const doesOrderHaveErrorMessage = (order) => {
  return order.error_message !== null && order.error_message !== undefined;
};

const getOrderInvoiceStatusBarColor = (order) => {
  if (order.economic_invoice_module) {
    // Check the invoice status
    var color_class = 'has-text-danger';
    if (isOrderInvoicedWithStripe(order)) {
      isOrderStripeInvoicePaid(order)
          ? color_class = 'has-text-success'
          : color_class = 'has-text-warning';
    }
    if (isOrderInvoicedWithEconomic(order)) {
      isOrderEconomicInvoiceBooked(order)
          ? color_class = 'has-text-success'
          : color_class = 'has-text-warning';
    }
    if (doesOrderHaveInvoiceCollection(order)) {
      color_class = 'has-text-grey';
      // Check if the invoice collection is closed
      if (isOrderInvoiceCollectionClosed(order)) {
        color_class = 'has-text-warning';
        // Check if the invoice collection is booked
        if (isOrderInvoiceCollectionBooked(order)) {
          color_class = 'has-text-success';
        }
      }
    }
    if (doesOrderHaveErrorMessage(order)) {
      color_class = 'has-text-danger';
    }
    // Return the color class
    return color_class;
  }
  return '';
};

const getOrderInvoiceStatusContent = (order) => {
  const content = [];
  if (isOrderInvoiced(order)) {
    // If the order is invoiced with e-conomic, show the invoice id
    if (isOrderInvoicedWithEconomic(order)) {
      isOrderEconomicInvoiceBooked(order)
          ? content.push('Bogført i e-conomic')
          : content.push('Gemt som kladde i e-conomic');
      isOrderEconomicInvoiceBooked(order)
          ? content.push('Faktura ID: <strong>' + order.economic_invoice_module.invoice_id + '</strong>')
          : content.push('Faktura Kladde ID: <strong>' + order.economic_invoice_module.invoice_draft_id + '</strong>');
    }
    // If the order is invoiced with stripe, show the invoice id
    if (isOrderInvoicedWithStripe(order)) {
      isOrderStripeInvoicePaid(order)
          ? content.push('Fakturaen er <strong>betalt</strong>')
          : content.push('Fakturaen er <strong>ikke betalt</strong>');
      content.push('Faktura ID: <strong>' + order.stripe_invoice_module.id + '</strong>');
    }
    content.push(''); // Add a line break
    isOrderInvoicedWithEconomic(order)
        ? content.push('<span class="has-text-grey">Faktureret med e-conomic</span>')
        : content.push('<span class="has-text-grey">Faktureret med stripe</span>');
  } else {
    // Check if the order has an invoice collection
    if (doesOrderHaveInvoiceCollection(order)) {
      // Check if the invoice collection is closed
      if (isOrderInvoiceCollectionClosed(order)) {
        content.push('Faktura samlingen er <strong>lukket</strong>');
        // Check if the invoice collection is booked
        if (isOrderInvoiceCollectionBooked(order)) {
          content.push('Faktura samlingen er <strong>bogført</strong>');
        }
      }
      content.push(''); // Add a line break
      content.push('Faktura samling ID: <strong>' + order.invoice_collection.id + '</strong>');
      // Add the Error message if it exists
      if (doesOrderHaveErrorMessage(order)) {
        content.push('Fejl: <strong class="has-text-danger">' + order.error_message + '</strong>');
      }
    } else {
      content.push(''); // Add a line break
      content.push('<strong class="has-text-grey">Transaktionen er ikke faktureret</strong>');
    }
  }
  // Return the list of content as a string, with line breaks between each item
  return content.join('<br>');
};

const getOrderInvoiceStatusTitle = (order) => {
  return isOrderInvoiced(order) ? 'Faktura status' : 'Transaktion status';
};

const clickUser = (customer_id) => {
  if (!SessionUser.canAccessSuperUser()) {
    return;
  }
  // Send the user to the user page
  SessionUser.adminUser.customers.fromCustomerNumber.getUserId(customer_id).then(response => window.open('/superuser/users/' + response.data.data.user_id, '_blank'));
};

const isColumnCurrentlyBeingSortedBy = (column) => {
  // Check if the column is currently being sorted by
  return orderBy.value === column;
};

const isCurrentSortDirectionAscending = () => {
  // Check if the current sort direction is ascending
  return orderDirection.value === 'asc';
};

const isCurrentSortDirectionDescending = () => {
  // Check if the current sort direction is descending
  return orderDirection.value === 'desc';
};

const onTableHeaderClick = (column) => {
  // Check if the column is already sorted
  if (orderBy.value === column) {
    // If the column is already sorted, toggle the direction
    const direction = orderDirection.value === 'asc' ? 'desc' : 'asc';
    setOrder(
        column,
        direction
    );
  } else {
    // If the column is not sorted, set the order to the new column and default to ascending
    const direction = 'asc';
    setOrder(
        column,
        direction
    );
  }
  // Load the list
  loadList();
};

const tableHeaders = ref([
  {
    name: 'id',
    title: 'Id',
    sortable: true,
  },
    ...(props.isCustomerView) ? [] : [{
    name: 'customer_id',
    title: 'Kunde',
    sortable: true,
  }],
    ...(props.isCustomerView) ? [] : [{
    name: 'cashier_id',
    title: 'Kassør',
    sortable: true,
  }],
  {
    name: 'department_id',
    title: 'Afdeling',
    sortable: true,
  },
  {
    name: 'reg_1',
    title: 'Reg. 1',
    sortable: true,
  },
  {
    name: 'reg_2',
    title: 'Reg. 2',
    sortable: true,
  },
  {
    name: 'reg_3',
    title: 'Reg. 3',
    sortable: true,
  },
  {
    name: 'reference',
    title: 'Reference',
    sortable: true,
  },
  {
    name: 'notes',
    title: 'Noter',
    sortable: true,
  },
  {
    name: 'created_at',
    title: 'Dato',
    sortable: true,
  },
  {
    name: 'total_net_amount',
    title: 'Total',
    sortable: false,
  },
  {
    name: 'completed_at',
    title: 'Gennemført',
    sortable: true,
  },
  {
    name: 'actions',
    title: 'Actions',
    sortable: false,
  },
]);

const active_dropdown_object_ids = ref([]);
const toggleDropdown = (object) => {
  // Check if the object is already in the active dropdown list
  if (active_dropdown_object_ids.value.includes(object.id)) {
    // If it is, remove it from the list
    active_dropdown_object_ids.value = active_dropdown_object_ids.value.filter(id => id !== object.id);
  } else {
    // If it is not, add it to the list
    active_dropdown_object_ids.value.push(object.id);
  }
};
const isDropdownActive = (object) => {
  // Check if the object is in the active dropdown list
  return active_dropdown_object_ids.value.includes(object.id);
};

/**
 * Invoice collection selection
 */
const selectedInvoiceCollections = ref([]);
const toggleInvoiceCollectionSelection = (invoiceCollectionId) => {
  // Check if the invoice collection is already selected
  if (selectedInvoiceCollections.value.includes(invoiceCollectionId)) {
    // If it is, remove it from the list
    selectedInvoiceCollections.value = selectedInvoiceCollections.value.filter(id => id !== invoiceCollectionId);
  } else {
    // If it is not, add it to the list
    selectedInvoiceCollections.value.push(invoiceCollectionId);
  }
};

const isInvoiceCollectionSelected = (invoiceCollectionId) => {
  // Check if the invoice collection is in the selected list
  return selectedInvoiceCollections.value.includes(invoiceCollectionId);
};
const isInvoiceCollectionSelectedAll = () => {
  // Check if all invoice collections are selected
  return selectedInvoiceCollections.value.length === getUniqueInvoiceCollections().length;
};
const selectAllInvoiceCollections = () => {
  // Check if all invoice collections are selected
  if (isInvoiceCollectionSelectedAll()) {
    // If they are, deselect all
    selectedInvoiceCollections.value = [];
  } else {
    // If they are not, select all
    selectedInvoiceCollections.value = getUniqueInvoiceCollections();
  }
};

const getUniqueInvoiceCollections = () => {
  // Get a list of unique invoice collections from the orders
  return [...new Set(props.orders.map(order => order.invoice_collection_id))];
};

const invoiceCollectionQueueInProgress = ref([]);
const invoiceCollectionQueueFailed = ref([]);
const invoiceCollectionQueueSuccess = ref([]);
const invoiceCollectionQueue = ref([]);
const invoiceCollectionMaxConnections = 2;
const isInvoiceMultipleCollectionsModalOpen = ref(false);

const invoiceSelectedCollections = () => {
  // Open the invoice multiple collections modal
  isInvoiceMultipleCollectionsModalOpen.value = true;
  // Check if any invoice collections are selected
  if (selectedInvoiceCollections.value.length > 0) {
    // If they are, show a message
    console.log('Selected invoice collections: ' + selectedInvoiceCollections.value);
    for (const invoiceCollectionId of selectedInvoiceCollections.value) {
      // Log the invoice collection id
      console.log('Invoice collection id: ', invoiceCollectionId);
      // Add the invoice collection to the queue
      addInvoiceCollectionToQueue(invoiceCollectionId);
    }
    // Process the invoice collection queue
    processInvoiceCollectionQueue();
  } else {
    // If they are not, show a message
    console.log('No invoice collections selected');
  }
};

const addInvoiceCollectionToQueue = (invoiceCollectionId) => {
  // Check if the invoice collection is already in the queue
  if (invoiceCollectionQueue.value.includes(invoiceCollectionId)) {
    // If it is, remove it from the queue
    invoiceCollectionQueue.value = invoiceCollectionQueue.value.filter(id => id !== invoiceCollectionId);
  } else {
    // If it is not, add it to the queue
    invoiceCollectionQueue.value.push(invoiceCollectionId);
  }
};

const processInvoiceCollectionQueue = () => {
  // Check if the queue is empty
  if (invoiceCollectionQueue.value.length === 0) {
    // If it is, show a message
    console.log('Invoice collection queue is empty');
    return;
  }
  // Check if the max connections are reached
  if (invoiceCollectionQueueInProgress.value.length >= invoiceCollectionMaxConnections) {
    // If they are, show a message
    console.log('Max connections reached');
    return;
  }
  while (invoiceCollectionQueueInProgress.value.length < invoiceCollectionMaxConnections && invoiceCollectionQueue.value.length > 0) {
    // Process the next invoice collection
    processNextInvoiceCollection();
  }
};

const processNextInvoiceCollection = () => {
  // Check if the queue is empty
  if (invoiceCollectionQueue.value.length === 0) {
    // If it is, show a message
    console.log('Invoice collection queue is empty');
    return;
  }
  // Get the next invoice collection from the queue
  const invoiceCollectionId = invoiceCollectionQueue.value.shift();
  // Process the invoice collection
  processInvoiceCollection(invoiceCollectionId);
};

const getFirstInvoiceWithCollectionId = (invoiceCollectionId) => {
  // Get the first invoice with the given collection id
  return props.orders.find(order => order.invoice_collection_id === invoiceCollectionId);
};

const processInvoiceCollection = (invoiceCollectionId) => {
  // Check if the invoice collection is already in progress
  if (invoiceCollectionQueueInProgress.value.includes(invoiceCollectionId)) {
    // If it is, remove it from the in progress list
    invoiceCollectionQueueInProgress.value = invoiceCollectionQueueInProgress.value.filter(id => id !== invoiceCollectionId);
  } else {
    // If it is not, add it to the in progress list
    invoiceCollectionQueueInProgress.value.push(invoiceCollectionId);
  }
  // Process the invoice collection
  console.log('Processing invoice collection: ' + invoiceCollectionId);
  // Send the invoice collection request to the server
  // Send the request
  SessionUser.request(
      '/collected-invoices/economic',
      'POST',
      {
        id: parseInt(invoiceCollectionId)
      }
  ).then((response) => {
        if (response.data && response.data.data && response.data.success) {
          // If the request was successful, add the invoice collection to the success list
          console.log('Invoice collection processed successfully: ' + invoiceCollectionId, response);
          addInvoiceCollectionToSuccess(invoiceCollectionId);
          addCollectionQueueLog(
              true, // Success state
              invoiceCollectionId, // Invoice collection id
              'Invoice collection processed successfully', // Error message
          );
        } else {
          // If the request failed, add the invoice collection to the failed list
          console.log('Invoice collection processing failed: ' + invoiceCollectionId, response);
          invoiceCollectionQueueFailed.value.push(invoiceCollectionId);
          addCollectionQueueLog(
              false, // Success state
              invoiceCollectionId, // Invoice collection id
              'Unknown error', // Error message
          );
        }
      }
  ).catch((error) => {
    // If the request failed, add the invoice collection to the failed list
    console.log('Invoice collection processing failed 2: ' + invoiceCollectionId, error);
    invoiceCollectionQueueFailed.value.push(invoiceCollectionId);
    let errorMessage = error.response.data.data.message;
    addCollectionQueueLog(
        false, // Success state
        invoiceCollectionId, // Invoice collection id
        errorMessage, // Error message
    );
  }).finally(() => {
    // Remove the invoice collection from the in progress list
    invoiceCollectionQueueInProgress.value = invoiceCollectionQueueInProgress.value.filter(id => id !== invoiceCollectionId);
    // Process the next invoice collection in the queue
    processInvoiceCollectionQueue();
  });
};

const collectionQueueLog = ref([]);
const addCollectionQueueLog = (success, invoiceCollectionId, errorMessage) => {
  // Add the log to the collection queue log
  collectionQueueLog.value.push({
    success: success,
    invoiceCollectionId: invoiceCollectionId,
    errorMessage: errorMessage
  });
};

const addInvoiceCollectionToSuccess = (invoiceCollectionId) => {
  // Check if the invoice collection is already in the success list
  if (invoiceCollectionQueueSuccess.value.includes(invoiceCollectionId)) {
    // If it is, remove it from the success list
    invoiceCollectionQueueSuccess.value = invoiceCollectionQueueSuccess.value.filter(id => id !== invoiceCollectionId);
  } else {
    // If it is not, add it to the success list
    invoiceCollectionQueueSuccess.value.push(invoiceCollectionId);
  }
};

const confirmCloseModal = () => {
  Swal.fire(
      {
        title: 'Er du sikker på at du vil lukke vinduet?',
        text: "Du vil ikke kunne få den visualiseret igen!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ja, luk vinduet!'
      }).then((result) => {
    if (result.isConfirmed) {
      isInvoiceMultipleCollectionsModalOpen.value = false;
    }
  });
};

</script>

<template>
  <table class="table is-fullwidth is-hoverable">
    <thead>
    <tr v-if="props.invoiceView && props.allowSelectMultiple">
      <td colspan="100%">
        <div class="buttons">
          <button
              class="button is-small"
              @click="invoiceSelectedCollections()"
              >
            {{SessionUser.objects.global.language.invoice}} {{SessionUser.objects.global.language.selected_multiple}} ({{selectedInvoiceCollections.length}})
          </button>
          <button
              class="button is-small"
              @click="selectAllInvoiceCollections()"
              :class="{
                  'is-light': !isInvoiceCollectionSelectedAll(),
                  'is-dark': isInvoiceCollectionSelectedAll()
              }"
          >
            {{ isInvoiceCollectionSelectedAll() ? SessionUser.objects.global.language.unselect : SessionUser.objects.global.language.select }} {{ SessionUser.objects.global.language.all.toLowerCase() }}
          </button>
        </div>
      </td>
    </tr>
    <tr>
      <th class="is-narrow" v-if="props.invoiceView && props.allowSelectMultiple"></th>
      <th class="is-narrow" v-if="props.invoiceView"></th>
      <template v-for="tableHeaders in tableHeaders" :key="tableHeaders">
        <th
            v-if="tableHeaders.sortable"
            :class="{
                'is-clickable': tableHeaders.sortable,
                'has-text-centered': tableHeaders.name === 'id'
            }"
            @click="onTableHeaderClick(tableHeaders.name)"
        >
          <span class="is-flex-wrap-nowrap">
            <span class="has-text-weight-bold">{{ tableHeaders.title }}</span>
            <span
                v-if="isColumnCurrentlyBeingSortedBy(tableHeaders.name)"
                :class="{
                    'fas fa-sort-up': isCurrentSortDirectionAscending(),
                    'fas fa-sort-down': isCurrentSortDirectionDescending()
                }"
                class="icon is-small"
            />
          </span>
        </th>
        <th
            v-else
            :class="{
                'has-text-centered': tableHeaders.name === 'id'
            }"
        >
          <span class="is-flex-wrap-nowrap">
            <span class="has-text-weight-bold">{{ tableHeaders.title }}</span>
          </span>
        </th>
      </template>
    </tr>
    </thead>
    <tbody>
    <template v-for="order in orders" :key="order.id">
      <tr>
        <template v-if="props.invoiceView && props.allowSelectMultiple">
          <td class="is-narrow">
            <button
                class="button is-small"
                @click="toggleInvoiceCollectionSelection(order.invoice_collection_id)"
                :class="{
                    'is-light': !isInvoiceCollectionSelected(parseInt(order.invoice_collection_id)),
                    'is-dark': isInvoiceCollectionSelected(parseInt(order.invoice_collection_id))
                }"
                >
              {{ isInvoiceCollectionSelected(parseInt(order.invoice_collection_id)) ? SessionUser.objects.global.language.unselect : SessionUser.objects.global.language.select }}
            </button>
          </td>
        </template>
        <template v-if="props.invoiceView">
          <td class="is-narrow">
            <button
                class="button is-small"
                @click="toggleDropdown(order)"
            >
              <span
                  class="icon"
                  :class="isDropdownActive(order) ? 'has-text-link' : ''"
                  :style="isDropdownActive(order) ? 'transform: rotate(90deg);' : ''"
              >
                <!-- Dropdown icon -->
                <i class="fas fa-angle-right"></i>
              </span>
            </button>
          </td>
        </template>
        <td>
          <ColorIndicator
              v-bind:color_class="getOrderInvoiceStatusBarColor(order)"
              v-bind:is_narrow="true"
              v-bind:label="{
                text: order.id,
                classes: [],
                max_length: 7,
              }"
              v-bind:visibility="{
                icon: true,
                dropdown: true,
              }"
              v-bind:dropdown_content="{
                title: null,
                buttons_title: null,
                content: [
                    // Transaction
                    {
                      text: SessionUser.functions.ucFirst(SessionUser.objects.orders.meta.labels.single),
                      action: () => {
                        redirectDepartmentOrderPage(order.id, order.department_id);
                      },
                      ...(SessionUser.canAccessSuperUser() ? {} : { disabled: true }),
                      button_classes: ['no-underline-text', 'is-text'],
                      button: true,
                      button_text: order.id,
                      v_centered: true,
                    },
                    // Invoice collection
                    {
                      text: SessionUser.objects.global.language.invoice + ' ' + SessionUser.objects.global.language.collection.toLowerCase(),
                      action: () => {
                        redirectSuperUserInvoiceCollectionPage(order.invoice_collection_id);
                      },
                      ...(SessionUser.canAccessSuperUser() ? {} : { disabled: true }),
                      button_classes: ['no-underline-text', 'is-text'],
                      button: true,
                      button_text: order.invoice_collection_id,
                      v_centered: true,
                    },
                    // Completed status
                    {
                      text: SessionUser.objects.orders.columns.completed_at.label,
                      action: () => {
                        redirectDepartmentOrderPage(order.id, order.department_id);
                      },
                      ...(SessionUser.canAccessSuperUser() ? {} : { disabled: true }),
                      button_classes: ['no-underline-text', 'is-text', ...(order.completed_at !== null ? [] : ['has-text-warning'])],
                      button: true,
                      button_text: (order.completed_at !== null ? SessionUser.objects.global.language.yes : SessionUser.objects.global.language.no),
                      v_centered: true,
                    },
                ],
                buttons: [],
              }"
          />
        </td>
        <td v-if="!props.isCustomerView">
          <ColorIndicator
              v-bind:label="{
                text: order.customer_name,
                classes: [],
                max_length: 7,
              }"
              v-bind:visibility="{
                icon: false,
                dropdown: true
              }"
              v-bind:dropdown_content="{
                title: null,
                buttons_title: null,
                content: [
                    {
                      text: order.customer_name,
                      action: () => {
                        clickUser(order.customer_id);
                      },
                      ...(SessionUser.canAccessSuperUser() ? {} : { disabled: true }),
                      button: true,
                      button_text: 'Vis kunde',
                    }
                ],
                buttons: [],
              }"
          />
        </td>
        <!--
        <td>
          <span
              @mouseover="showPopper(
                              popperBox(
                                  'Customer ID',
                                  order.customer_id,
                                  ),
                                  $event.target
                              )"
              @mouseleave="removePopperIfOpen()"
              @click="clickUser(order.customer_id)"
              :class="{ 'is-clickable': SessionUser.canAccessSuperUser() }"
              >
        {{ order.customer_name }}
      </span>
        </td> -->
        <td v-if="!props.isCustomerView">{{ order.cashier_id }}</td>
        <td>{{ getDepartmentName(order.department_id) }}</td>
        <td>
          <ColorIndicator
            v-bind:label="{
              text: order.reg_1,
              classes: [],
              max_length: 7,
            }"
            v-bind:visibility="{
              icon: false,
              dropdown: (order.reg_1.length > 7),
            }"
            v-bind:dropdown_content="{
              title: null,
              buttons_title: null,
              content: [
                  {
                    text: order.reg_1,
                    action: () => {},
                  }
              ],
              buttons: [],
            }"
          />
        </td>
        <td>
          <ColorIndicator
              v-show="order.reg_2 !== ''"
              v-bind:label="{
                text: order.reg_2,
                classes: [],
                max_length: 7,
              }"
              v-bind:visibility="{
                icon: false,
                dropdown: (order.reg_2.length > 7),
              }"
              v-bind:dropdown_content="{
                title: null,
                buttons_title: null,
                content: [
                    {
                      text: order.reg_2,
                      action: () => {},
                    }
                ],
                buttons: [],
              }"
          />
        </td>
        <td>
          <ColorIndicator
              v-show="order.reg_3 !== ''"
              v-bind:label="{
                text: order.reg_3,
                classes: [],
                max_length: 7,
              }"
              v-bind:visibility="{
                icon: false,
                dropdown: (order.reg_3.length > 7),
              }"
              v-bind:dropdown_content="{
                title: null,
                buttons_title: null,
                content: [
                    {
                      text: order.reg_3,
                      action: () => {},
                    }
                ],
                buttons: [],
              }"
          />
        </td>
        <td>
          <ColorIndicator
              v-show="order.reference !== ''"
              v-bind:label="{
                text: order.reference,
                classes: [],
                max_length: 7,
              }"
              v-bind:visibility="{
                icon: false,
                dropdown: (order.reference.length > 7),
              }"
              v-bind:dropdown_content="{
                title: null,
                buttons_title: null,
                content: [
                    {
                      text: order.reference,
                      action: () => {},
                    }
                ],
                buttons: [],
              }"
          />
        </td>
        <td>
          <ColorIndicator
              v-show="order.notes !== ''"
              v-bind:label="{
                text: order.notes,
                classes: [],
                max_length: 7,
              }"
              v-bind:visibility="{
                icon: false,
                dropdown: (order.notes.length > 7),
              }"
              v-bind:dropdown_content="{
                title: null,
                buttons_title: null,
                content: [
                    {
                      text: order.notes,
                      action: () => {},
                    }
                ],
                buttons: [],
              }"
          />
        </td>
        <td>{{ order.created_at }}</td>
        <td>{{ SessionUser.functions.currency.toLocal(order.total_net_amount) }}</td>
        <td>{{ order.completed_at }}</td>
          <td>
            <!-- Dropdown -->
            <ActionSettingsWheelButton
            v-bind:user_id="order.user_id"
            v-bind:order_id="order.id"
            v-bind:invoice_collection_id="order.invoice_collection_id"
            v-bind:reg_1="order.reg_1"
            >
              <template v-slot:actions>
                <!--
                Go to the order page, in a new tab
                <action-settings-wheel-item
                  label="Se transaktion i ny fane"
                  icon="fas fa-external-link-alt"
                  :click-action="() => redirectDepartmentOrderPage(order.id, order.department_id)"
                  :disabled="false"
                  />
                Show the invoice collection, in a new tab
                <action-settings-wheel-item
                  label="Vis faktura samling i ny fane"
                  icon="fas fa-file-invoice-dollar"
                  :click-action="() => redirectSuperUserInvoiceCollectionPage(order.invoice_collection.id)"
                  :disabled="!doesOrderHaveInvoiceCollection(order)"
                  />
                -->
              </template>
            </ActionSettingsWheelButton>
          </td>
      </tr>
      <!-- Dropdown content (if the invoice view is enabled,and the dropdown is active) -->
      <tr v-if="props.invoiceView && isDropdownActive(order)">
        <!-- Order line items -->
        <td colspan="100%">
          <!-- Content -->
          <div class="content">
            <OrderContentTable
                :order-id="order.id"
            />
          </div>
        </td>
      </tr>
    </template>
    </tbody>
    <tfoot>
    <tr>
      <td colspan="100%">Viser {{ orders.length }} transaktioner</td>
    </tr>
    </tfoot>
  </table>
  <InvoiceMultipleCollectionsModal
      v-if="isInvoiceMultipleCollectionsModalOpen"
      v-bind:in-progress="invoiceCollectionQueueInProgress"
      v-bind:failed="invoiceCollectionQueueFailed"
      v-bind:succeeded="invoiceCollectionQueueSuccess"
      v-bind:queued="invoiceCollectionQueue"
      v-bind:log="collectionQueueLog"
      @closeModal="confirmCloseModal()"
      />
</template>

<style scoped>
.status-bar-table-header {
  max-width: 5px;
  padding-left: 0;
  padding-right: 0;
}
.status-bar-table-row {
  border-radius: 5px;
  width: 5px;
  padding-left: 0;
  padding-right: 0;

}
.status-bar.has-text-danger {
  border-color: #ff3860;
}
.status-bar.has-text-warning {
  border-color: #ffdd57;
}
.status-bar.has-text-success {
  border-color: #48c774;
}
</style>