<script setup>

const props = defineProps({
  onlyFromInvoiceCollection: {
    type: Number,
    default: 0
  },
  autoLoad: {
    type: Boolean,
    default: true
  },
  setCustomerFilter: {
    type: Number,
    default: 0
  },
  hideSearch: {
    type: Boolean,
    default: false
  },
  invoiceView: {
    type: Boolean,
    default: false
  },
  applyDefaultFilters: {
    type: Boolean,
    default: true
  }
})
import {defineProps, ref} from "vue";
import { useRouter } from "vue-router";
import {
  isLoaded,
  isLoading,
  list,
  loadList,
  metaCurrentPage,
  metaItemsPerPage,
  metaTotalItems,
  setEndpoint,
  setMetaItemsPerPage,
  setPage,
  getFilter,
  metaSearch,
  search,
  endpoint,
  setFilter,
  setOrder,
  hideSearchField,
  setHideSearchField,
} from "@/components/pagination/paginatedList.vue";
import PaginationNavigation from "@/components/displays/pagination/PaginationNavigation.vue";

import LoadButtonWhileAwait from "@/components/request/LoadButtonWhileAwait.vue";
import PaginationDisplay from "@/components/displays/pagination/PaginationDisplay.vue";
import OrdersTable from "@/components/displays/department/pos/orders/ordersTable.vue";
import {SessionUser} from "@/components/session/token/SessionUser.vue";

const router = useRouter();
setHideSearchField(props.hideSearch);
setEndpoint("/orders", false);
// If the customer filter is set, filter the orders by the customer number
if (props.setCustomerFilter > 0) {
  setFilter("customer_id", props.setCustomerFilter);
  console.log("Setting customer filter to: " + props.setCustomerFilter);
}

// If the departmentId is set, in the route, filter the orders by the departmentId
if (router.currentRoute.value.params.departmentId) {
  setOrder("created_at", "desc");
  setFilter("department_id", router.currentRoute.value.params.departmentId, false);
} else {
  setOrder("created_at", "desc");
}

// If the onlyFromInvoiceCollection prop is set, filter the orders by the invoice collection id
if (props.onlyFromInvoiceCollection > 0) {
  setFilter("invoice_collection_id", props.onlyFromInvoiceCollection, false);
}

// Load the list automatically if the autoLoad prop is set
if (props.autoLoad) {
  if (props.applyDefaultFilters) {
    setFilter('customer_id-has_key-OtherVaskeabonnement', '!OtherVaskeabonnement', false);
    setFilter('customer_id-has_key-OtherSpecialArrangement', '!OtherSpecialArrangement', false);
    setFilter('booked_invoice_id', 'is_null', false);
  }
  loadList();
}

const date_from = ref(null);
const date_to = ref(null);

const setFilterTime = {
  is_last_month: (date_from, date_to) => {
    // Check if the date_from and date_to are set to the first and last day of the month
    const date = new Date();
    const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth() - 1, 2);
    const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
    return date_from === firstDayOfMonth.toISOString().split("T")[0] && date_to === lastDayOfMonth.toISOString().split("T")[0];
  },
  last_month: () => {
    // Set the value of the date_from and date_to to the first and last day of the month
    const date = new Date();
    // Since the timestamp is not relevant, we can set the date to the first and last day of the month like 1/4/2023 to 30/4/2023
    const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth() - 1, 2);
    const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
    date_from.value = firstDayOfMonth.toISOString().split("T")[0];
    date_to.value = lastDayOfMonth.toISOString().split("T")[0];
    // Set the filter to the date_from and date_to
    setFilter("created_at-date_from", date_from.value, false);
    setFilter("created_at-date_to", date_to.value, false);
    loadList();
  },
  is_this_month: (date_from, date_to) => {
    // Check if the date_from and date_to are set to the first and last day of the month
    const date = new Date();
    const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 2);
    const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1);
    return date_from === firstDayOfMonth.toISOString().split("T")[0] && date_to === lastDayOfMonth.toISOString().split("T")[0];
  },
  this_month: () => {
    // Set the value of the date_from and date_to to the first and last day of the month
    const date = new Date();
    // Since the timestamp is not relevant, we can set the date to the first and last day of the month like 1/4/2023 to 30/4/2023
    const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 2);
    const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1);
    date_from.value = firstDayOfMonth.toISOString().split("T")[0];
    date_to.value = lastDayOfMonth.toISOString().split("T")[0];
    // Set the filter to the date_from and date_to
    setFilter("created_at-date_from", date_from.value, false);
    setFilter("created_at-date_to", date_to.value, false);
    loadList();
  },
  is_today: (date_from, date_to) => {
    // Check if the date_from and date_to are set to today
    const date = new Date();
    const today = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
    return date_from === today.toISOString().split("T")[0] && date_to === today.toISOString().split("T")[0];
  },
  today: () => {
    // Set the value of the date_from and date_to to today
    const date = new Date();
    // Since the timestamp is not relevant, we can set the date to the first and last day of the month like 1/4/2023 to 30/4/2023
    const today = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
    date_from.value = today.toISOString().split("T")[0];
    date_to.value = today.toISOString().split("T")[0];
    // Set the filter to the date_from and date_to
    setFilter("created_at-date_from", date_from.value, false);
    setFilter("created_at-date_to", date_to.value, false);
    loadList();
  },
  is_yesterday: (date_from, date_to) => {
    // Check if the date_from and date_to are set to yesterday
    const date = new Date();
    const yesterday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    return date_from === yesterday.toISOString().split("T")[0] && date_to === yesterday.toISOString().split("T")[0];
  },
  yesterday: () => {
    // Set the value of the date_from and date_to to the first and last day of the month
    const date = new Date();
    // Since the timestamp is not relevant, we can set the date to the first and last day of the month like 1/4/2023 to 30/4/2023
    const yesterday = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 0);
    date_from.value = yesterday.toISOString().split("T")[0];
    date_to.value = yesterday.toISOString().split("T")[0];
    // Set the filter to the date_from and date_to
    setFilter("created_at-date_from", date_from.value, false);
    setFilter("created_at-date_to", date_to.value, false);
    // Reload the list
    loadList();
  },
  is_all: (date_from, date_to) => {
    // Check if the date_from and date_to are set to null
    return date_from === null && date_to === null;
  },
  all: () => {
    // Set the value of the date_from and date_to to null
    date_from.value = null;
    date_to.value = null;
    // Set the filter to the date_from and date_to
    setFilter("created_at-date_from", null, false);
    setFilter("created_at-date-to", null, false);
    // Reload the list
    loadList();
  }
}

const getTimeShortcutClass = (boolean) => {
  // Check if the shortcut is set to the current date
  return boolean ? 'is-success is-light' : '';
}

const getTimeShortcutIcon = (boolean) => {
  // Check if the shortcut is set to the current date
  return boolean ? 'fas fa-check' : '';
}


const doesEndpointMatch = (matcher) => {
  // Check if the endpoint matches the current endpoint
  return endpoint.value === matcher;
}

</script>

<template>
  <template v-if="doesEndpointMatch('/orders')">
    <input @input="search($event.target.value)" class="input" type="text" placeholder="Søg i transaktioner" v-if="!hideSearchField"/>
    <PaginationDisplay :metaItemsPerPage="metaItemsPerPage" :loadFunction="loadList" :isLoading="isLoading" :setMetaItemsPerPage="setMetaItemsPerPage">
      <template #paginationColumns>
        <!-- Sort by created_at -->
        <div class="column is-narrow my-3">
          <label class="label">Order direction</label>
          <div class="control">
            <div class="select">
              <select @change="setOrder('created_at', $event.target.value, true);">
                <option value="asc">Ascending (Oldest first)</option>
                <option value="desc" selected>Descending (Newest first)</option>
              </select>
            </div>
          </div>
        </div>
        <!-- Invoice status -->
        <div class="column is-narrow my-3">
          <label class="label">Bogføringsstatus</label>
          <div class="control">
            <div class="select">
              <select @change="setFilter('booked_invoice_id', $event.target.value, true);">
                <option value="*" :selected="!props.applyDefaultFilters">All</option>
                <option value="not null">Bogført</option>
                <option value="is_null" :selected="props.applyDefaultFilters">Ikke bogført</option>
              </select>
            </div>
          </div>
        </div>
        <!-- Error status -->
        <div class="column is-narrow my-3">
          <label class="label">Fejlstatus</label>
          <div class="control">
            <div class="select">
              <select @change="setFilter('error_message', $event.target.value, true);">
                <option value="*" selected>All</option>
                <option value="not null">Ja</option>
                <option value="is_null">Nej</option>
              </select>
            </div>
          </div>
        </div>
        <!-- Payment processor -->
        <div class="column is-narrow my-3">
          <label class="label">Betalingsprocessor</label>
          <div class="control">
            <div class="select">
              <select @change="setFilter('processor', $event.target.value, true);">
                <option value="*" selected>All</option>
                <option value="1">E-conomic</option>
                <option value="2">Stripe</option>
                <option value="3">Anden ( Uden tracking )</option>
                <option :value="'is_null'">Ikke specificeret</option>
              </select>
            </div>
          </div>
        </div>
        <!-- Marked as complete ("Gennemført") -->
        <div class="column is-narrow my-3">
          <label class="label">Gennemført</label>
          <div class="control">
            <div class="select">
              <select @change="setFilter('completed_at', $event.target.value, true);">
                <option value="*" selected>All</option>
                <option value="not null">Gennemført</option>
                <option :value="'is_null'">Ikke gennemført</option>
              </select>
            </div>
          </div>
        </div>
        <!-- Multiple selection, customer has attribute -->
        <div class="column is-narrow my-3">
          <label class="label">Faktura valg</label>
          <div class="control">
            <div class="select">
              <select @change="setFilter('customer_id-has_attribute', $event.target.value, true);">
                <option value="*" selected>All</option>
                <option value="invoiceAllOrdersIndividually">Faktura pr. ordre</option>
                <option value="!invoiceAllOrdersIndividually">Faktura pr. måned</option>
              </select>
            </div>
          </div>
        </div>
        <!-- Multiple selection, customer has special arrangement -->
        <div class="column is-narrow my-3">
          <label class="label">Specialaftale</label>
          <div class="control">
            <div class="select">
              <select @change="setFilter('customer_id-has_key-OtherSpecialArrangement', $event.target.value, true);">
                <option value="*" :selected="!props.applyDefaultFilters">All</option>
                <option value="OtherSpecialArrangement">Har specialaftale</option>
                <option value="!OtherSpecialArrangement" :selected="props.applyDefaultFilters">Har ikke specialaftale</option>
              </select>
            </div>
          </div>
        </div>
        <!-- Multiple selection, customer has washing subscription -->
        <div class="column is-narrow my-3">
          <label class="label">Vaskeabonnement</label>
          <div class="control">
            <div class="select">
              <select @change="setFilter('customer_id-has_key-OtherVaskeabonnement', $event.target.value, true);">
                <option value="*" :selected="!props.applyDefaultFilters">All</option>
                <option value="OtherVaskeabonnement">Har vaskeabonnement</option>
                <option value="!OtherVaskeabonnement" :selected="props.applyDefaultFilters">Har ikke vaskeabonnement</option>
              </select>
            </div>
          </div>
        </div>
        <!-- Multiple selection, customer has washing subscription -FIX
        <div class="column is-narrow my-3">
          <label class="label">Only tank cleaning</label>s
          <div class="control">
            <div class="select">
              <select @change="setFilter('customer_id-has_attribute', $event.target.value, true);">
                <option value="*" :selected="!props.applyDefaultFilters">All</option>
                <option value="onlyTankCleaning">Only tank cleaning</option>
                <option value="!onlyTankCleaning" :selected="props.applyDefaultFilters">Ikke tankcleaning</option>
              </select>
            </div>
          </div>
        </div> -->
        <!-- Date from -->
        <div class="column is-narrow my-3">
          <label class="label">Fra dato</label>
          <div class="control">
            <input type="date" class="input" @change="setFilter('created_at-date_from', $event.target.value, true)" v-model="date_from" />
          </div>
        </div>
        <!-- Date to -->
        <div class="column is-narrow my-3">
          <label class="label">Til dato</label>
          <div class="control">
            <input type="date" class="input" @change="setFilter('created_at-date_to', $event.target.value, true)" v-model="date_to" />
          </div>
        </div>
        <!-- Time shortcuts -->
        <!-- Last month -->
        <div class="column is-narrow my-3">
          <label class="label">&nbsp</label>
          <div class="control">
            <button
                class="button"
                v-bind:class="getTimeShortcutClass(setFilterTime.is_last_month(date_from, date_to))"
                @click="setFilterTime.last_month()"
            >
              <span class="icon">
                <i v-bind:class="getTimeShortcutIcon(setFilterTime.is_last_month(date_from, date_to))"></i>
              </span>
              <span>{{SessionUser.objects.global.language.time.last_month}}</span>
              <span class="icon">
              </span>
            </button>
          </div>
        </div>
        <!-- This month -->
        <div class="column is-narrow my-3">
          <label class="label">&nbsp</label>
          <div class="control">
            <button
                class="button"
                v-bind:class="getTimeShortcutClass(setFilterTime.is_this_month(date_from, date_to))"
                @click="setFilterTime.this_month()"
            >
              <span class="icon">
                <i v-bind:class="getTimeShortcutIcon(setFilterTime.is_this_month(date_from, date_to))"></i>
              </span>
              <span>{{SessionUser.objects.global.language.time.this_month}}</span>
              <span class="icon">
              </span>
            </button>
          </div>
        </div>
        <!-- Today -->
        <div class="column is-narrow my-3">
          <label class="label">&nbsp</label>
          <div class="control">
            <button
                class="button"
                v-bind:class="getTimeShortcutClass(setFilterTime.is_today(date_from, date_to))"
                @click="setFilterTime.today()"
            >
              <span class="icon">
                <i v-bind:class="getTimeShortcutIcon(setFilterTime.is_today(date_from, date_to))"></i>
              </span>
              <span>{{SessionUser.objects.global.language.time.today}}</span>
              <span class="icon">
              </span>
            </button>
          </div>
        </div>
        <!-- Yesterday -->
        <div class="column is-narrow my-3">
          <label class="label">&nbsp</label>
          <div class="control">
            <button
                class="button"
                v-bind:class="getTimeShortcutClass(setFilterTime.is_yesterday(date_from, date_to))"
                @click="setFilterTime.yesterday()"
            >
              <span class="icon">
                <i v-bind:class="getTimeShortcutIcon(setFilterTime.is_yesterday(date_from, date_to))"></i>
              </span>
              <span>{{SessionUser.objects.global.language.time.yesterday}}</span>
              <span class="icon">
              </span>
            </button>
          </div>
        </div>
        <!-- All -->
        <div class="column is-narrow my-3">
          <label class="label">&nbsp</label>
          <div class="control">
            <button
                class="button"
                v-bind:class="getTimeShortcutClass(setFilterTime.is_all(date_from, date_to))"
                @click="setFilterTime.all()"
            >
              <span class="icon">
                <i v-bind:class="getTimeShortcutIcon(setFilterTime.is_all(date_from, date_to))"></i>
              </span>
              <span>{{SessionUser.objects.global.language.time.all}}</span>
              <span class="icon">
              </span>
            </button>
          </div>
        </div>
      </template>
    </PaginationDisplay>
    <OrdersTable :orders="list" :invoiceView="props.invoiceView" :allowSelectMultiple="true"/>
    <PaginationNavigation :currentPage="metaCurrentPage" :totalPages="Math.ceil(metaTotalItems / metaItemsPerPage)" :loadFunction="loadList" :setPage="setPage" :isLoading="isLoading" />
    <LoadButtonWhileAwait class="is-dark" :isLoading="isLoading" :loadFunction="loadList" icon="fas fa-sync-alt">Reload</LoadButtonWhileAwait>
  </template>
</template>

<style scoped>

</style>