<script setup>
import placeholder from "/src/assets/piktogrammer/placeholder.png";
import productImage01 from "/src/assets/piktogrammer/01.png";
import productImage02 from "/src/assets/piktogrammer/02.png";
import productImage03 from "/src/assets/piktogrammer/03.png";
import productImage04 from "/src/assets/piktogrammer/04.png";
import productImage05 from "/src/assets/piktogrammer/05.png";
import productImage06 from "/src/assets/piktogrammer/06.png";
import productImage07 from "/src/assets/piktogrammer/07.png";
import productImage08 from "/src/assets/piktogrammer/08.png";
import productImage09 from "/src/assets/piktogrammer/09.png";
import productImage10 from "/src/assets/piktogrammer/10.png";
import productImage12 from "/src/assets/piktogrammer/12.png";
import productImage13 from "/src/assets/piktogrammer/13.png";
import productImage14 from "/src/assets/piktogrammer/14.png";
import {onMounted, ref, watch} from 'vue';
import {
  getOrderId,
  getProductsCategory,
  loadOrderItems,
  productCategoryAllowed,
  setProductsCategory,
  getUserProductDiscount,
  showFakeCreateOrderItem,
  department_id,
  user_discounts,
  getUserGlobalDiscount,
  getUserDiscounts,
  customer_id,
  customer_attributes
} from "@/components/shop/POSDepartmentProcess.vue";
import {getProductCategory, getProducts} from "@/components/shop/Products.vue";
import {createOrderItem} from "@/components/shop/OrdersItems.vue";
import {SessionUser} from "@/components/session/token/SessionUser.vue";
import  { useRoute } from 'vue-router';
import Swal from "sweetalert2";
import ConfigurationCategory from "@/components/displays/superuser/configuration/ConfigurationCategory.vue";
import WhiteBox from "@/components/displays/boxes/WhiteBox.vue";
import ProductBox from "@/components/displays/boxes/ProductBox.vue";
// Define the products
const products = ref([]);

// If the category is not defined, get all products
if (getProductsCategory() === null) {
  getProducts(department_id.value).then((response) => {
    products.value = response.data.data;
    console.log(products.value);
  });
} else {
  // Get the products by category
  getProductCategory(getProductsCategory(), department_id.value).then((response) => {
    products.value = response.data.data;
    console.log(products.value);
  });
}



// Get the picture of the product
const getPicture = (piktogram) => {
  // If the image is not defined, return a placeholder image
  if (piktogram === null || piktogram === "" || piktogram === undefined) {
    // Import the placeholder image
    return placeholder;
  }
  // Return the image based on the piktogram
  /**
   * I'm defining the images here, because I don't want to import them in the template
   */
  switch (piktogram) {
    case "01":
      return productImage01;
    case "02":
      return productImage02;
    case "03":
      return productImage03;
    case "04":
      return productImage04;
    case "05":
      return productImage05;
    case "06":
      return productImage06;
    case "07":
      return productImage07;
    case "08":
      return productImage08;
    case "09":
      return productImage09;
    case "10":
      return productImage10;
    case "12":
      return productImage12;
    case "13":
      return productImage13;
    case "14":
      return productImage14;
    default:
      return placeholder;
  }
};

const showAddMultipleProducts = (productId) => {
  Swal.fire({
    title: 'Tilføj flere produkter',
    input: 'number',
    inputAttributes: {
      autocapitalize: 'off'
    },
    showCancelButton: true,
    confirmButtonText: 'Tilføj',
    showLoaderOnConfirm: true,
    preConfirm: (inputValue) => {
      // Check if the input number is higher than 200
      if (inputValue > 200) {
        Swal.showValidationMessage(
          'Du kan ikke tilføje mere end 200 produkter ad gangen'
        );
      }
      else if (inputValue < 1) {
        Swal.showValidationMessage(
          'Du skal tilføje mindst 1 produkt'
        );
      } else {
        return createOrderItem(getOrderId(), productId, inputValue).then(async () => await addAddonsToOrderMiddleware(productId, inputValue).then(() => loadOrderItems()));
      }
    },
    allowOutsideClick: () => !Swal.isLoading()
  });
};

// Define the categories
const categories_static = ref([
  {
    name: "Alle",
    identifier: null
  },
])

// Set the categories
const categories = ref([]);

// Add the dynamic categories
const loadCategories = async () => {
  categories.value = [];
  // Add the static categories
  categories.value.push(...categories_static.value);
  // Get the department id from the route
  const route = useRoute();
  const departmentId = route.params.departmentId;
  // Get the categories
  await SessionUser.objects.department_categories.get.single(
      departmentId
  ).then((response) => {
    for (let i = 0; i < response.length; i++) {
      categories.value.push({
        name: response[i].category.name,
        identifier: response[i].category.id
      });
    }
  });
};

// Load the categories
onMounted(() => {
  loadCategories();
});


// Get product border
const getProductBorder = (product) => {
  // RED (#ff3860): Category is not allowed
  // GREEN (#00d1b2): Same item was selected last time
  // BLUE (#3273dc): Default border

  // Check if the category is allowed
  if (!productCategoryAllowed(product.category)) {
    return '1px solid #ff3860';
  }

  // Check if the product is the same as the last time the vehicle ordered TODO: Implement this

  // Return the default border
  return '1px solid #3273dc';
};

const productAddons = ref([]);

const isProductAddonTrue = (productId, addonId) => {
  return productAddons.value.find((productAddon) => productAddon.product_id === productId && productAddon.addon_id === addonId && productAddon.status === true) !== undefined;
};
// Set the product addon
const setProductAddon = (productId, addonId, status, quantity = 1) => {
  // Set the product addon status
  const productAddon = productAddons.value.find((productAddon) => productAddon.product_id === productId && productAddon.addon_id === addonId);
  if (productAddon === undefined) {
    productAddons.value.push({
      product_id: productId,
      addon_id: addonId,
      quantity: status ? quantity : 0,
      status: quantity === 0 ? false : status
    });
  } else {
    productAddon.status = status;
  }
};

// Toggle product addon
const toggleProductAddon = (productId, addonId) => {
  console.log(productId, addonId);
  setProductAddon(productId, addonId, !isProductAddonTrue(productId, addonId));
};

const addAddonsToOrderMiddleware = async (product_id, quantity = 1, related_item_id = null) => {
  // If the product addons are set, add them to the order (If the product is added)
  var product_addons = productAddons.value.filter((productAddon) => productAddon.product_id === product_id && productAddon.status === true);
  for (let i = 0; i < product_addons.length; i++) {
    console.log('Adding addon to order', product_addons[i]);
    // Get the addons quantity (If the addon quantity is 0, use the product quantity, otherwise multiply the addon quantity with the product quantity)
    let addon_quantity = product_addons[i].quantity === 0 ? quantity : product_addons[i].quantity * quantity;
    // Get the products addon, and show the fake create order item
    showFakeCreateOrderItem(
        product_addons[i].addon_id,
        addon_quantity,
        0,
        related_item_id,
        product_addons[i].notes === undefined ? null : product_addons[i].notes
    );
  }
  // Add the addons to the order
  for (let i = 0; i < product_addons.length; i++) {
    let addon_quantity = product_addons[i].quantity === 0 ? quantity : product_addons[i].quantity * quantity;
    await createOrderItem(
        getOrderId(),
        product_addons[i].addon_id,
        addon_quantity,
        related_item_id,
        product_addons[i].notes === undefined ? null : product_addons[i].notes
    );
  }
};

const getProductAddonQuantity = (productId, addonId) => {
  // Get the product addon quantity (If the product addon is not set, return 0)
  const productAddon = productAddons.value.find((productAddon) => productAddon.product_id === productId && productAddon.addon_id === addonId);
  return productAddon === undefined ? 0 : productAddon.quantity;
};

const setProductAddonQuantity = (productId, addonId, quantity) => {
  console.log(productId, addonId, quantity);
  // If the quantity is 0, set the product addon status to false
  if (quantity === 0 || quantity < 0) {
    setProductAddon(productId, addonId, false, 0);
  } else {
    // Set the product addon quantity
    setProductAddon(productId, addonId, true, quantity);
  }
};

const addProductWithAddonsToOrder = async (product_id) => {
  // Check if the product requires a note
  const product = products.value.find((product) => product.id === product_id);
  if (product.requires_note) {
    // Show the note input
    await Swal.fire({
      title: 'Tilføj en note',
      input: 'text',
      inputLabel: 'Noten kan ses af kunden. F.eks. "Fjernelse af graffiti på venstre side"',
      inputAttributes: {
        autocapitalize: 'off'
      },
      showCancelButton: true,
      confirmButtonText: 'Tilføj',
      showLoaderOnConfirm: true,
      preConfirm: (note) => {
        // Show the fake create order item
        showFakeCreateOrderItem(product_id, 1, 0, 0, note);
        // Create the order item
        createOrderItem(getOrderId(), product_id, 1, 0, note).then(async (result) => {
          let order_item_id = result.data.data.id;
          // Add the addons to the order
          await addAddonsToOrderMiddleware(product_id, 1, order_item_id).then(() => {
            loadOrderItems();
          });
        });
      },
      allowOutsideClick: () => !Swal.isLoading()
    });
    return;
  }
  // If the product requires a note, show the note input
  console.log(product_id);
  let quantity = 1;
  // Show the fake create order item
  showFakeCreateOrderItem(product_id, quantity, 0);
  // Create the order item
  await createOrderItem(getOrderId(), product_id, quantity).then(async (result) => {
    let order_item_id = result.data.data.id;
    // Add the addons to the order
    await addAddonsToOrderMiddleware(product_id, quantity, order_item_id).then(() => {
      loadOrderItems();
    });
  });
};

const recommended_product_ids = ref([]);
const recommended_last_orders = ref([]);

const getRecommended = () => {
  SessionUser.request(
      '/departments/order/recommended?id=' + getOrderId(),
      'GET'
  ).then((response) => {
    console.log(response.data.data);
    recommended_product_ids.value = response.data.data.reg_1.motorapi;
    // Since the current order is saved, we need to remove the first item from the order history
    recommended_last_orders.value = [
        response.data.data.reg_1.order_history[2],
        response.data.data.reg_1.order_history[3],
        response.data.data.reg_1.order_history[4],
        response.data.data.reg_1.order_history[5],
        ];
  });
}

getRecommended();

const isShowingRecommended = ref(false);

const showRecommendedProducts = () => {
  // Set the category to null
  setProductsCategory(null);
  getProducts(department_id.value).then((response) => {
    products.value = response.data.data;
    isShowingRecommended.value = true;

  });
};

const hideRecommendedProducts = () => {
  isShowingRecommended.value = false;
};

const selectedProduct = ref(null);

const isProductSelected = (productId) => {
  return selectedProduct.valueOf() === parseInt(productId);
};

const selectProduct = (productId) => {
  if (selectedProduct.valueOf() === parseInt(productId)) {
    selectedProduct.value = null;
  } else {
    selectedProduct.value = parseInt(productId);
  }
};

const getAddonPrice = (productId, addonId) => {
  return products.value.find((product) => product.id === productId).addons.find((addon) => addon.option_id === addonId).price;
};

const addProductAddon = (productId, addonId) => {
  const product = products.value.find((product) => product.id === productId);
  const addon = product.addons.find((addon) => addon.option_id === addonId);
  const productAddon = productAddons.value.find((productAddon) => productAddon.product_id === productId && productAddon.addon_id === addonId);
  if (productAddon === undefined) {
    productAddons.value.push({
      product_id: productId,
      addon_id: addonId,
      quantity: 1,
      status: true
    });
  } else {
    productAddon.quantity += 1;
    productAddon.status = true;
  }
};

const setProductAddonNote = (productId, addonId, note) => {
  const productAddon = productAddons.value.find((productAddon) => productAddon.product_id === productId && productAddon.addon_id === addonId);
  if (productAddon !== undefined) {
    productAddon.notes = note;
  }
  console.log(productAddons.value);
};

const subtractProductAddon = (productId, addonId) => {
  const productAddon = productAddons.value.find((productAddon) => productAddon.product_id === productId && productAddon.addon_id === addonId);
  if (productAddon !== undefined) {
    if (productAddon.quantity > 0) {
      productAddon.quantity -= 1;
    }
    // If the quantity is 0, set the product addon status to false
    if (productAddon.quantity === 0) {
      productAddon.status = false;
    }
  }
};

const unselectProduct = () => {
  // Wait for the selection from the click to be done
  setTimeout(() => {
    selectedProduct.value = null;
  }, 100);
};

// If the customer id is set, get the discounts
const onCustomerChange = () => {
  if (parseInt(customer_id.value) > 0) {
    getUserDiscounts(customer_id.value).then((discounts_res) => {
      //console.log(discounts_res);
      // Set the discounts
      user_discounts.value = discounts_res;
    });
    return;
  }
  user_discounts.value = undefined;
};

// Watch the customer id
watch(customer_id, () => {
  onCustomerChange();
});
onMounted(() => {
  onCustomerChange();
});
</script>

<template>
  <div>
    <div class="columns is-multiline">
      <div class="column is-12 is-flex is-justify-content-space-between">
        <!-- Categories - Desktop -->
        <WhiteBox style="padding-bottom: 0; padding-top: 0.6rem;" class="px-0 is-hidden-touch">
          <template #default>
            <!-- Tabs -->
            <div class="tabs" style="overflow-x: auto;">
              <ul>
                <li
                    v-for="category in categories"
                    :key="category.identifier"
                    :class="{
                      'is-active': category.identifier === getProductsCategory() && !isShowingRecommended
                    }">
                  <a
                      @click="hideRecommendedProducts();
                      setProductsCategory(category.identifier);
                      getProductCategory(category.identifier, department_id.valueOf())
                      .then((response) => {
                        products = response.data.data;
                      });"
                      :style="{ 'border-bottom-color': category.identifier === getProductsCategory() ? '#3273dc' : '#fff' }"
                      style="
                        border-bottom-width: 0.6rem;
                        min-width: 4rem;
                        font-size: 0.8rem;
">
                    {{ category.name }}
                  </a>
                </li>
              </ul>
            </div>
          </template>
        </WhiteBox>
        <!-- Categories - Mobile -->
        <WhiteBox class="is-hidden-desktop" style="padding-bottom: 0; padding-top: 0.6rem; width: 100%;">
          <template #default>
            <div class="select is-fullwidth mb-2">
              <select
                  @change="hideRecommendedProducts();
                  setProductsCategory($event.target.value);
                  getProductCategory($event.target.value, department_id.valueOf())
                  .then((response) => {
                    products = response.data.data;
                  });"
              >
                <option v-for="category in categories" :key="category.identifier" :value="category.identifier ?? 'null'">
                  {{ category.name }}
                </option>
              </select>
            </div>
          </template>
        </WhiteBox>
      </div>
    </div>
    <div class="tw-scroll-minimal" style="overflow-y: auto; overflow-x: clip; max-height: 100vh;">
      <div class="columns is-multiline is-mobile">
        <!-- Recommended products -->
        <div class="column is-12" v-if="isShowingRecommended">
          <!-- Same as last time -->
          <configurationCategory
            module="Skal kunden have det samme som sidst?"
            subtitle="Opret en ny ordre baseret på tidligere ordrer"
            icon="fas fa-history"
            v-if="isShowingRecommended"
          >
            <template #default>
              <div v-for="previous_order in recommended_last_orders">
                <configurationCategory
                  class="mt-3"
                  title="Tidligere ordre"
                  v-if="previous_order.length > 0"
                >
                <table class="table is-fullwidth" v-if="previous_order.length > 0">
                  <thead>
                    <tr>
                      <th>Produkt</th>
                      <th class="has-text-right">Antal</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="order_item in previous_order">
                      <td>{{ order_item.product.name }}</td>
                      <td class="has-text-right">{{ order_item.quantity }}</td>
                    </tr>
                  </tbody>
                  <tfoot>
                    <tr>
                      <td colspan="2">
                        <button style="text-decoration-line: none;" class="button is-text is-fullwidth" @click="(previous_order.forEach((order_item) => { showFakeCreateOrderItem(order_item.product.id, order_item.quantity, (order_item.product.price - (order_item.product.price * (getUserProductDiscount(order_item.product) / 100))).toFixed(0)); createOrderItem(getOrderId(), order_item.product.id, order_item.quantity).then(() => addAddonsToOrderMiddleware(order_item.product.id, order_item.quantity).then(() => loadOrderItems())); })); isShowingRecommended = false;">
                          <span class="icon">
                            <i class="fas fa-plus"></i>
                          </span>
                          <span>Tilføj alle ( {{ previous_order.length }} ) produkter</span>
                        </button>
                      </td>
                    </tr>
                  </tfoot>
                </table>
                </configurationCategory>
              </div>
            </template>
          </configurationCategory>
          <!-- Recommended products -->
          <configurationCategory
            module="Anbefalede produkter"
            subtitle="Baseret på køretøjet"
            icon="fas fa-car"
            >
            <div class="columns">
              <div class="column is-6" v-for="product_id in recommended_product_ids" :key="product_id">
                <div class="card">
                  <div class="card-content">
                    <p class="title is-6">
                      <span>{{ products.find(product => product.id === product_id).name }}</span>
                      <span class="is-float-right">{{ products.find(product => product.id === product_id).price - (products.find(product => product.id === product_id).price * (getUserProductDiscount(products.find(product => product.id === product_id)) / 100)).toFixed(0) }} Kr.</span>
                    </p>
                    <p class="subtitle is-6 has-text-grey">{{ products.find(product => product.id === product_id).description }}</p>
                    <div class="content">
                      <div class="buttons is-narrow">
                        <template v-for="addons in products.find(product => product.id === product_id).addons" :key="addons.id">
                          <button class="button is-rounded is-small" @click="setProductAddon(product_id, addons.option_id, !isProductAddonTrue(product_id, addons.option_id))" :class="{ 'is-primary': isProductAddonTrue(product_id, addons.option_id), 'is-inverted': isProductAddonTrue(product_id, addons.option_id) }">
                            <span class="icon">
                              <i class="fas fa-plus" v-if="!isProductAddonTrue(product_id, addons.option_id)"></i>
                              <i class="fas fa-check" v-else></i>
                            </span>
                            <span>
                              {{ addons.name }}
                            </span>
                          </button>
                        </template>
                      </div>
                    </div>
                  </div>
                  <footer class="card-footer">
                    <a href="#" class="card-footer-item" @click.prevent="showAddMultipleProducts(product_id)" v-if="productCategoryAllowed(products.find(product => product.id === product_id).category)">
                      <span class="icon">
                        <i class="fas fa-plus"></i>
                      </span>
                      <span>Tilføj flere</span>
                    </a>
                    <a href="#" class="card-footer-item"
                       @click.prevent="showFakeCreateOrderItem(products.find(product => product.id === product_id), 1, (products.find(product => product.id === product_id).price - (products.find(product => product.id === product_id).price * (getUserProductDiscount(products.find(product => product.id === product_id)) / 100))).toFixed(0)); createOrderItem(getOrderId(), product_id, 1).then(() => addAddonsToOrderMiddleware(product_id).then(() => loadOrderItems()));"
                       v-if="productCategoryAllowed(products.find(product => product.id === product_id).category)">
                      <span class="icon">
                        <i class="fas fa-plus"></i>
                      </span>
                      <span>Tilføj</span>
                    </a>
                    <a href="#" class="card-footer-item" v-if="!productCategoryAllowed(products.find(product => product.id === product_id).category)" disabled>IKKE TILGÆNGELIG FOR DENNE KUNDE</a>
                  </footer>
                </div>
              </div>
            </div>
            <pre>{{ recommended_product_ids }}</pre>
          </configurationCategory>
        </div>
        <!-- New product display -->
        <template v-for="product in products" :key="product.id" v-if="!isShowingRecommended">
          <div class="column is-6-desktop">
            <WhiteBox
                class="p-0 pos-product-box"
                :class="{ 'is-selected': selectedProduct === product.id }"
            >
              <ProductBox
                  :product="product"
                  :id="product.id"
                  :name="product.name"
                  :description="product.description"
                  :price="product.price"
                  :image="getPicture(product.piktogram)"
                  :addons="product.addons"
                  :isSelected="selectedProduct === product.id"
                  :selectedAddons="productAddons"
                  :toggleProductAddon="toggleProductAddon"
                  :getProductAddonQuantity="getProductAddonQuantity"
                  :addProductAddon="addProductAddon"
                  :subtractProductAddon="subtractProductAddon"
                  @click="!isProductSelected(product.id) ? selectProduct(product.id) : void 0"
                  @addToCart="addProductWithAddonsToOrder(product.id)"
                  :unselect="unselectProduct"
                  :setProductAddonNote="setProductAddonNote"
                  :customer-discounts="user_discounts"
                  v-bind:customer-attributes="customer_attributes"
              />
            </WhiteBox>
          </div>
        </template>

        <!-- Products
        <div class="column is-4-desktop" v-for="product in products" :key="product.id" v-if="!isShowingRecommended">
          <div class="card" :style="{ 'border': getProductBorder(product) }">
            <div class="card-header-title">{{ SessionUser.objects.categories.functions.getCategoryName(product.category) }}</div>
            <div class="card-content">
              <div class="media mb-0">
                <div class="media-left">
                  <figure class="image is-48x48">
                    <img
                        :src="getPicture(product.piktogram)"
                        :alt="product.name"
                    />
                  </figure>
                </div>
                <div class="media-content">
                  <p class="title is-6">{{ product.name }}</p>
                  <p class="subtitle is-6 has-text-grey" v-if="getUserProductDiscount(product) === 0">{{ product.price }} Kr.</p>
                  <p class="subtitle is-6 has-text-grey" v-else>{{ (product.price - (product.price * (getUserProductDiscount(product) / 100))).toFixed(0) }} Kr. ({{ getUserProductDiscount(product) }}% rabat)</p>
                  <p class="subtitle is-7">{{ product.description }}</p>
                </div>
              </div>
              <div class="content">
                <div class="buttons is-narrow">
                  <template v-for="addons in product.addons" :key="addons.id">
                        <button class="button is-rounded is-small" @click="setProductAddon(product.id, addons.option_id, !isProductAddonTrue(product.id, addons.option_id))" :class="{ 'is-primary': isProductAddonTrue(product.id, addons.option_id), 'is-inverted': isProductAddonTrue(product.id, addons.option_id) }">
                          <span class="icon">
                            <i class="fas fa-plus" v-if="!isProductAddonTrue(product.id, addons.option_id)"></i>
                            <i class="fas fa-check" v-else></i>
                          </span>
                          <span>
                          {{ addons.name }}
                          </span>
                        </button>
                  </template>
                </div>
              </div>
            </div>
            <footer class="card-footer">
              <a href="#" class="card-footer-item" @click.prevent="showAddMultipleProducts(product.id)" v-if="productCategoryAllowed(product.category)">
                <span class="icon">
                  <i class="fas fa-plus"></i>
                </span>
                <span>Tilføj flere</span>
              </a>
              <a href="#" class="card-footer-item"
                 @click.prevent="showFakeCreateOrderItem(product, 1, (product.price - (product.price * (getUserProductDiscount(product) / 100))).toFixed(0)); createOrderItem(getOrderId(), product.id, 1).then(() => addAddonsToOrderMiddleware(product.id).then(() => loadOrderItems()));"
                 v-if="productCategoryAllowed(product.category)">
                <span class="icon">
                  <i class="fas fa-plus"></i>
                </span>
                <span>Tilføj</span>
              </a>
              <a href="#" class="card-footer-item" v-if="!productCategoryAllowed(product.category)" disabled>IKKE TILGÆNGELIG FOR DENNE KUNDE</a>
            </footer>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<style scoped>
.tw-scroll-minimal {
  scrollbar-color: #4A5568 transparent;
  scrollbar-width: thin;
}
.pos-product-box {
  border: 0.5rem solid transparent;
  cursor: pointer;
}
.pos-product-box.is-selected {
  border: 0.5rem solid #3273dc;
}
</style>