<template>
  <div
    class="gatelayout-background-image"
    ref="divOne"
    v-scroll="onScroll"
    v-resize="OnResize"
  >
    <v-navigation-drawer
      v-model="showMenu"
      v-if="showMenu"
      width="320"
      :app="showMenu"
      :absolute="!showMenu"
      color="primary"
      tile
    >
      <v-icon
        @click.stop="showMenu = !showMenu"
        class="white--text pa-4 pl-4 cursor-pointer"
        >mdi-close</v-icon
      >
      <div class="px-4 pb-3">
      
        <v-text-field
          v-model="search"
          autofocus
          single-line
          type="text"
          color="white"
          class="mobile-header-search-field white--text background-transparent"
          @blur="showSearchInput = false"
          v-on:keyup.enter="GotoPage"
        >
          <template v-slot:prepend>
            <v-icon @click="GotoPage()" class="white--text">mdi-magnify</v-icon>
          </template>
        </v-text-field>
      </div>

      <v-row class="mt-12" justify="center" v-if="inProgress">
        <v-progress-circular
          :size="60"
          color="white"
          indeterminate
        ></v-progress-circular>
      </v-row>
    

      <v-list class="pl-4 mobile-header-list background-transparent">
        <v-list-group v-if="userAuth">
          <template v-slot:activator>
            <v-list-item-content>
              <v-list-item-title class="white--text text-uppercase h3 my-2"
                >Hi {{ userName }}</v-list-item-title
              >
            </v-list-item-content>
          </template>
          <v-list-item>
            <span
              class="white--text text-uppercase h4 my-2"
              @click="goToDashboard()"
              >My Account</span
            >
          </v-list-item>
          <v-list-item>
            <span
              @click="goToLogout()"
              class="white--text text-uppercase h4 my-2"
              >Logout</span
            >
          </v-list-item>
        </v-list-group>
        <v-list-item v-if="!userAuth">
          <v-list-item-content class="pa-0">
            <v-list-item-title
              class="white--text text-uppercase h3 my-2"
              @click="goToLogin()"
              >Sign-In</v-list-item-title
            >
          </v-list-item-content>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>
    <Header
      v-bind:heroData="heroData"
      v-bind:offsetTop="offsetTop"
      @action="onAction"
      @actionScroll="onActionScroll"
    />
    <v-container fill-height class="ios-fill-height py-0">
      <v-row align="center" align-content="center" justify="center">
        <v-col cols="12" sm="8" md="6" class="mr-sm-0">
          <router-view />
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>
<script>
import Header from "@/components/layout/header/Header";
import {
  customAttributeValueNew,
  getCategoryOne,
} from "@/services/util.service";
import { doFetchCatelogProducts } from "@/services/product.service";
import humps from "lodash-humps";
export default {
  name: "GateLayout",
  components: {
    Header,
  },
  data: () => ({
    activeMainMenu: "",
    activeSubMenu: "",
    activeSubMenuItem: "",
    offsetTop: 0,
    showMenu: false,
    heroData: null,
    pageNo: 1,
    pageSize: 9,
    // categoryList: [],
    sortSelect: { label: "Position", value: "position" },
    blockId: "30",
    search: null,
    searchResultList: [],
    lookupCatelog: null,
    searchInProgress: false,
  }),
  watch: {
    lookupCatelog: {
      handler: function (newVal) {
        clearTimeout(this.lookupCatelogProductTimeoutId);
        this.lookupCatelogProductTimeoutId = setTimeout(async () => {
          try {
            if (!newVal) this.searchResultList = [];
            else {
              this.searchInProgress = true;
              let results = await doFetchCatelogProducts(newVal);
              if (results != null) {
                this.searchResultList = humps(results);
              } else {
                this.searchResultList = [];
              }
              this.searchInProgress = false;
            }
          } catch (error) {
            this.searchResultList = [];
          }
        }, 500);
      },
    },
  },
  computed: {
    easingOptions() {
      return {
        duration: this.duration,
        //  offset: this.offset,
        easing: this.easing,
      };
    },
    isDesktop: function () {
      return this.$vuetify.breakpoint.xsOnly ? true : false;
    },
    userAuth: function () {
      return this.$store.state.auth.userAuth;
    },
    
    userName: function () {
      return this.$store.state.accountOne.one.firstname;
    },
    inProgress: function () {
      return this.$store.state.headerCategoryList.inProgress;
    },
    categoryList: {
      get: function () {
        return this.$store.state.headerCategoryList.categoryList;
      },
      set: function () {},
      //return this.$store.state.headerCategoryList.categoryList;
    },
    categoryDetailsList: function () {
      return this.$store.state.headerCategoryList.categoryDetails;
    },
  },
  methods: {
    OnResize() {
      setTimeout(() => {
        if (this.$vuetify.breakpoint.mdAndUp) {
          this.showMenu = false;
        }
      }, 200);
    },
    GotoPage() {
      if (this.search) {
        this.showSearchInput = false;
        this.searchResultList = [];
        let searchKeywords = this.search;
        let pagePath = this.$route.path;
        let isGateModulePage = pagePath.includes("/gate/");
        if (isGateModulePage) {
          window.open(
            `/search?pageNumber=${this.pageNo}&pageSize=${this.pageSize}&sortBy=relevance&q=${searchKeywords}&filter=e30=`,
            "_self"
          );
        } else {
          this.$router
            .push({
              name: "SearchPage",
              query: {
                pageNumber: this.pageNo,
                pageSize: this.pageSize,
                sortBy: "relevance",
                q: searchKeywords,
                filter: "e30=",
              },
            })
            .catch((error) => {
              error;
            });
          this.$store.dispatch("catalogBrowser/search", {
            fullCatalog: window.craneCatalog,
            keywords: searchKeywords,
            filters: [],
            pageNumber: 1,
            pageSize: 9,
            sortBy: "relevance",
          });
        }
        localStorage.removeItem("cr_subCategoryItemId");
        localStorage.removeItem("cr_subCategoryId");
        localStorage.removeItem("cr_mainCategoryId");
        this.search = null;
      }
    },
    onAction(action) {
      this.showMenu = action.showMenu;
      this.categoryList = action.categoryList;
    },
    onActionScroll() {
      if (this.$refs.divOne) {
        this.$vuetify.goTo(this.$refs.divOne, this.easingOptions);
      }
    },
    onScroll() {
      this.offsetTop = window.pageYOffset || document.documentElement.scrollTop;
    },
    goToStoreLocator() {
      // window.open(`/store-locator`, "_self");
    },
    goToLogin() {
      window.open("/gate/sign-in", "_self");
    },
    getCustomAttributeValue(customAttributes, attributeCode) {
      return customAttributeValueNew(customAttributes, attributeCode);
    },
    /* eslint-disable no-alert, no-console ,  no-debugger */
    async categoryProducts(flag, category, subcategorys, items) {
      let mainCat = "";
      switch (flag) {
        case "main":
          mainCat = category;
          localStorage.setItem("cr_mainCategoryId", category);
          localStorage.setItem("cr_subCategoryItemId", items);
          localStorage.setItem("cr_subCategoryId", subcategorys);
          break;
        case "subManu":
          mainCat = subcategorys;
          localStorage.setItem("cr_mainCategoryId", category);
          localStorage.setItem("cr_subCategoryItemId", items);
          localStorage.setItem("cr_subCategoryId", subcategorys);
          break;
        case "subManuChild":
          mainCat = items;
          localStorage.setItem("cr_mainCategoryId", category);
          localStorage.setItem("cr_subCategoryItemId", items);
          localStorage.setItem("cr_subCategoryId", subcategorys);
          break;
        default:
      }
      if (this.categoryDetailsList) {
        let categoryOne = await getCategoryOne(
          this.categoryDetailsList,
          mainCat
        );
        if (categoryOne) {
          this.$store.dispatch("layout/setHeroContent", categoryOne);
          let path = this.getCustomAttributeValue(
            categoryOne.customAttributes,
            "url_path"
          );
         // console.log(categoryOne.name, categoryOne);
          /*googleAanalyticsEventCategory(
            "browse_category",
            "ecommerce",
            categoryOne
          );*/
          let pagePath = this.$route.path;
          let isGateModulePage = pagePath.includes("/gate/");
          if (isGateModulePage) {
            window.open(`/${path}`, "_self");
          }
         this.$store.dispatch("catalogBrowser/search", {
          fullCatalog: window.craneCatalog,
          keywords: "",
          filters: [{ label: "Category", prop: "ci", value: mainCat }],
          pageNumber: 1,
          pageSize: 9,
          sortBy: "position",
        })
        .catch((error) => {
          error;
        });

        }
      }
    },
    goToLogout() {
      this.$store.dispatch("auth/logout");
    },
    goToDashboard() {
      window.open("/b2b", "_self");
    },
  },
  created() {
    if (!this.categoryList.id) {
      this.$store.dispatch("headerCategoryList/fetchCategoryList");
    }

   // this.$store.dispatch("block/fetchHeaderPromoBanner", this.blockId);
    if (this.userAuth) {
      this.$store.dispatch("userCartProduct/cartProductList");
      // this.$store.dispatch("userCartProduct/productTotalAmt");
      this.$store.dispatch("accountOne/basicInfo");
    }
  },
};
</script>
<style lang="scss">
.header-input-custom {
  .v-input__control {
    background-color: transparent !important;
  }
  .v-input__slot {
    &:before {
      border-color: #ffffff !important;
      border-style: solid;
      border-width: 1px;
    }
    &:after {
      border-color: #ffffff !important;
      border-style: solid;
      border-width: 1px;
    }
  }
  .v-text-field__slot {
    input {
      color: #ffffff !important;
      border-bottom-color: #ffffff !important;
    }
    input::placeholder {
      color: #ffffff !important;
    }
    input:-ms-input-placeholder {
      color: #ffffff !important;
    }

    input ::-ms-input-placeholder {
      color: #ffffff !important;
    }
  }
  .v-icon {
    color: #ffffff !important;
  }
  .mobile-header-list.theme--light.v-list {
    background: #2805da;
  }
  .v-list-item__icon {
    color: #ffffff !important;
  }
}
.mobile-header-autocomplete .v-input__append-inner .v-input__icon {
  display: none !important;
}
.mobile-header-autocomplete .theme--light.v-icon {
  color: #ffffff !important;
}
.mobile-header-autocomplete.theme--light.v-input input {
  color: #ffffff !important;
}
.mobile-header-autocomplete.theme--light.v-text-field--filled
  > .v-input__control
  > .v-input__slot {
  background-color: transparent !important;
}
.mobile-header-search-field.theme--light.v-text-field--solo
  > .v-input__control
  > .v-input__slot {
  background-color: transparent !important;
}
.mobile-header-search-field.theme--light.v-input input {
  color: #fff;
}
</style>

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