<script setup>

import UserSubPageWrapper from "@/views/dashboards/superUserDashboard/user/UserSubPageWrapper.vue";
import PageTitle from "@/components/global/PageTitle.vue";
import { useRouter } from 'vue-router'
import {user, getUserData, userId, setUser, getUserCustomerNumber} from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import {SessionUser} from "@/components/session/token/SessionUser.vue";
import OrdersPagination from "@/components/displays/pagination/models/DepartmentPos/OrdersPagination.vue";
import {watch} from "vue";
import NotFoundFallBackPageWrapper from "@/components/page/wrappers/NotFoundFallBackPageWrapper.vue";
import PageLoader from "@/components/global/PageLoader.vue";
import Swal from "sweetalert2";
import InvoiceOrdersPagination
  from "@/components/displays/pagination/models/SuperUserDashboard/InvoiceOrdersPagination.vue";
// Get the user from the route
const router = useRouter()

// Set the user
setUser(router.currentRoute.value.params.userId);

const invoiceOrders = async (orders) => {
  console.log('Invoiced individual orders');
  // Check if the order draft exists
  await SessionUser.adminUser.invoices.draft.get(user.keys.value.open_invoice_draft).then(async (response) => {
    console.log(response);
    for (let i = 0; i < orders.length; i++) {
      console.log(orders[i].id);
      await SessionUser.adminUser.invoices.exportOrderToDraft(orders[i].id);
    }
  }).catch((error) => {
    Swal.fire({
      title: 'Fejl',
      html: '<p>Det var ikke muligt at finde faktura kladden. <br>Er den faktureret, eller slettet uden for systemet?</p>',
      icon: 'error',
      confirmButtonText: 'OK'
    });
    console.log(error);
  });
};

const invoicePerOrder = () => {
  // Check if the customer has been loaded
  if (user.attributes.value === null) {
    return false;
  }
  return user.attributes.value.some(attribute => attribute.attribute === 'invoiceAllOrdersIndividually');
};

const reload = () => {
  // Reload the user data
  getUserData();
};
</script>

<template>
  <UserSubPageWrapper>
    <template #title>
      <PageTitle title="User" subtitle="Transaktionshistorik" />
    </template>
    <div>
      <p>User ID: {{ userId }} (Customer number: {{ user.customer_number }})</p>
      <!-- User invoicing -->
      <!--
      <div class="card">
        <div class="card-header">
          <p class="card-header-title">
            <span class="icon"><i class="fas fa-file-invoice"></i></span>
            Fakturering
          </p>

          <p class="card-header-icon" @click="console.log('Settings clicked')">
            <span class="icon"><i class="fas fa-cog"></i></span>
          </p>
        </div>
        <div class="card-content">
          <p>Faktureringsmetode: <strong>{{ invoicePerOrder() ? 'Faktureres pr. ordre' : 'Faktureres samlet' }}</strong></p>
          <p v-if="user.orders_not_invoiced.value">Transaktioner der ikke er faktureret: <strong>{{ user.orders_not_invoiced.value.length }}</strong></p>
          <p v-else>Alle transaktioner er faktureret</p>
          <p v-if="user.keys.value.open_invoice_draft">Aktiv faktura kladde: <strong>{{ user.keys.value.open_invoice_draft }}</strong></p>
        </div>
        <div class="card-footer">
          <div class="card-footer-item">
            <button class="card-footer-item button is-warning is-inverted mx-2"
                    v-if="!invoicePerOrder() && user.orders_not_invoiced.value && user.orders_not_invoiced.value.length > 0"
                    @click="invoiceOrders(user.orders_not_invoiced.value).then(reload())">Tilføj {{ user.orders_not_invoiced.value.length ?? 0 }} transaktioner til samlet faktura kladde
            </button>
            <button class="card-footer-item button is-dark mx-2"
                    v-else
                    disabled>Alle transaktioner er faktureret
            </button>
            <button class="card-footer-item button is-warning is-inverted mx-2"
                    v-if="invoicePerOrder() && user.orders_not_invoiced.value"
                    @click="invoiceOrders(user.orders_not_invoiced.value)">Opret individuelle faktura kladder: {{ user.orders_not_invoiced.value.length ?? 0 }} transaktioner
            </button>
            <button class="card-footer-item button is-success is-inverted mx-2"
                    v-if="!invoicePerOrder() && user.keys.value.open_invoice_draft"
                    @click="SessionUser.adminUser.invoices.draft.close(user.keys.value.open_invoice_draft).then(reload())">Luk faktura kladde ({{ user.keys.value.open_invoice_draft }})
            </button>
          </div>
        </div>
      </div> -->

      <!-- <p>User orders not invoiced: {{ user.orders_not_invoiced.value.length }}</p> -->
      <!-- "orders_not_invoiced": [ { "id": "429" }, { "id": "430" } ] } -->
      <!--<p v-if="user.orders_not_invoiced">
        <span v-for="order in user.orders_not_invoiced.value" :key="order.id">{{ order.id }}, </span>
      </p> -->
      <!-- <button @click="invoiceOrders(user.orders_not_invoiced.value)">Invoice orders</button> -->
      <!-- Orders -->
      <!--<OrdersPagination :hideSearch="true" :set-customer-filter="user.customer_number.value" :auto-load="false" v-if="user.customer_number.value" /> -->
      <InvoiceOrdersPagination
        :hideSearch="false"
        :apply-default-filters="false"
        :set-customer-filter="user.customer_number.value"
        :auto-load="true"
        :invoice-view="true"
        v-if="user.customer_number.value"
        />
      <!-- While the user is not loaded, show a loading message -->
      <div v-else>
        <page-loader title="Loading user data" subtitle="Please wait while we load the user data" />
      </div>
    </div>

  </UserSubPageWrapper>
</template>

<style scoped>

</style>