<script setup>
import { ref, defineProps } from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import UserOtherSpecialArrangement
  from "@/views/dashboards/superUserDashboard/user/displays/other/UserOtherSpecialArrangement.vue";
import UserOtherVaskeabonnement
  from "@/views/dashboards/superUserDashboard/user/displays/other/UserOtherVaskeabonnement.vue";
import Swal from "sweetalert2";
import OrderItemsTable from "@/components/displays/department/pos/order/orderItemsTable.vue";
import OrderContentTable from "@/components/displays/superuser/tables/OrderContentTable.vue";

const props = defineProps({
  orders: {
    type: Object,
    required: true,
    default: {},
  },
  options: {
    type: Object,
    required: true,
    default: {},
  },
  columns: {
    type: Object,
    required: true,
    default: {},
  },
  user_id: {
    type: Number,
    required: true,
    default: null,
  },
})

/** Rows */
const defaultColumnFunctions = {
    getRowValue: (order, row) => {
      return order[row.key];
    },
    getRowValueFormatted: (order, row) => {
      return order[row.key];
    },
    getRowValueColor: (order, row) => {
      return 'has-text-black';
    },
    buttonOnClick: (order, row) => {
      return null;
    },
    isButton: false,
};
const defaultColumn = {
  label: null,
  type: null,
  sortable: null,
  creation: {
    required: null
  },
  visible: true,
  buttonOnClick: null,
  ...defaultColumnFunctions
};
// Get the columns, and add additional columns, if they are defined in the props
const default_columns = SessionUser.objects.orders.columns;
const columns = {
  ...props.columns,
  ...default_columns,
};
// Parse the columns
const rows = ref((Object.keys(columns).map((key) => {
  return Object.assign({}, defaultColumn, {
    key: key,
    label: columns[key].label,
    type: columns[key].type,
    sortable: columns[key].sortable,
    creation: columns[key].creation,
    visible: columns[key].visible,
    ...defaultColumnFunctions,
    ...props.columns[key] || {}
  });
})));
/** Order */
const defaultOrder = {};

/** Options */
const defaultOptions = {};
const options = ref(Object.assign({}, defaultOptions, props.options));

/** Selected invoice collections */
const selectedInvoiceCollections = ref([]);
const isSelected = (object) => {
  return selectedInvoiceCollections.value.includes(object.invoice_collection_id);
}
const toggleSelected = (object) => {
  if (isSelected(object)) {
    selectedInvoiceCollections.value.splice(selectedInvoiceCollections.value.indexOf(object.invoice_collection_id), 1);
  } else {
    selectedInvoiceCollections.value.push(object.invoice_collection_id);
  }
}

/** Toggle all orders */
const toggleAllOrders = () => {
  // If any of the orders are selected, deselect all orders
  if (selectedInvoiceCollections.value.length > 0) {
    selectedInvoiceCollections.value = [];
  } else {
    // If no orders are selected, select all orders
    let orders = props.orders;
    for (let i = 0; i < orders.length; i++) {
      let order = orders[i];
      if (!isSelected(order)) {
        // To prevent duplicates, we check if the order is already selected
        selectedInvoiceCollections.value.push(order.invoice_collection_id);
      }
    }
  }
  console.log('Toggle all orders');
}

/** Is any order selected */
const isAnyOrderSelected = () => {
  return selectedInvoiceCollections.value.length > 0;
}

/** Invoice collections */
const onInvoiceCollections = async () => {
  // Check if any orders are selected
  if (selectedInvoiceCollections.value.length === 0) {
    return;
  }
  /** 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);
        }
    )
  }
  for (let i = 0; i < selectedInvoiceCollections.value.length; i++) {
    const selectedInvoiceCollectionId = selectedInvoiceCollections.value[i];
    // Check if the invoice collection is already booked
    const invoiceCollection = props.orders.find((order) => order.invoice_collection_id === selectedInvoiceCollectionId);
    console.log('Invoice collection', invoiceCollection);
    // Create the invoice
    console.log('Create invoice', selectedInvoiceCollectionId);

    await SessionUser.objects.collectedOrderInvoices.functions.economic.invoice(
        selectedInvoiceCollectionId,
        props.user_id
    ).then((response) => {
      console.log('Invoice collections created successfully', response);
    }).catch((error) => {
      console.log('Error creating invoice collections', error);
    });
  }
  // Show a success message
  Swal.fire({
    title: 'Fakturaer oprettet',
    text: 'Fakturaerne er oprettet i E-conomic',
    icon: 'success',
    showConfirmButton: false,
    timer: 2000
  }).then(() => {
    // Reload the page
    location.reload();
  });
}

const isOrderContentVisible = (order) => {
  return order.show_content !== undefined && order.show_content;
}

</script>

<template>
  <!-- User arrangements (if any) -->
  <div class="columns">
      <!-- Special Arrangement -->
      <UserOtherSpecialArrangement :user_id="user_id" :readOnly="true" :text-only="true"/>
      <!-- Vaskeabonnement -->
      <UserOtherVaskeabonnement :user_id="user_id" :readOnly="true" :text-only="true"/>
  </div>
  <!-- Actions -->
  <div class="buttons">
    <!-- Select all -->
    <button
        class="button is-small"
        @click="toggleAllOrders()"
    >
      {{ isAnyOrderSelected() ? 'Unselect all' : 'Select all' }}
    </button>
    <!-- Invoice -->
    <button
        class="button is-small"
        @click="onInvoiceCollections()"
        :disabled="!isAnyOrderSelected()"
    >
      Overfør til fakturering
    </button>
  </div>
  <!-- Table -->
  <table class="table is-fullwidth is-hoverable">
    <thead>
    <tr>
      <th class="selector is-clickable">
        <!-- Selector -->
        <input type="checkbox" @click="toggleAllOrders()" :checked="isAnyOrderSelected()" />
      </th>
      <template v-for="row in rows" :key="row.key">
        <th v-if="row.visible">
          {{ row.label }}
        </th>
      </template>
    </tr>
    </thead>
    <tbody>
    <template v-for="order in orders" :key="order.id">
      <tr>
        <td>
          <!-- Selector -->
          <input type="checkbox" @click="toggleSelected(order)" :checked="isSelected(order)" />
        </td>
        <template v-for="row in rows" :key="row.key">
          <td
              v-if="row.visible"
              :class="row.getRowValueColor(order, row)"
          >
            <template v-if="row.isButton">
              <button
                  @click="row.buttonOnClick(order, row)"
                  class="button is-small"
              >
                {{ row.getRowValueFormatted(order, row) }}
              </button>
            </template>
            <template v-else>
              {{ row.getRowValueFormatted(order, row) }}
            </template>
          </td>
        </template>
      </tr>
      <template v-if="isOrderContentVisible(order)">
        <tr>
          <td colspan="100%">
            <!-- Content -->
            <div class="content">
              <OrderContentTable
                :order-id="order.id"
                />
            </div>
          </td>
        </tr>
      </template>
    </template>
    </tbody>
  </table>
</template>

<style scoped>

</style>