import _ from 'lodash'
import querystring from 'querystring'
import { get, post } from '@/store/utils/api'
import * as T from '@/store/utils/types'
import * as U from '@/store/utils/apiUrls'

export const setSalesVoucherToRedeem = ({ commit }, data) => {
  commit(T.SET_SALES_VOUCHER_TO_REDEEM, data)
}

export const setSelectedProduct = ({ commit }, data) => {
  commit(T.SET_SALES_VOUCHER_SELECTED_PRODUCT, data)
}

export const setSelectedVoucher = ({ commit }, data) => {
  commit(T.SET_SALES_VOUCHER_SELECTED_VOUCHER, data)
}

export const selectEvoucherProductsSizes = ({ commit }, payload) => {
  commit(T.SET_EVOUCHER_PRODUCT_DUMMY, payload)
}

export const setShowRedemptionModal = ({ commit }, data) => {
  commit(T.SET_SHOW_EVOUCHER_REDEMPTION_MODAL, data)
}

export const setSearchText = ({ commit }, data) => {
  commit(T.SET_ORDER_HISTORY_SEARCH_TEXT, data)
}

export const setEkSmartSearchText = ({ commit }, data) => {
  commit(T.SET_EK_SMART_ORDER_HISTORY_SEARCH_TEXT, data)
}

export const retrieveApplicationForm = ({ commit }, query) => {
  return post(U.DOWNLOAD_SALES_APPLICATION_FORM, query)
    .then(response => {
      commit(T.SET_SALES_APPLICATION_FORM_LINK, response.data)
    })
    .catch(error => {
      alert(error)
      return false
    })
}

export const loadBonusAdjustmentList = ({ commit }, payload) => {
  commit(T.PROCESSING_STARTED, 'loadingBonusAdjustmentList', { root: true })
  let query = '?' + querystring.stringify(_.pickBy(payload, _.identity))

  return get(U.MEMBER_BONUS_MANUAL_ADJUSTMENT + query)
    .then(response => response.data)
    .catch(() => false)
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingBonusAdjustmentList', { root: true })
    })
}
