<template>
  <v-container>
    <v-overlay :value="cartProductsProgress" :opacity="0.2">
      <v-container>
        <v-row>
          <v-col cols="12" class="d-flex justify-center align-center">
            <v-progress-circular
              indeterminate
              size="80"
              color="primary"
              align="center"
              justify="center"
            ></v-progress-circular>
          </v-col>
        </v-row>
      </v-container>
    </v-overlay>
    <div v-show="!cartProductsProgress">
      <v-row><v-col cols="12" sm="12" md="12">
        <v-col cols="12" sm="12" md="8">
              <v-menu offset-y down allow-overflow >
                <template v-slot:activator="{ on }">
                  <v-text-field
                    prepend-inner-icon="mdi-magnify"
                    placeholder="Enter Item, Name, Keyword"
                    v-model="searchData"
                    v-on="on"
                    @input="searchProducts"
                  >
                  </v-text-field>
                </template>
                <div>
                  <v-card tile flat v-if="searchData">
                    <RetailerSearchProducts />
                  </v-card>
                </div>
              </v-menu>
            </v-col>
            </v-col>
</v-row>
      <v-row v-show="cartProductsItem.length == 0">
        <v-col>
          <v-alert class="alert-box-outline" type="error" text dense
            >You have no items in your shopping cart.</v-alert
          >
        <!--  <p>
            Click
            <span
              class="
                mr-1
                text-decoration-none
                fontcolor-black-light
                fontsize-16
                guest-shipping-address-login
              "
            >
              <span @click="goToShopping()" class="cursor-pointer"
                >here</span
              > </span
            >to continue shopping.
          </p>-->
        </v-col>
      </v-row>

      <div v-show="cartProductsItem.length != 0">
        <v-row  >
          <v-col cols="12" sm="12" md="8">
            
            <v-col cols="12">
              <p
                class="h3   body-font text-uppercase primary--text"
                v-if="!cartProductsProgress"
              >
                Your Cart ( {{ cartProductsItem.length }} )
              </p>
            </v-col>
            <v-divider class="hidden-md-and-up"></v-divider>
            <v-row>
              <v-col cols="12" sm="12" md="12" class="mt-5">
                <CartProductList
                  :checkOut="chekoutFlag"
                  :cartItems="cartProductsItem"
                  :cartProductsProgress="cartProductsProgress"
                  :cartProductPage="cartProductPage"
                  @actionClose="showSnackBarMessage"
                />
              </v-col>
            </v-row>
          </v-col>
          <v-col cols="12" sm="12" md="4" class="pb-0 mb-0">
            <v-row>
              <v-col cols="12">
                <p class="pb-0 mb-0 h2 body-font text-uppercase primary--text">
                  Summary
                </p>
                <v-divider class="primary pb-0 mb-0"></v-divider>
              </v-col>
            </v-row>
            <v-row v-if="!cartTotalAmtProgress && cartProductTotalAmt">
              <v-col cols="12">
                <p class="float-left pb-0 mb-0">Subtotal</p>
                <p class="float-right pb-0 mb-0">
                  ${{ priceFormatter(cartProductTotalAmt.baseSubtotal) }}
                </p>
              </v-col>

              <v-col cols="12">
                <p class="float-left pb-0 mb-0">Shipping</p>
                <p class="float-right pb-0 mb-0">
                  ${{ priceFormatter(cartProductTotalAmt.baseShippingAmount) }}
                </p>
              </v-col>
              <v-col
                v-if="stockFlag"
                cols="12"
                align="center"
                class="px-10 my-6"
              >
                <v-hover v-slot:default="{ hover }">
                  <v-btn
                    tile
                    large
                    block
                    class="d-sm-none d-md-block cart-products-button"
                    :outlined="hover"
                    :color="hover ? 'white' : 'primary'"
                    :class="hover ? 'primary--text' : 'white--text'"
                    dark
                    depressed
                    @click="goToCheckout()"
                    >GO TO CHECKOUT</v-btn
                  >
                </v-hover>
                <v-hover v-slot:default="{ hover }">
                  <v-btn
                    tile
                    large
                    class="
                      d-none d-sm-flex d-md-none
                      px-12
                      cart-products-button
                    "
                    :outlined="hover"
                    :color="hover ? 'white' : 'primary'"
                    :class="hover ? 'primary--text' : 'white--text'"
                    dark
                    depressed
                    @click="goToCheckout()"
                    >GO TO CHECKOUT</v-btn
                  >
                </v-hover>
              </v-col>
              <!--<v-col cols="12" align="center">
            <v-col cols="7" sm="3" md="7" class="pt-0">
              <v-img
                class="cursor-pointer"
                @click="payPalPayment()"
                :src="require('@/assets/pay-with-paypal.png')"
              ></v-img>
            </v-col>
              </v-col>-->
            </v-row>
            <v-row v-else>
              <v-col cols="12" class="d-flex justify-center align-center">
                <v-progress-circular
                  indeterminate
                  size="80"
                  color="primary"
                  align="center"
                  justify="center"
                ></v-progress-circular>
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </div>
    </div>
    <SnackbarComponent :snackbar="snackbar"></SnackbarComponent>
  </v-container>
</template>
<script>
/* eslint-disable no-alert, no-console ,  no-debugger */
const baseUrl = process.env.VUE_APP_BASE_URL;
import CartProductList from "@/components/retailer/cart-product/CartProductList";
import RetailerSearchProducts from "@/components/retailer/retailer-search/RetailerSearchProducts";

import SnackbarComponent from "@/components/common/SnackbarComponent";
import { getCookieByName } from "@/services/auth";
import { priceFormatter } from "@/services/util.service";
export default {
  name: "CartProducts",
  data: () => ({
    searchData: null,
    priceFormatter: priceFormatter,
    stockFlag: true,
    cartProductPage: true,
    errorMessage: false,
    estimatedShipping: "",
    blue: "primary",
    white: "white",
    dialog: false,
    chekoutFlag: true,
    discountTextCode: "",
    lazy: false,
    textRules: [(v) => !!v || "This field is required"],
    snackbar: {
      show: false,
      message: null,
      color: null,
      timeout: 0,
    },
  }),
  components: {
    CartProductList,
    SnackbarComponent,
    RetailerSearchProducts,
  },
  computed: {
    canonical: function () {
      return this.$route.meta.canonical;
    },
    isDesktop: function () {
      return this.$vuetify.breakpoint.smAndDown ? true : false;
    },
    userAuth: function () {
      return this.$store.state.auth.userAuth;
    },
    guestQuoteId: function () {
      return getCookieByName("cr_guestQuoteId");
    },
    cartProductsItem() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductList;
      } else {
        return this.$store.state.cartProduct.cartProductList;
      }
    },
    cartProductTotalAmt() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.productTotalAmt;
      } else {
        return this.$store.state.cartProduct.productTotalAmt;
      }
    },
    cartTotalAmtProgress() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartTotalAmtProgress;
      } else {
        return this.$store.state.cartProduct.cartTotalAmtProgress;
      }
    },

    cartProductsProgress: function () {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductsProgress;
      } else {
        return this.$store.state.cartProduct.cartProductsProgress;
      }
    },
    
  },
  metaInfo() {
    return {
      title: "Shopping Cart",
      meta: [
        { name: "title", content: "Shopping Cart" },
        { name: "keywords", content: "Magento, Varien, E-commerce" },
        { name: "viewport", content: "width=device-width, initial-scale=1" },
        { name: "robots", content: "INDEX,FOLLOW" },
        { name: "format-detection", content: "telephone=no" },
      ],
      link: [
        {
          rel: "canonical",
          href: `${
            this.canonical ? window.location.href.split("?")[0] : baseUrl
          }`,
        },
      ],
    };
  },
  watch: {
    
    cartProductsItem() {
      this.stockFlagHideShow();
      this.calledCriteoViewBasket();
    },
  },
  methods: {
    calledCriteoViewBasket() {
      if (this.userAuth) {
        this.$store.dispatch("userCartProduct/setCriteoViewBasket");
      } else {
        if (this.guestQuoteId) {
          this.$store.dispatch("cartProduct/setCriteoViewBasket");
        }
      }
    },
    removeMinus(val) {
      if (val) return val.toString().substring(1);
    },
    showSnackBarMessage(obj) {
      this.snackbar = {
        show: obj.show,
        message: obj.message,
        color: obj.color,
        timeout: obj.timeout,
      };
    },
    stockFlagHideShow() {
      if (this.cartProductsItem) {
        let errorCount = 0;
        let i;
        for (i = 0; i < this.cartProductsItem.length; i++) {
          if (
            (!this.cartProductsItem[i].stockDetails.isInStock ||
              this.cartProductsItem[i].stockDetails.qty <
                this.cartProductsItem[i].qty) &&
            this.cartProductsItem[i].stockDetails.manageStock &&
            this.cartProductsItem[i].stockDetails.backorders == 0
          ) {
            errorCount++;
          }
        }
        if (errorCount) {
          this.stockFlag = false;
        } else {
          this.stockFlag = true;
        }
      }
    },
    resetValidation() {},
    goToShopping() {
      this.$router.push({
        name: "HomePage",
      });
    },
    payPalPayment() {},
    goToCheckout() {
      this.$router.push({
        name: "CheckoutPage",
        params: {},
      });
    },
    searchProducts() {
      if (this.searchData) {
        this.$store.dispatch("catalogBrowser/search", {
          fullCatalog: window.craneCatalog,
          keywords: this.searchData,
          filters: [],
          pageNumber: 1,
          pageSize: "ALL",
          sortBy: "relevance",
        });
      }
    },
  },

  created() {
    this.$store.dispatch("catalogBrowser/index", {
      productsCatalog: window.craneCatalog.products,
    });
    if (this.userAuth) {
      this.$store.dispatch("userCartProduct/fetchCartCoupon");

      this.calledCriteoViewBasket();
    }
    this.stockFlagHideShow();
  },
};
</script>
<style src="./cart_products.scss" lang="scss" scoped />