 <template>
  <v-app-bar
    :clipped-left="$vuetify.breakpoint.mdAndUp"
    app
    color="header-background-color darken-3"
    dark
  >
    <v-col class="d-flex justify-start pa-0">
      <v-app-bar-nav-icon @click="menuAction()" class="header-buttons" />
      <v-img
        class="ml-md-2 cursor-pointer d-none d-md-flex d-lg-flex"
        @click="goTohomePage()"
        src="@/assets/Crane_Logo_white.png"
        max-height="45"
        max-width="100"
        contain
      ></v-img>
    </v-col>
 
    <v-col class="d-flex justify-center">
      <v-img
        class="ml-md-2 cursor-pointer d-md-none d-lg-none"
        @click="goTohomePage()"
        src="@/assets/Crane_Logo_white.png"
        max-height="45"
        max-width="100"
        contain
      ></v-img>
      <!-- <div
        v-for="(categories, index) in categoryList.childrenData"
        v-bind:key="index"
      >
        <v-toolbar-items
          class="white--text d-none d-md-flex"
          v-if="index === 0"
        >
          <v-menu
            open-on-hover
            down
            offset-y
            allow-overflow
            content-class="pt-4 header-menu-content"
            v-for="(category, index) in categories.childrenData"
            v-bind:key="index"
            v-show="category.isActive"
          >
            <template v-slot:activator="{ on }">
              <div
                v-if="
                  category.name !== 'Baby' &&
                  category.name !== 'Gifts' &&
                  category.isActive
                "
                text
                class="cursor-pointer text-uppercase my-auto body pa-0 d-inline-block px-sm-2 ls-n01 px-lg-4 menu-nav-link custom-menu"
                v-on="on"
                :class="
                  category.id == activeCategoryMenu &&
                  pageName() == 'CategoryPage'
                    ? 'meheader-category-text-active'
                    : 'meheader-category-text'
                "
                @click="categoryProducts(category.id, category)"
              >
                {{ category.name }}
              </div>
            </template>
            <v-col v-if="category.childrenData != ''">
              <SubMenu
                :subCategoryList="category"
                @action="inactiveCategoryMenu"
                :mainMenu="category.id"
                :subMenuItem="subMenuItem"
              />
            </v-col>
          </v-menu>
        </v-toolbar-items>
      </div> -->
    </v-col>

    <v-col class="d-flex justify-end pr-0">
      <!-- <v-btn icon @click="goToShopping()">
      <v-icon>mdi-shopping-outline</v-icon>
      </v-btn> -->
      <div class="mt-3 mr-5 d-none d-md-block">
        <v-menu offset-y v-if="userAuth">
          <template v-slot:activator="{ on, attrs }">
            <div color="primary" >
              <span  v-bind="attrs" v-on="on" class="text-uppercase cursor-pointer" >  Welcome,</span>
              <span class="text-uppercase cursor-pointer pl-2">{{ userName}}</span>
            </div>
           
          </template>
          <v-list class="pr-10  d-none d-md-block">
            <v-list-item  class="pr-10">
              <v-list-item-title
                @click="goTohomePage()"
                class="cursor-pointer meheader-category-text"
                >Retailer Portal</v-list-item-title
              >
            </v-list-item>
            <v-list-item >
              <v-list-item-title
                @click="goToAddressBook()"
                class="cursor-pointer meheader-category-text"
                >Address Book</v-list-item-title
              >
            </v-list-item>
            <v-list-item> 
              <v-list-item-title
                @click="goToLogout()"
                class="cursor-pointer meheader-category-text"
                >Logout</v-list-item-title
              >
            </v-list-item>
          </v-list>
        </v-menu>
      </div>

      <v-btn
        icon
        class="header-buttons"
        @click="goToLogout()"
        :max-width="$vuetify.breakpoint.mdOnly ? '35px' : ''"
      >
        <v-icon>mdi-logout</v-icon>
      </v-btn>
      <!-- <v-btn
        icon
        @click="showSearchInput = true"
        class="d-none d-md-block header-buttons"
        :max-width="$vuetify.breakpoint.mdOnly ? '35px' : ''"
      >
        <v-icon class="header-action-icons">mdi-magnify</v-icon>
      </v-btn> -->
      <v-btn
        icon
        class="header-buttons"
        @click="goToCartProducts()"
        :max-width="$vuetify.breakpoint.mdOnly ? '35px' : ''"
      >
        <v-icon>mdi-cart-outline</v-icon>
        <span v-if="cartProductsProgress || inProgress">
          <v-progress-circular
            :size="20"
            color="pink"
            :width="2"
            indeterminate
          ></v-progress-circular>
        </span>
        <span v-else>
          <v-badge
            class="mb-4"
            v-show="cartProductsItem.length"
            color="pink"
            :content="cartProductsItem.length"
          ></v-badge>
        </span>
      </v-btn>
      <v-navigation-drawer
        v-model="showSearchInput"
        v-if="showSearchInput"
        absolute
        right
        color="#ffffff"
        :width="searchInputWidth"
        height="64"
      >
        <v-text-field
          v-model="search"
          autofocus
          clearable
          single-line
          label="Search"
          solo
          type="text"
          color="primary"
          class="me-header-search-field black--text"
          @blur="showSearchInput = false"
          v-on:keyup.enter="GotoPage"
        >
          <template v-slot:append>
            <v-icon @click="GotoPage()" class="primary--text"
              >mdi-magnify</v-icon
            >
          </template>
        </v-text-field>
      </v-navigation-drawer>
     
    </v-col>
  </v-app-bar>
</template>
<script>
// import SubMenu from "@/components/layout/sub-menu/SubMenu";
import { doFetchCatelogProducts } from "@/services/product.service";
import {
  customAttributeValueNew,
  googleAanalyticsEventCategory,
  goToCategoryPageRouting,
  getCategoryOne,
} from "@/services/util.service";
import humps from "lodash-humps";

export default {
  name: "Header",
  // components: { SubMenu },

  props: [],
  data: () => ({
    activeCategoryMenu: "",
    searchResultList: [],
    searchInProgress: false,
    lookupCatelog: null,
    showSearchInput: false,
    search: null,
  }),
  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: {
      userName:function(){
      return this.$store.state.accountOne.one.firstname;
     },
    userAuth: function () {
      return this.$store.state.auth.userAuth;
    },
    guestQuoteId: function () {
      return this.$store.state.guestInfo.guestQuoteId;
    },
    categoryList: function () {
      return this.$store.state.headerCategoryList.categoryList;
    },
    cartProductsProgress: function () {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductsProgress;
      } else {
        return this.$store.state.cartProduct.cartProductsProgress;
      }
    },
    subMenuItem: {
      get: function () {
        return this.$store.state.headerCategoryList.categoryId;
      },
      set: function () {},
    },
    inProgress: function () {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.inProgress;
      } else {
        return this.$store.state.cartProduct.inProgress;
      }
    },
    cartProductsItem() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductList;
      } else {
        return this.$store.state.cartProduct.cartProductList;
      }
    },
    categoryDetailsList: function () {
      return this.$store.state.headerCategoryList.categoryDetails;
    },
    searchInputWidth() {
      return this.$vuetify.breakpoint.xsOnly ? "100%" : "256";
    },
  },
  methods: {
   
    goToAddressBook(){
      return this.$router.push({ name : "AddressBook"})
    },
   
    pageName() {
      return this.$route.name;
    },
    menuAction: function () {
      this.$emit("action");
    },
    goToCartProducts() {
      window.open("/cart-products", "_self");
    },
    goTohomePage() {
      window.open("/", "_self");
    },
    goToLogout() {
      localStorage.removeItem("cr_checkOutTab");
      window.open("/logout-success", "_self");
    },
    getCustomAttributeValue(customAttributes, attributeCode) {
      return customAttributeValueNew(customAttributes, attributeCode);
    },
    GotoPage() {
      if (this.search) {
        this.showSearchInput = false;
        this.searchResultList = [];
        let searchKeywords = this.search;
        let pagePath = this.$route.path;
        let isMeModulePage = pagePath.includes("/retailer/");
        if (isMeModulePage) {
          window.open(
            `/search?pageNumber=1&pageSize=9&sortBy=relevance&q=${searchKeywords}&filter=W10=`,
            "_self"
          );
        } else {
          this.$router
            .push({
              name: "SearchPage",
              query: {
                pageNumber: 1,
                pageSize: 9,
                sortBy: "relevance",
                q: searchKeywords,
                filter: "W10=",
              },
            })
            .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;
      }
    },
    async categoryProducts(categoryId, categoryDetails) {
      if (this.categoryDetailsList) {
        let categoryOne = await getCategoryOne(
          this.categoryDetailsList,
          categoryId
        );
        if (categoryOne) {
          this.$store.dispatch("layout/setHeroContent", categoryOne);
          let path = this.getCustomAttributeValue(categoryOne.ca, "url_path");
          console.log(categoryOne.n, categoryOne);
          this.activeCategoryMenu = categoryId;
          googleAanalyticsEventCategory(
            "browse_category",
            "ecommerce",
            categoryDetails
          );
          localStorage.setItem("cr_mainCategoryId", categoryId);
          localStorage.removeItem("cr_subCategoryItemId");
          localStorage.removeItem("cr_subCategoryId");
          let subMenuItem = "";
          this.$store.dispatch("headerCategoryList/setCategoryId", subMenuItem);
          this.$emit("actionScroll");
          let pagePath = this.$route.path;
          let isMeModulePage = pagePath.includes("/retailer/");
          if (isMeModulePage) {
            window.open(`/${path}`, "_self");
          } else {
            let vm = this;
            goToCategoryPageRouting(vm, categoryOne);
          }
          this.$store
            .dispatch("catalogBrowser/search", {
              fullCatalog: window.craneCatalog,
              keywords: "",
              filters: [{ label: "Category", prop: "ci", value: categoryId }],
              pageNumber: 1,
              pageSize: 9,
              sortBy: "position",
            })
            .catch((error) => {
              error;
            });
        }
      }
    },
    async inactiveCategoryMenu(data) {
      this.activeCategoryMenu = data.mainMenu;
      //this.subMenu = data.subMenu;
      this.$store.dispatch(
        "headerCategoryList/setCategoryId",
        data.subMenuItem
      );
      localStorage.setItem("cr_mainCategoryId", data.mainMenu);
      localStorage.setItem("cr_subCategoryItemId", data.subMenuItem);
      localStorage.setItem("cr_subCategoryId", data.subMenu);
      //let categoryObj = { mainMenu: data.mainMenu, subMenu: data.subMenu };
      //localStorage.setItem("cr_categoryIds", JSON.stringify(categoryObj));
      if (data.subMenuItem) {
        if (this.categoryDetailsList) {
          let categoryOne = await getCategoryOne(
            this.categoryDetailsList,
            data.subMenuItem
          );
          if (categoryOne) {
            this.$store.dispatch("layout/setHeroContent", categoryOne);
            let path = this.getCustomAttributeValue(categoryOne.ca, "url_path");
            console.log(categoryOne.n, categoryOne);
            // const words = path.split("/");
            let pagePath = this.$route.path;
            let isMeModulePage = pagePath.includes("/retailer/");
            if (isMeModulePage) {
              window.open(`/${path}`, "_self");
            } else {
              let vm = this;
              goToCategoryPageRouting(vm, categoryOne);
            }
          }
        }
      }
    },
  },
  created() {},
};
</script>
<style src="./Header.scss" lang="scss" />
