import Vue from 'vue'
import constants from '@/config/const'
import helpers from '@/helpers'
import appSettings from '@/config/app-settings'

export default {
  getProductSearchName: state => state.searchName,
  getProductSelectedSubCategories: state => state.selectedSubCategories,
  getProducts: state => state.products,
  getProductCurrentCategory: state => state.currentCategory,
  getFilteredPriceRange: state => {
    return state.filterPriceRange
  },
  getFilteredCvRange: state => state.filterCvRange,
  getProductSortOrder: state => state.sortOrder || 2,
  getProductTotal: state => state.totalProducts,
  getProductsPerPage: state => state.productsPerPage,
  getFreeProducts: state => state.freeProducts,
  getMemberKitProducts: state => state.memberKit,
  getSortedProductMainCategoriesOptions: (state, getter) => {
    return getter.getProductMainCategorires.map(category => ({
      text: helpers.getValue(category, 'translated_name.content', category.name),
      value: category.id,
    }))
  },
  getProductMainCategorires: state => {
    let mainCategories = state.categories.filter(category => category.parent_id === 1 && category.for_sales === 1)
    // TODO: remove after backend sorting is applied
    let manualSort = ['health food', 'beauty', 'home appliances', 'fmcg', 'others']

    mainCategories = mainCategories.sort((item1, item2) => {
      let index1 = manualSort.indexOf(item1.name.toLowerCase())
      let index2 = manualSort.indexOf(item2.name.toLowerCase())
      if (index1 > -1 && index2 > -1) {
        return index1 - index2
      } else {
        return mainCategories.length + 1
      }
    })

    return [{ id: null, name: Vue.prototype.$t('Common.AllCategories.Title') }, ...mainCategories]
  },
  getProductSubCategories: state => categoryId => {
    return state.categories.filter(category => category.parent_id !== undefined && category.parent_id === categoryId)
  },
  getProductCurrentSubCategories: (state, getters) => {
    let productCurrentCategory = getters.getProductCurrentCategory
    if (productCurrentCategory) {
      return getters.getProductSubCategories(productCurrentCategory.id)
    } else {
      return []
    }
  },
  getIsEkSmart: state => {
    let isEkSmart = state.filterIsEkSmart
    if (typeof isEkSmart !== 'undefined') {
      return isEkSmart
    } else {
      0
    }
  },
  getFilteredSalesTypes: (state, getters, rootState, rootGetters) => {
    if (state.filterSalesTypeIds.length === 0) {
      if (
        rootGetters.getMemberEnrollmentRank !== undefined &&
        Object.keys(rootGetters.getMemberEnrollmentRank).length > 0 &&
        rootGetters.getMemberEnrollmentRank.sales_types !== undefined
      ) {
        return rootGetters
          .getMasterDataKeysByKeysTitles(
            constants.masterKey.SALE_TYPES,
            rootGetters.getMemberEnrollmentRank.sales_types.values
          )
          .filter(
            typeObject =>
              typeObject.id ===
              helpers.getValue(
                rootGetters.getMasterDataKeysByKeysTitles(constants.masterKey.SALE_TYPES, [
                  constants.masterData.AUTO_MAINTENANCE,
                ])[0],
                'id'
              )
          )
          .map(typeObject => typeObject.id)
      }
    } else {
      return state.filterSalesTypeIds
    }
  },
  getBaSalesTypeId: (state, getters, rootState, rootGetters) => {
    let baUpgradeType = rootGetters.getMasterDataKeysByKeysTitles('sale_types', ['BA Upgrade'])
    if (baUpgradeType.length !== 0) {
      return baUpgradeType[0].id
    } else {
      false
    }
  },
  getProductMainCategoriresOptions: state => {
    let mainCategoriesOptions = [{ value: null, text: Vue.prototype.$t('Common.AllCategories.Title') }]
    for (var i in state.categories) {
      if (
        typeof state.categories[i].parent_id !== 'undefined' &&
        state.categories[i].parent_id === 1 &&
        state.categories[i].for_sales === 1
      ) {
        mainCategoriesOptions.push({ value: state.categories[i].id, text: state.categories[i].name })
      }
    }
    return mainCategoriesOptions
  },
  getProductOrKittingById: state => (productId, kittingId) => {
    let product = state.products.find(function(item) {
      if (
        (item.product_id !== '' && item.product_id !== null && item.product_id === productId) ||
        (item.kitting_id !== '' && item.kitting_id !== null && item.kitting_id === kittingId)
      ) {
        return true
      }
    })
    return product
  },
  getProductUserEligibleSalesTypeId: (state, getters, rootState, rootGetters) => (productId, kittingId) => {
    let product = getters.getProductOrKittingById(productId, kittingId)
    let baId = rootGetters.getBaSalesTypeId
    let selectedTypes = getters.getFilteredSalesTypes
    if (
      selectedTypes !== undefined &&
      selectedTypes.includes(baId) &&
      product.sales_types.find(type => type.id === baId)
    ) {
      return baId
    } else {
      let selectedType = product.sales_types.find(
        type => selectedTypes !== undefined && selectedTypes.includes(type.id)
      )
      if (typeof selectedType !== 'undefined') {
        return selectedType.id
      } else {
        return false
      }
    }
  },
  getProductOrKittingDetails: state => (productId = null, kittingId = null) => {
    return state.productDetails.find(product => {
      if ((productId && product.product_id === productId) || (kittingId && product.kitting_id === kittingId)) {
        return true
      }
    })
  },
  getProductOrKittingDummies: (state, getters) => (productId = null, kittingId = null, productProvided = null) => {
    let product = null
    if (productProvided !== null) {
      product = {
        details: productProvided,
      }
    } else {
      product = productProvided || getters.getProductOrKittingDetails(productId, kittingId)
    }
    let dummies = []
    if (typeof product !== 'undefined') {
      if (typeof product.details.product_id !== 'undefined' && product.details.dummy !== 'undefined') {
        dummies.push({
          ...product.details.dummy,
          quantity: product.details.quantity || 1,
          product_id: product.details.product_id,
          kitting_id: null,
          is_dummy: true,
          is_foc: false,
        })
      } else if (typeof product.details.kitting_id !== 'undefined') {
        product.details.kitting_products.forEach(kittingProduct => {
          if (kittingProduct.product.is_dummy_code === 1 && kittingProduct.dummy !== null) {
            dummies.push({
              ...kittingProduct.dummy,
              quantity: kittingProduct.quantity !== 0 ? kittingProduct.quantity : kittingProduct.foc_qty,
              product_id: kittingProduct.product_id,
              kitting_id: product.details.kitting_id,
              is_dummy: true,
              is_foc: kittingProduct.foc_qty !== 0,
            })
          } else {
            // Non dummy product just for display
            dummies.push({
              ...kittingProduct.dummy,
              name: kittingProduct.product.name,
              sku: kittingProduct.product.sku,
              quantity: kittingProduct.quantity !== 0 ? kittingProduct.quantity : kittingProduct.foc_qty,
              product_id: kittingProduct.product_id,
              kitting_id: product.details.kitting_id,
              is_dummy: false,
              is_foc: kittingProduct.foc_qty !== 0,
            })
          }
        })
      }
    }
    return dummies
  },
  isProductFree: state => product => {
    return product.filters !== undefined
      ? product.filters.includes('free_items') ||
          (product.filters.includes('member_subscription_item') && product.total_price <= 0)
      : false
  },
  isMemberKit: state => product => {
    return product.filters !== undefined ? product.filters.includes('member_kit') : false
  },
  getAvailableFilters: state => {
    return state.availableFilters
  },
  isShowRetailPrice: state => {
    return appSettings.retailPrice.enable ? state.isRetailPrice : false
  },
}
