<script setup>
import UserSubPageWrapper from "@/views/dashboards/superUserDashboard/user/UserSubPageWrapper.vue";
import PageTitle from "@/components/global/PageTitle.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import {user, getUserData, userId, setUser, getUserCustomerNumber, onUserChange} from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import {ref, watch} from "vue";
import XLVaskVehiclesTable from "@/views/dashboards/superUserDashboard/user/displays/xlvask/XLVaskVehiclesTable.vue";


/** XLVask User vehicles */
const xlvaskUserVehicles = ref([]);
const getXlvaskUserVehicles = async () => {
  // Get the vehicles from XLVask
  await SessionUser.superUser.modules.xlvask.functions.getVehicles(
      xlvaskUserObject.value.customerId,
  ).then((response) => {
        let matchingVehicles = response.data.data;
        if (matchingVehicles.length !== 0) {
          xlvaskUserVehicles.value = matchingVehicles;
        }
      }
  ).catch((error => {}));
}

/** XLVask User */
const xlvaskDefaultUserFunctions = {
  hasXLVaskAccount: () => {
    return xlvaskUserObject.value.customerId !== null
  },
  getThis: () => {
    return xlvaskUserObject
  },
}
const xlvaskDefaultUserObject = {
  customerId: null,
  name: null,
  vendorId: null,
  customerTypeId: null,
  discount: null, // Int
  phone: null,
  email: null,
  address: null,
  address2: null,
  zip: null,
  city: null,
  userId: null,
  vatnumber: null,
  excludeFromAutoInvoice: null,
  country: null,
  createDate: null,
  externId: null,
  active: null,
  language: null,
  note: null,
  updated: null,
  ...xlvaskDefaultUserFunctions,
}
const generateXlVaskUserObject = async () => {
  let tmp_xlvaskUserObject = {
    ...xlvaskDefaultUserObject
  }
  // If the customer number is set, then we can contact XLVask
  if (user.customer_number.value) {
    //console.log("XLVask customer number set", user.customer_number.value);
    // Get all the matching customers from XLVask
    await SessionUser.superUser.modules.xlvask.functions.getCustomers(
        null,
        null,
        user.customer_number.value,
    ).then((response) => {
          //console.log("XLVask response", response.data.data);
          let matchingCustomers = response.data.data;
          if (matchingCustomers.length === 0) {
            //console.log("XLVask customer not found");
          } else {
            //console.log("XLVask customer found", matchingCustomers);
            // Get the first customer
            let customer = matchingCustomers[0];
            //console.log("XLVask customer", customer);
            // Set the customer data
            tmp_xlvaskUserObject = {
              ...tmp_xlvaskUserObject,
              ...customer,
              externId: parseInt(customer.externId),
            }
          }
        }
    ).catch((error => {
      //console.error("XLVask error", error);
    })).finally(() => {
      //console.log("XLVask finally");
      xlvaskUserObject.value = tmp_xlvaskUserObject;
    });
  } else {
    //console.log("XLVask customer number not set");
  }
}
const xlvaskUserObject = ref(xlvaskDefaultUserObject);
const initXlvaskUserObject = async (userId = null) => {
  // Reset the xlvask user object
  xlvaskUserObject.value = {...xlvaskDefaultUserObject};
  if (userId) {
    await generateXlVaskUserObject();
  }
}
onUserChange(newUserId => {
  // Get the user data
  initXlvaskUserObject(newUserId);
})
initXlvaskUserObject(user.id);
watch(user.customer_number, (newValue) => {
  initXlvaskUserObject(user.id);
});

watch(xlvaskUserObject, (newValue) => {
  // Check if the user has an XLVask account
  if (xlvaskUserObject.value.hasXLVaskAccount()) {
    // Get the vehicles from XLVask
    getXlvaskUserVehicles();
  } else {
    // If the user does not have an XLVask account, reset the vehicles
    xlvaskUserVehicles.value = [];
  }
}, { immediate: true });
</script>

<template>
  <UserSubPageWrapper>
    <template #title>
      <PageTitle title="User" :subtitle="SessionUser.superUser.modules.xlvask.meta.title"/>
    </template>
    <div v-if="xlvaskUserObject">
      {{ userId }} (Customer number: {{ user.customer_number }})
      <template v-if="xlvaskUserObject.hasXLVaskAccount()">
        <!-- The user has an XLVask account -->
        <div class="message is-success">
          <div class="message-body">
            <strong>{{ SessionUser.superUser.modules.xlvask.meta.title }} {{ SessionUser.objects.global.language.customer.toLowerCase() }} {{ SessionUser.objects.global.language.found.toLowerCase()}}</strong>
            <p>Navn: {{ xlvaskUserObject.name }}</p>
            <p>Telefon: {{ xlvaskUserObject.phone }}</p>
            <p>Email: {{ xlvaskUserObject.email }}</p>
            <p>Adresse: {{ xlvaskUserObject.address }} {{ xlvaskUserObject.address2 }}</p>
            <p>Postnummer: {{ xlvaskUserObject.zip }}</p>
            <p>By: {{ xlvaskUserObject.city }}</p>
            <p>Land: {{ xlvaskUserObject.country }}</p>
            <!-- If the customer has a discount, show it -->
            <p v-if="xlvaskUserObject.discount !== null">{{ SessionUser.objects.global.language.payment.discount }}: <strong>{{ xlvaskUserObject.discount }}%</strong></p>
            <p>XLVask ID: <strong>{{ xlvaskUserObject.customerId }}</strong></p>
          </div>
        </div>
        <!-- Vehicles connected to the user -->
        <!--{{ xlvaskUserVehicles }} -->
        <XLVaskVehiclesTable
          v-bind:objects="xlvaskUserVehicles"
          v-bind:xl-vask-customer-object="xlvaskUserObject"
          v-bind:user-id="user.id.value"
          />
      </template>
      <template v-else>
        <!-- The user does not have an XLVask account -->
        XLVask ID: <strong>Ingen</strong>
      </template>
    </div>
  </UserSubPageWrapper>
</template>

<style scoped>

</style>