<template>
  <div>
    <v-navigation-drawer
      v-model="cartDrawer"
      v-if="cartDrawer"
      :width="!isDesktop ? defaultWidth : productListWidth"
      absolute
      right
      color="#ffffff"
      class="headerpage-cart-drawer"
      :height="!cartProductsItem.length == 0 ? sideBarHeight(): cartProductsProgress || inProgress ? sideBarHeight() : defaultHeight"
      v-resize="resizeCart"
      v-click-outside="outside"
      
    >
      <v-row class="px-4"  @click="stopPropogation" >
        <v-col cols="7">
          <h2 class="black--text mt-3">Shopping Cart</h2>
        </v-col>
        <v-col cols="5" justify="center">
          <v-hover v-slot:default="{ hover }">
            <v-btn
              large
              tile
              class="float-right mt-2"
              :outlined="hover"
              :color="hover?'white':'primary'"
              :class="hover?'primary--text header-closedrawer-button':'white--text'"
              depressed
              @click.stop="closeCartDrawer(false)"
            >
              CLOSE
              <v-icon :class="hover?'primary--text':'white--text'" class="h3">mdi mdi-close</v-icon>
            </v-btn>
          </v-hover>
        </v-col>
      </v-row>
      <v-row v-show="cartProductsProgress || inProgress">
        <v-col 
          class="mt-12"
          align="center"
          justify="center"
        >
          <v-progress-circular :size="80" color="primary" indeterminate></v-progress-circular>
        </v-col>
     </v-row>
        <div v-show="!cartProductsProgress && !inProgress" @click="stopPropogation" >
          <div v-show="cartProductsItem.length == 0" ref="defaultMsgDiv">
            <v-row>
              <v-col class="text-center pt-8">
            <p class="black--text pb-0 mb-0 font-weight-medium">You have no items in your shopping cart.</p>
            </v-col>
            </v-row>
          </div>
          <div v-show="cartProductsItem.length !== 0">
            <div ref="checkoutButtonDiv">
          <v-row class="px-4 my-3"  v-if="stockFlag">
            <v-col cols="7">
              <p
                :class="isScrolled? '':'black--text'"
              >{{cartProductsItem.length}} Items</p>
            </v-col>
            <v-col cols="5" align="right">
              <p class="black--text mb-0">Cart Subtotal</p>
              <h2 :class="isScrolled? '':'black--text'">${{priceFormatter(cartProductTotalAmt.subtotal)}}</h2>
            </v-col>
          </v-row>
          <v-row class="px-4" v-if="stockFlag">
            <v-col cols="12">
              <v-hover v-slot:default="{ hover }">
                <v-btn
                  tile
                  large
                  block
                  dark
                  :outlined="hover"
                  :color="hover?'white':'primary'"
                  :class="hover?'primary--text':'white--text'"
                  class="header-checkoutpage-button"
                  depressed
                  @click="goToCheckout()"
                >GO TO CHECKOUT</v-btn>
              </v-hover>
            </v-col>
          </v-row>
            </div>
          <v-list class="headerpage-cart-list mb-6" :height="productListHeight()">
            <v-list-item>
              <v-col class="overflow-y-scroll">
                <CartProductList
                  @actionClose="showSnackBarMessage"
                  :checkOut="chekoutFlag"
                  :cartProductsProgress="cartProductsProgress"
                  @actionEditMessage="showMessageOnPage"
                  @stockFlag="stockFlagHideShow"
                />
              </v-col>
            </v-list-item>
          </v-list>
        </div>
        </div>
    </v-navigation-drawer>
  </div>
</template>

<script>
import CartProductList from "@/components/retailer/cart-product/CartProductList";
import {  priceFormatter } from "@/services/util.service";
export default {
  name: "NavigationDrawerComponent",
  components: {
    CartProductList
  },
  props: [],
  data: () => ({
    priceFormatter: priceFormatter,
    defaultWidth: 400,
    chekoutFlag: true,
    stockFlag:true
  }),
  computed: {
    isDesktop: function() {
      return this.$vuetify.breakpoint.xsOnly ? true : false;
    },
    productListWidth() {
      return window.innerHeight;
    },
    defaultHeight: function() {
      if (this.isDesktop) {
        return window.innerHeight;
      } else {
        return "200";
      }
    },
    userAuth: function() {
      return this.$store.state.auth.userAuth;
    },
     
    cartDrawer: {
      get() {
        if (this.userAuth) {
          return this.$store.state.userCartProduct.cartDrawer;
        } else {
          return ''
        }
      },
      set() {}
    },
    cartProductsProgress: function() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductsProgress;
      } else {
        return ''
      }
    },
     inProgress: function() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.inProgress;
      } else {
         return ''
      }
    },
    cartTotalAmtProgress() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartTotalAmtProgress;
      } else {
        return this.$store.state.cartProduct.cartTotalAmtProgress;
      }
    },
    cartProductsItem() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductList;
      } else {
        return '';
      }
    },
    cartProductTotalAmt() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.productTotalAmt;
      } else {
        return ''
      }
    },
   
  },
  watch: {
    cartProductsItem(){
      this.stockFlagHideShow();
    }
  },
  methods: {
    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;
        }
      }
    },
    showMessageOnPage(){
    this.$emit("actionPageMessage");
    },
    goToCheckout() {
      if (this.userAuth) {
        this.$store.dispatch("userCartProduct/cartDrawer", false);
      }  
      let pagePath = this.$route.path;
      let isGateModulePage = pagePath.includes("/gate/");
      if (isGateModulePage) {
        window.open("/checkout", "_self");
      } else {
        this.$router.push({
          name: "CheckoutPage",
          params: {}
        });
      }
    },
       isScrolled: function() {
      let pagePath = this.$route.path;
      let isGateModulePage = pagePath.includes("/gate/");
      if (isGateModulePage) {
        return this.offsetTop > 30 ? true : false;
      }
      if (!this.heroData) return true;

      return this.offsetTop > 30 ? true : false;
    },
       showSnackBarMessage(obj) {
        this.$emit("actionShowMessage", obj);
    },
    outside() {
      //console.log("clicked outside!");
      // this.cartDrawer=false;
       if (this.userAuth) {
        this.$store.dispatch("userCartProduct/cartDrawer", false);
      }  
    },
    stopPropogation(event) {
      event.stopPropagation();
    },
    closeCartDrawer(flag) {
      if (this.userAuth) {
        this.$store.dispatch("userCartProduct/cartDrawer", flag);
      }  
    },
    resizeCart() {
      return this.sideBarHeight() && this.productListHeight();
    },
    productListHeight() {
      return window.innerHeight - 250;
     /* let headerDiv = this.$refs.headerDiv?this.$refs.headerDiv.clientHeight:0;
      let defaultMsgDiv  = this.$refs.defaultMsgDiv?this.$refs.defaultMsgDiv.clientHeight:0;
      let checkoutButtonDiv  = this.$refs.checkoutButtonDiv?this.$refs.checkoutButtonDiv.clientHeight:0;
      return window.innerHeight - (headerDiv+defaultMsgDiv+checkoutButtonDiv);*/
    },
    sideBarHeight() {
      return window.innerHeight;
    },
    pageName() {
      return this.$route.name;
    },

    goToLogout() {
      //  localStorage.removeItem("cr_userQuoteId", null);
      this.$store.dispatch("auth/logout");
      // window.open("/gate/sign-in", "_self");
    },
    goToLogin() {
      window.open("/gate/sign-in", "_self");
    }
  },
  directives: {
    "click-outside": {
      bind: function(el, binding, vNode) {
        // Provided expression must evaluate to a function.
        if (typeof binding.value !== "function") {
          const compName = vNode.context.name;
          let warn = `[Vue-click-outside:] provided expression '${binding.expression}' is not a function, but has to be`;
          if (compName) {
            warn += `Found in component '${compName}'`;
          }

          console.warn(warn);
        }
        // Define Handler and cache it on the element
        const bubble = binding.modifiers.bubble;
        const handler = e => {
          if (bubble || (!el.contains(e.target) && el !== e.target)) {
            binding.value(e);
          }
        };
        el.__vueClickOutside__ = handler;
        // add Event Listeners
        document.addEventListener("click", handler);
      },
      unbind: function(el, binding) {
        console.warn(binding);
        // Remove Event Listeners
        document.removeEventListener("click", el.__vueClickOutside__);
        el.__vueClickOutside__ = null;
      }
    }
  },
  created() {
    this.stockFlagHideShow();
  }
};
</script>

<style src="./NavigationDrawerComponent.scss" lang="scss" scoped/>
