import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'productsMixin',
  data() {
    return {
      filters: {},
      productFilters: [],
      salesTypesIds: [],
      externalLinkBase: '',
      externalLinkOpenMethod: '',
    }
  },
  computed: {
    ...mapGetters('eshop', [
      'getProducts',
      'getProductTotal',
      'getProductSortOrder',
      'getCartProductQuantity',
      'getProductSortOrder',
      'getProductsPerPage',
      'getProductSearchName',
      'getCartTotal',
      'isShowRetailPrice',
    ]),
    ...mapGetters(['getAppLocationCountry', 'getPagination', 'isLoading', 'getLayoutMode', 'isLoggedInGuest']),
    getCategoryId() {
      let params = {}
      window.location.search.replace(/[?&]+([^=&]+)=([^&!/]*)/gi, function(str, key, value) {
        params[key] = value
      })
      let selectedCategory = this.$helpers.getValue(this.filters, 'selectedCategory')
      let urlCategory = this.$helpers.getValue(params, 'category_id')
      if (urlCategory) {
        selectedCategory = urlCategory
      }
      return selectedCategory
    },
  },
  mounted() {
    this.externalLinkBase = process.env.VUE_APP_THIRDPARTY_PRODUCT_DISPLAY_LINK || false
    this.externalLinkOpenMethod = process.env.VUE_APP_THIRDPARTY_PRODUCT_DISPLAY_LINK_METHOD || false
  },
  methods: {
    ...mapActions('eshop', ['loadProducts']),
    async loadProductList() {
      // wait for nextTick allow pagination mutation to complete
      this.$nextTick(async () => {
        await this.loadProducts({
          identifier: 'byDzyne-products',
          name: this.filters.search,
          countryId: this.getAppLocationCountry.countryId,
          locationId: this.getAppLocationCountry.locationId,
          sortOrder: this.filters.selectedSort,
          categoryIds: this.getCategoryId ? [this.getCategoryId] : [],
          salesTypesIds: this.salesTypesIds,
          filters: this.productFilters,
          ek_smart: false,
          is_rp: this.isShowRetailPrice,
          pagination: {
            limit:
              !this.filters.resetPage && this.getPagination('byDzyne-products')
                ? this.getPagination('byDzyne-products').limit
                : 12,
            offset:
              !this.filters.resetPage && this.getPagination('byDzyne-products')
                ? this.getPagination('byDzyne-products').offset
                : 0,
          },
        })
        // Remove resetPage after every request
        delete this.filters['resetPage']
      })
    },
    clearSearchText() {
      this.loadProductList()
    },
    searchProduct() {
      this.loadProductList()
    },
  },
}
