<script setup>
import EditableTableColumn from "@/components/displays/buttons/EditableTableColumn.vue";
import {getCustomerName} from "@/components/shop/POSDepartmentProcess.vue";
import {getDepartmentName, getDepartments} from "@/components/pagination/departmentTabs.vue";

const props = defineProps({
  objects: {
    type: Object,
    required: true
  },
  show_closed_invoices: {
    type: Boolean,
    required: false,
    default: false
  },
});
import {ref, watch} from 'vue';
import { loadList } from "@/components/pagination/paginatedList.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import ActionSettingsWheelButton from "@/components/displays/buttons/ActionSettingsWheelButton.vue";
import ActionSettingsWheelItem from "@/components/displays/buttons/ActionSettingsWheelItem.vue";
import OrdersTable from "@/components/displays/department/pos/orders/ordersTable.vue";
import UserOtherSpecialArrangement
  from "@/views/dashboards/superUserDashboard/user/displays/other/UserOtherSpecialArrangement.vue";
import InvoiceOrderTable from "@/components/displays/superuser/tables/InvoiceOrderTable.vue";

const activeDropdowns = ref([]);
const invoiceTotal_default = {
  loading: true,
  total_net_amount: {
    open_invoices: 0,
    closed_invoices: 0,
  },
};

const customerTotals = ref({});

const redirect = (path) => {
  // Open the url in a new tab
  window.open(path, '_blank');
}

const isDropdownActive = (object) => {
  return activeDropdowns.value.includes(object.customer_number);
}

const toggleDropdown = (object) => {
  if (isDropdownActive(object)) {
    activeDropdowns.value.splice(activeDropdowns.value.indexOf(object.customer_number), 1);
  } else {
    activeDropdowns.value.push(object.customer_number);
  }
}

const getInvoiceTotals = () => {
  console.log('getInvoiceTotals');
  let customers = props.objects;
  let customer_numbers = [];
  for (let i = 0; i < customers.length; i++) {
    let customer = customers[i];
    customer_numbers.push(customer.customer_number);
  }
  console.log('customer_numbers', customer_numbers);
  // Divide the customer numbers into chunks of 15 to avoid exceeding the request limit
  let chunks = [];
  for (let i = 0; i < customer_numbers.length; i += 15) {
    chunks.push(customer_numbers.slice(i, i + 15));
  }
  console.log('chunks', chunks);
  // For each chunk, get the invoice totals
  for (let i = 0; i < chunks.length; i++) {
    let chunk = chunks[i];
    console.log('chunk', chunk);
    // Get the invoice totals for each chunk
    getInvoiceTotalsForChunk(chunk);
  }
}
const getInvoiceTotalsForChunk = (customer_numbers) => {
  // Get all invoices for the customers (collectively, to avoid multiple requests)
  SessionUser.request(
      '/collected-invoices/customers/invoiceTotals',
      'POST',
      {
        customer_numbers: customer_numbers,
      }
  ).then((response) => {
    console.log('response', response);
    let data = response.data.data;
    addChunkToCustomerTotals(data);
  }).catch((error) => {
    console.error(error);
  });
}

const addChunkToCustomerTotals = (data) => {
  console.log('addChunkToCustomerTotals', data);
  // Merge the data into the customerTotals object
  customerTotals.value = Object.assign(customerTotals.value, data);
  // Set the loading state to false for each customer
  for (let i = 0; i < Object.keys(data).length; i++) {
    let customer_number = Object.keys(data)[i];
    if (customerTotals.value[customer_number] !== undefined) {
      customerTotals.value[customer_number].loading = false;
    }
  }
  console.log('customerTotals', customerTotals.value);
}

watch(() => props.objects, (newValue) => {
  console.log('props.objects', newValue);
  getInvoiceTotals();
}, { immediate: true });


// Get the invoice totals for each customer
getInvoiceTotals();

const getCustomerTotals = (customer_number) => {
  if (customerTotals.value[customer_number] === undefined) {
    return invoiceTotal_default;
  }
  return customerTotals.value[customer_number];
}

const isCustomerTotalsLoaded = (customer_number) => {
  if (customerTotals.value[customer_number] === undefined) {
    return false;
  }
  return customerTotals.value[customer_number].loading === false;
}

const getCustomerTotalNet = (object) => {
  let customer_number = object.customer_number;
  let invoiceTotals = getCustomerTotals(customer_number);
  console.log('invoiceTotals', invoiceTotals);
  if (invoiceTotals.loading) {
    return 0;
  }
  if (props.show_closed_invoices) {
    return invoiceTotals.total_net_amount.closed_invoices;
  }
  // If the closed invoices are not shown, return the total net amount of the open invoices
  return invoiceTotals.total_net_amount.open_invoices;
}

getDepartments();

const getOrders = (object) => {
  let customer_number = object.customer_number;
  if (!isCustomerTotalsLoaded(customer_number)) {
    return [];
  }
  let open_invoices = customerTotals.value[customer_number].invoices.open_invoices
  let closed_invoices = customerTotals.value[customer_number].invoices.closed_invoices
  let invoices = [
    ...open_invoices,
    ...(props.show_closed_invoices ? closed_invoices : [])
  ];
  let orders = [];
  // For each invoice, get the orders
  for (let i = 0; i < invoices.length; i++) {
    let invoice = invoices[i];
    // Get the orders for the invoice
    let invoice_orders = invoice.orders;
    // For each order, add the customer_number to the order
    for (let j = 0; j < invoice_orders.length; j++) {
      let order = invoice_orders[j];
      order.customer_number = customer_number;
      order.closed_at = invoice.closed_at ? invoice.closed_at : null;
      order.external_id = invoice.external_id ? invoice.external_id : null;
      orders.push(order);
    }
  }
  // Sort the orders by external_id (The one that is null, should be first)
  orders.sort((a, b) => {
    if (a.external_id === null && b.external_id !== null) {
      return -1;
    } else if (a.external_id !== null && b.external_id === null) {
      return 1;
    }
    return 0;
  });
  console.log('orders', orders);
  return orders;
}

const getCustomerUserId = (object) => {
  let customer_number = object.customer_number;
  if (!isCustomerTotalsLoaded(customer_number)) {
    return null;
  }
  // Return the user_id of the customer
  return customerTotals.value[customer_number].user_id;
}

</script>

<template>
  {{ activeDropdowns }}
    <table class="table is-fullwidth is-hoverable is-striped">
      <thead>
      <tr>
        <th class="is-narrow"><!-- Dropdown --></th>
        <th>{{ SessionUser.objects.global.language.customer_name }}</th>
        <th class="is-narrow">{{ SessionUser.objects.collectedOrderInvoices.columns.customer_number.label }}</th>
        <!--<th class="is-narrow">Åbne fakturaer</th> -->
        <!--<th class="is-narrow">Lukkede fakturaer</th> -->
        <th>{{ SessionUser.objects.global.language.total}}</th>
        <th><!-- Actions --></th>
      </tr>
      </thead>
      <tbody>
      <template v-for="object in objects" :key="object.id">
        <tr>
        <td>
          <button
              class="button is-small"
              @click="toggleDropdown(object)"
          >
            <span
                class="icon"
                :class="isDropdownActive(object) ? 'has-text-link' : ''"
                :style="isDropdownActive(object) ? 'transform: rotate(90deg);' : ''"
            >
              <!-- Dropdown icon -->
              <i class="fas fa-angle-right"></i>
            </span>
          </button>
        </td>
        <!-- Customer name -->
        <EditableTableColumn
            :object="object"
            :loadList="loadList"
            column="customer_name"
            :virtual-column="true"
            :parse-function="(value) => value.display_name"
            :style="isDropdownActive(object) ? 'font-weight: bold;' : ''"
        />
        <!-- Customer number -->
        <EditableTableColumn
            :object="object"
            :loadList="loadList"
            column="customer_number"
        />
        <!-- Active invoice count
          <EditableTableColumn :object="object" :loadList="loadList" column="active_invoices"/>
          -->
        <!-- Closed invoice count
          <EditableTableColumn
              :object="object"
              :loadList="loadList"
              column="closed_invoices"
          />
          -->
        <!-- Status -->
        <!-- Total net amount -->
        <td v-if="isCustomerTotalsLoaded(object.customer_number)">
          {{ SessionUser.functions.currency.toLocal(getCustomerTotalNet(object) ) }}
        </td>
        <td v-else>
          Loading...
        </td>
        <!-- Actions -->
        <td>
          <ActionSettingsWheelButton>
            <template #actions>
              <ActionSettingsWheelItem
                icon="fas fa-eye"
                @click="redirect('/superuser/invoices/' + object.id)"
                label="Vis"
              />
            </template>
          </ActionSettingsWheelButton>
        </td>
      </tr>
      <!-- Dropdown content -->
        <tr v-if="isDropdownActive(object)">
          <td colspan="8">
            <template v-if="isCustomerTotalsLoaded(object.customer_number)">
            <InvoiceOrderTable
                v-bind:orders="getOrders(object)"
                v-bind:options="{ }"
                v-bind:user_id="getCustomerUserId(object)"
                v-bind:columns="{
                  id: {
                    label: 'Transaktion ID',
                    visible: true
                  },
                  customer_id: { visible: false },
                  cashier_id: { visible: false },
                  department_id: {
                    label: 'Afdeling',
                    visible: true,
                    getRowValueFormatted: (order, row) => {
                      return getDepartmentName(order[row.key]);
                    }
                  },
                  reg_1: { visible: true },
                  reg_2: { visible: true },
                  reg_3: { visible: true },
                  reference: { visible: true },
                  notes: { visible: true },
                  created_at: { visible: true },
                  total_net_amount: {
                    label: 'Total',
                    type: 'number',
                    sortable: true,
                    creation: {
                      required: false
                    },
                    visible: true,
                    getRowValueFormatted: (order, row) => {
                      return SessionUser.functions.currency.toLocal(parseInt(order[row.key]));
                    },
                  },
                  /**
                  completed_at: {
                    label: SessionUser.objects.global.language.status,
                    visible: true,
                    getRowValueFormatted: (order, row) => {
                      return order[row.key] ? SessionUser.objects.global.language.completed : SessionUser.objects.global.language.not_completed;
                    },
                    getRowValueColor: (order) => {
                      return order.completed_at ? 'has-text-success' : 'has-text-danger';
                    },
                  }, */
                  external_id: {
                    label: 'Status',
                    visible: true,
                    getRowValueFormatted: (order, row) => {
                      return order[row.key] ? 'E-conomic Kladde' : 'Ikke overført';
                    },
                    getRowValueColor: (order) => {
                      return order.external_id ? 'has-text-warning' : 'has-text-grey';
                    },
                  },
                  show_content: {
                    label: 'Vis',
                    visible: true,
                    getRowValueFormatted: (order, row) => {
                      // Check if the order is already shown (or hidden)
                      if (order.show_content !== undefined && order.show_content) {
                        // Hide the order
                        return SessionUser.objects.global.language.hide_content;
                      } else {
                        // Show the order
                        return SessionUser.objects.global.language.show_content;
                      }
                    },
                    buttonOnClick: (order, row) => {
                      // Check if the order is already shown (or hidden)
                      if (order.show_content !== undefined && order.show_content) {
                        // Hide the order
                        order.show_content = false;
                      } else {
                        // Show the order
                        order.show_content = true;
                      }
                    },
                    isButton: true
                  },
                  manage: {
                    label: SessionUser.objects.global.language.manage,
                    visible: true,
                    getRowValueFormatted: (order, row) => {
                      // Open the order in a new tab
                      return SessionUser.objects.global.language.manage;
                      },
                    buttonOnClick: (order, row) => {
                      // Open the order in a new tab
                      redirect('/admin/' + order.department_id + '/modules/pos/orders/' + order.id);
                    },
                    isButton: true
                  },
                }"
            />
            </template>
            <template v-else>
              <progress class="progress is-small is-link" max="100">Loading...</progress>
            </template>
          </td>
        </tr>
      </template>
      <!-- If the list is empty -->
      <tr v-if="objects.length === 0">
        <td colspan="9">
          Ingen {{ SessionUser.objects.collectedOrderInvoices.meta.labels.multiple }} fundet
        </td>
      </tr>
      <!-- Show a count of the total number of objects -->
      <tr>
        <td colspan="9">Viser {{ objects.length }} af {{ objects.length }} {{ SessionUser.objects.collectedOrderInvoices.meta.labels.multiple }}</td>
      </tr>
      </tbody>
    </table>
</template>

<style scoped>

</style>