<template>
  <div class="w-100 eshop-header-block">
    <menu-header />
    <b-container class="p-0 eshop-header">
      <div class="d-flex px-1 align-items-center">
        <div class="branding text-left d-none d-md-flex flex-grow-0 justify-content-center">
          <b-img :src="companyLogo" class="mr-2" :class="`icon-size-${($appSettings.evo.enable && '5') || '4'}`" />
        </div>
        <div class="d-flex flex-grow-1 flex-wrap search-bar my-md-3">
          <b-col cols="12" xl="7" class="pt-2">
            <search-bar
              debounce="500"
              class="rounded-1"
              data-list-support
              :value="currentSearchBarValue"
              dropdown-options-class="d-none d-md-block"
              :dropdown-options="getSortedProductMainCategoriesOptions"
              :data-list-call-back="loadAutofillSuggestions"
              @update="updateFilter"
            />
          </b-col>
          <b-col cols="12" xl="5" class="pt-2">
            <b-input-group>
              <b-input-group-text class="bg-white border-left-0 border-y-0 order-for-prepend-text">
                {{ $t('Eshop.Header.OrderFor.Prepend') }}
              </b-input-group-text>
              <eshop-autocomplete
                v-model="downLineSearchText"
                :items="getMemberList"
                :min-len="0"
                :get-label="getLabel"
                :wait="100"
                variant="primary"
                @updateItems="searchMemberListExcludeSelf"
                @item-selected="orderForDownLineSelected"
                :readonly="itemSelected"
                class="flex-grow-1"
                :absolute="false"
                input-class="border-0 h-100 px-2 w-100 text-truncate order-for-auto-complete-input"
                template-name="member"
                ref="downline_search"
                data-qa="eshop-eshop-header-order-for-autoComplete"
              />
              <b-input-group-append>
                <b-button variant="white" class="border-left" @click="orderBtnClick">
                  <icon v-show="itemSelected" class="animated fadeIn" name="eshop-angle-close" />
                  <icon v-show="!itemSelected" class="animated fadeIn" name="angle-down" />
                </b-button>
              </b-input-group-append>
            </b-input-group>
          </b-col>
          <div class="order col-12 col-lg-6 position-relative pr-3 mb-2"></div>
        </div>
        <eshop-cart-btn class="cart d-flex flex-column justify-content-center" v-if="cartBtn" />
      </div>
    </b-container>
  </div>
</template>
<script>
import MenuHeader from './MenuHeader'
import { BRAND_NAME } from '@/config/defaults'
import EshopCartBtn from '../elements/EshopCartBtn'
import { mapRecursiveRouterParam } from '@/elements/common/mixins/recursive-route-param'
import EshopAutocomplete from '@/app/_global/components/elements/EshopAutocomplete'
import { mapActions, mapGetters } from 'vuex'
import _ from 'lodash'
import SearchBar from '@/elements/common/components/SearchBar'

export default {
  name: 'EshopHeader',
  data() {
    return {
      downLineSearchText: '',
      items: [],
      companyLogo: this.$const.constImage.COMPANY_LOGO,
      brandName: BRAND_NAME,
      itemSelected: false,
      searchText: '',
    }
  },
  props: {
    ...mapRecursiveRouterParam({
      cartBtn: {
        default: true,
      },
    }),
  },
  components: {
    SearchBar,
    MenuHeader,
    EshopCartBtn,
    EshopAutocomplete,
  },
  mounted() {
    if (this.getOrderingFor) {
      this.downLineSearchText = _.cloneDeep(this.getOrderingFor.details)
    }
  },
  methods: {
    ...mapActions(['searchMemberListExcludeSelf', 'getSelectedMemberDetail']),
    ...mapActions('eshop', [
      'filterProductsName',
      'orderForDownLine',
      'productChangeCurrentCategory',
      'fetchProductSearchRecommendation',
    ]),
    isCartIconShow: function() {
      let routeLocation = this.$router.resolve(window.location).route.matched.pop()
      if (routeLocation.path === '/eshop/order/review') {
        return false
      }
      return true
    },
    getLabel: function(item) {
      return item ? [[item.country.code, item.user.old_member_id].join(''), [item.name]].join(' ') : ''
    },
    orderForDownLineSelected: function(item) {
      if (item !== null) {
        this.itemSelected = true
        this.getSelectedMemberDetail(item.user_id).then(async () => {
          if (
            this.getOrderingFor === null ||
            this.$helpers.getValue(this.getOrderingFor, 'details.user_id') !==
              this.$helpers.getValue(this.getSelectedMemberDetails, 'details.user_id')
          ) {
            await this.orderForDownLine(this.getSelectedMemberDetails)
            this.navigateToMainListing()
          }
        })
      } else {
        this.itemSelected = false
        if (this.getOrderingFor !== null) {
          this.orderForDownLine(null)
          this.navigateToMainListing()
        }
      }
    },
    orderBtnClick: function() {
      if (this.itemSelected) {
        this.downLineSearchText = ''
        this.searchMemberListExcludeSelf('')
        this.itemSelected = false
        this.orderForDownLine(null)
        this.navigateToMainListing()
      } else {
        this.$refs.downline_search.$el.querySelector('input').focus()
      }
    },
    navigateToMainListing() {
      if (parseInt(this.$route.params.page) !== 1) {
        this.$router.push({ name: 'ListingHomePaginated', params: { page: 1 } })
      }
    },
    updateFilter(payload) {
      let { dropdown: categoryId, input: keyword } = payload

      if (keyword !== this.getProductSearchName) {
        this.filterProductsName(keyword)
      }
      if (categoryId !== this.getProductCurrentCategory) {
        this.productChangeCurrentCategory(categoryId)
      }
    },
    loadAutofillSuggestions(value) {
      let payload = {
        search: value,
        limit: 4,
      }
      return this.fetchProductSearchRecommendation(payload)
    },
  },
  computed: {
    ...mapGetters(['getMemberList', 'getSelectedMemberDetails', 'getLoggedInUser']),
    ...mapGetters('eshop', [
      'getProductSearchName',
      'getOrderingFor',
      'getSortedProductMainCategoriesOptions',
      'getProductCurrentCategory',
    ]),
    currentSearchBarValue() {
      return {
        dropdown: this.getProductCurrentCategory.id,
        input: this.getProductSearchName,
      }
    },
  },
}
</script>
