import { post, get, put } from '../../utils/api'
import * as U from '../../utils/apiUrls'
import * as T from '../../utils/types'
import _ from 'lodash'
import moment from 'moment'
import helpers from '@/helpers'
import appSettings from '@/config/app-settings'
import { IS_LOGGED_IN_GUEST_GETTER_NAME } from '@/config/defaults'
/**
 * Load Sales Payment Modes
 *
 * @param commit
 * @param getters
 * @param dispatch
 * @param {Object} payload
 * @param {int} payload.country_id The country Id, default is selected country id
 * @param {int} payload.location_id The location Id, default is selected locations id
 * @param {string[]} payload.exclude_payment_mode Payment Modes to exclude
 */
export const loadSalesPaymentModes = ({ commit, getters, dispatch }, payload = {}) => {
  commit(T.PROCESSING_STARTED, 'SalesPaymentModes')
  let query = _.defaults(payload, {
    country_id: getters.getAppLocationCountry.countryId,
    location_id: getters.getAppLocationCountry.locationId,
    exclude_payment_mode: [],
    user_id: getters.getPaymentUserId || null,
  })
  return post(U.SALES_PAYMENT_MODES, query)
    .then(response => {
      commit(T.PROCESSING_FINISHED, 'SalesPaymentModes')
      const json = response.data
      commit(T.SALES_SET_PAYMENT_MODES, {
        list: json,
      })
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'SalesPaymentModes')
      dispatch('logError', { SalesPaymentModes: e.data }, { root: true })
    })
}

export const loadOnHoldPaymentOptions = async ({ commit, getters, dispatch, rootGetters }, typesKey) => {
  commit(T.PROCESSING_STARTED, 'SalesNonPaymentModes')
  let payload = {
    country_id: getters.getAppLocationCountry.countryId,
    types: typesKey,
  }
  return await post(U.API_COUNTRY_DYNAMIC_CONTENT_TYPES, payload)
    .then(response => {
      let result = response.data && Object.values(response.data)
      return JSON.parse(result)
    })
    .catch(error => {
      dispatch('logError', { SalesNonPaymentModes: error.data }, { root: true })
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'SalesNonPaymentModes')
    })
}

/**
 * Make payment to sales
 *
 * @param commit
 * @param dispatch
 * @param {Object} query
 * @param {int} query.sale_id // the sale id
 * @param {int} query.payment_mode_id // the payment type used
 * @param {string} query.payment_mode_name // the payment type used
 * @param {string} query.payment_type // the payment type used
 * @return {Object} payment form
 */
export const doSalesPaymentMakePayment = ({ commit, dispatch }, query) => {
  commit(T.PROCESSING_STARTED, 'doSalesPaymentMakePayment')
  return post(U.SALES_PAYMENT_MAKE_PAYMENT, query)
    .then(res => {
      commit(T.SALES_SET_CURRENT_PAYMENT, res.data)
      commit(T.PROCESSING_FINISHED, 'doSalesPaymentMakePayment')
      return res
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'doSalesPaymentMakePayment')
      dispatch('logError', { SalesPaymentModes: e.data }, { root: true })
      throw e
    })
}

/**
 * Make payment to sales
 *
 * @param commit
 * @param dispatch
 * @param {Object} query
 * @param {int} query.sale_id // the sale id
 * @param {int} query.payment_mode_id // the payment type used
 * @param {string} query.payment_mode_name // the payment type used
 * @param {string} query.payment_type // the payment type used
 * @return {Object} payment form
 */
export const doSalesPaymentCrossDomainMakePayment = ({ commit, dispatch }, query) => {
  commit(T.PROCESSING_STARTED, 'doSalesPaymentMakePayment')
  return post(U.SALES_PAYMENT_CROSS_DOMAIN_MAKE_PAYMENT, query)
    .then(res => {
      commit(T.SALES_SET_CURRENT_PAYMENT, res.data)
      commit(T.PROCESSING_FINISHED, 'doSalesPaymentMakePayment')
      return res
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'doSalesPaymentMakePayment')
      dispatch('logError', { SalesPaymentModes: e.data }, { root: true })
      throw e
    })
}

/**
 * Do Sales Creating from Cart
 *
 * @param store
 * @param commit
 * @param dispatch
 * @param getters
 * @param rootGetters
 * @param {object} payload
 * @param {int} payload.country_id
 * @param {int} payload.location_id
 * @param {int} payload.stock_location_id
 * @param {int} payload.sponsor_member_id
 * @param {object} payload.selected
 * @param {object} payload.selected.shipping
 * @param {int} payload.selected.shipping.sales_delivery_method_id
 * @param {int} payload.selected.shipping.self_collection_point_id
 * @param {int} payload.selected.shipping.recipient_name
 * @param {int} payload.selected.shipping.recipient_mobile_phone_number
 * @param {int} payload.selected.shipping.recipient_mobile_country_code_id
 * @param {object[]} payload.selected.shipping.recipient_addresses
 * @param {int} payload.selected.shipping.recipient_selected_shipping_index
 * @return {int|boolean} saleId sales Id when sales is complete, false if no
 */
// eslint-disable-next-line no-unused-vars
export const doSalesCartCreateSale = async ({ store, commit, dispatch, getters, rootGetters }, payload) => {
  let orderForUserId = null
  if (getters.getAppStatus('eshop') === true && getters['eshop/getIsOrderingForDownLine'] === true) {
    orderForUserId = getters['eshop/getOrderingFor'].details.user_id
  }
  let query = _.defaults(payload, {
    country_id: getters.getAppLocationCountry.countryId,
    location_id: getters.getAppLocationCountry.locationId,
    is_paylater: helpers.getValue(getters, 'getOnHoldPaymentMode.is_paylater'),
    is_cash_on_delivery: helpers.getValue(getters, 'getOnHoldPaymentMode.is_cash_on_delivery'),
    stock_location_id: 1, // TODO: get stock location from API
    order_for_user_id: orderForUserId,
    rental_card_detail: { rental_card_data: {} },
  })
  query['selected']['additional_requirements'] = getters['eshop/getCartIsAllDummiesSelectedForSales']
  query['is_rental_sale_order'] = getters['eshop/getCartIsRentalSaleOrder']
  query['is_rental_ha_sales'] = getters['eshop/getHasInstDetails']
  query['rental_installation_detail'] = getters['eshop/getRentalInstDetails']
  query['rental_card_detail']['rental_card_data'] = getters['enrolment/getRentalCardDataPayload']
  query['credit_card_photocopy'] = getters['enrolment/getNRICDocDetails']
  query['income_proof'] = getters['enrolment/getSupportingDocDetails']
  query['ek_smart'] = getters['eshop/getCartIsRentalSaleOrder']
  query['application_form'] = []

  if (appSettings.eshop.order_item.cv_transfer_checkbox === true) {
    query['cv_transfer_list'] = getters['eshop/getCvTransferList']
  }
  if (getters.getAppStatus('enrolment') === true) {
    query['sponsor_member_id'] = helpers.getValue(getters['enrolment/getEnrolForm'], 'sponsor_member_id', null)
    query['enrolment_type_id'] = helpers.getValue(getters['enrolment/getEnrolForm'], 'enrolment_type', null)
  }
  if (
    rootGetters[IS_LOGGED_IN_GUEST_GETTER_NAME] &&
    (rootGetters.getAppStatus('thirdPartyAppsCheckout') === true ||
      rootGetters.getAppStatus('thirdPartyAppsProductList') === true)
  ) {
    let sponsorMemberId = rootGetters['3rdPartyCheckoutEnrolment/getSkipEnrolmentPrivilege']
      ? helpers.getValue(rootGetters['3rdPartyCheckoutEnrolment/getEnrolmentFormData'], 'sponsor_member_id', null)
      : helpers.getValue(rootGetters['3rdPartyCheckoutEnrolment/getEnrolmentInfo'], 'sponsor_member_id', null)

    let enrolmentTypeId = rootGetters['3rdPartyCheckoutEnrolment/getSkipEnrolmentPrivilege']
      ? helpers.getValue(rootGetters['3rdPartyCheckoutEnrolment/getEnrolmentFormData'], 'enrolment_type', null)
      : helpers.getValue(rootGetters['3rdPartyCheckoutMembership/getMembershipInfo'], 'enrolment_type_id', null)

    query['sponsor_member_id'] = sponsorMemberId
    query['enrolment_type_id'] = enrolmentTypeId
    query['is_enrollment_sale'] = !rootGetters['3rdPartyCheckoutEnrolment/getSkipEnrolmentStatus']
    query['is_rp'] = rootGetters['eshop/isShowRetailPrice']
  }
  // Set sale platform either 'eshop' or 'elkenGlobal'
  if (getters.getMasterDataByKey('sale_platform') === undefined) {
    // Call mater data if sales platform master data not found
    await dispatch('loadMasterDataKeys', ['sale_platform'])
  }

  if (rootGetters.getAppStatus('virel') === true) {
    query['is_rp'] = true
  }

  let platform =
    (getters.getAppStatus('eshop') === true && 'eshop') ||
    (getters.getAppStatus('thirdPartyApps') === true && 'elkenglobal') ||
    ''
  if (getters.getMasterDataByKey('sale_platform').find(data => data.key === platform)) {
    query['sale_platform_id'] = getters.getMasterDataByKey('sale_platform').find(data => data.key === platform).id
  }
  if (rootGetters.getAppStatus('eshop') === true && appSettings.evo.enable) {
    query['cw_id'] = rootGetters['eshop/getCartSalesCwId']
  }
  commit(T.PROCESSING_STARTED, 'doSalesCartCreateSale')
  return post(U.SALES_CART_CREATE_SALES, query)
    .then(res => {
      commit(T.SALES_SET_SALE, res.data.sales_data)
      dispatch('setOnHoldPaymentMode', { is_paylater: false, is_cash_on_delivery: false })
      return res.data.sales_data.sale_id
    })
    .catch(e => {
      dispatch('logError', { doSalesCartCreateSale: e.data }, { root: true })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'doSalesCartCreateSale')
    })
}

/**
 * Do Shop Sales Creating
 *
 * @param commit
 * @param dispatch
 * @param getters
 * @param {object} payload
 * @param {int} payload.country_id
 * @param {int} payload.location_id
 * @param {int} payload.stock_location_id
 * @param {int} payload.sponsor_member_id
 * @param {object} payload.selected
 * @param {object} payload.selected.shipping
 * @param {int} payload.selected.shipping.sales_delivery_method_id
 * @param {int} payload.selected.shipping.self_collection_point_id
 * @param {int} payload.selected.shipping.recipient_name
 * @param {int} payload.selected.shipping.recipient_mobile_phone_number
 * @param {int} payload.selected.shipping.recipient_mobile_country_code_id
 * @param {object[]} payload.selected.shipping.recipient_addresses
 * @param {int} payload.selected.shipping.recipient_selected_shipping_index
 * @return {int|boolean} saleId sales Id when sales is complete, false if nto
 */
// eslint-disable-next-line no-unused-vars
export const doShopCreateSale = async ({ store, commit, dispatch, getters }, payload) => {
  let query = _.defaults(payload, {
    country_id: helpers.getValue(getters, 'getSelectedCountry.id'),
    location_id: helpers.getValue(getters, 'getSelectedCountryLocation.id'),
    stock_location_id: 1, // TODO: get stock location from API
  })
  if (query['selected']) {
    query['selected']['additional_requirements'] = getters['eshop/getCartIsAllDummiesSelectedForSales']
  }
  // Set sale platform either 'eshop' or 'elkenGlobal'
  if (getters.getMasterDataByKey('sale_platform') === undefined) {
    // Call mater data if sales platform master data not found
    await dispatch('loadMasterDataKeys', ['sale_platform'])
  }

  let platform =
    (getters.getAppStatus('eshop') === true && 'eshop') ||
    (getters.getAppStatus('thirdPartyApps') === true && 'elkenglobal') ||
    ''
  if (getters.getMasterDataByKey('sale_platform').find(data => data.key === platform)) {
    query['sale_platform_id'] = getters.getMasterDataByKey('sale_platform').find(data => data.key === platform).id
  }
  commit(T.PROCESSING_STARTED, 'doCreateSale')
  return post(U.SALES_SHOP_CREATE_SALES, query)
    .then(res => {
      commit(T.SALES_SET_SALE, res.data.sales_data)
      commit(T.PROCESSING_FINISHED, 'doCreateSale')
      return res.data.sales_data.sale_id
    })
    .catch(e => {
      dispatch('logError', { doSalesCartCreateSale: e.data }, { root: true })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'doCreateSale')
    })
}

/**
 * Check payment status of a given payment, if not the status is checked for the current payment in the store
 *
 * @param store
 * @param commit
 * @param dispatch
 * @param getters
 * @param {int} paymentId
 */
// eslint-disable-next-line no-unused-vars
export const checkPaymentStatus = ({ store, commit, dispatch, getters }, paymentId = null) => {
  commit(T.PROCESSING_STARTED, 'doSalesCartCreateSale')
  paymentId = paymentId || getters.getCurrentPaymentId
  if (paymentId === 0) {
    return Promise.resolve(false)
  }
  return get(`${U.SALES_PAYMENT_CHECK_STATUS}/${paymentId}`)
    .then(res => {
      let status = res.data.status
      commit(T.PROCESSING_FINISHED, 'doSalesCartCreateSale')
      commit(T.SET_PAYMENT_STATUS, status)
      return parseInt(status)
    })
    .catch(e => {
      commit(T.SET_PAYMENT_STATUS, 0)
      dispatch('logError', { doSalesCartCreateSale: e.data }, { root: true })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'doSalesCartCreateSale')
    })
}

/**
 * Load Sales List
 *
 * @param commit
 * @param dispatch
 * @param rootGetters
 */
export const loadSalesList = ({ commit, dispatch, rootGetters }) => {
  commit(T.PROCESSING_STARTED, 'salesListLoading', { root: true })
  dispatch('removeError', 'salesList')
  let toDate = moment(new Date()).format('YYYY-MM-DD')
  let pagination = rootGetters.getPagination('orderhistory') || {
    limit: rootGetters['orderhistory/getOrderHistoryPaginationSize'],
    offset: 0,
  }
  let searchText = rootGetters['orderhistory/getSearchText']
  let isRentalSaleOrder = rootGetters['orderhistory/getIsRentalSaleList']
  let query = {
    to_date: toDate,
    search_text: searchText.doc,
    user_id: searchText.member !== null && searchText.member.user_id !== '' ? searchText.member.user_id : null,
    is_evoucher: 0,
    is_rental_sale_order: isRentalSaleOrder,
    limit: pagination.limit,
    offset: pagination.offset || 0,
  }
  return post(U.SALES_LIST, query)
    .then(response => {
      commit(T.SET_SALES_LIST, response.data.data)
      commit(T.SET_SALES_LIST_TOTAL_ROWS, response.data.total)
      commit(T.PROCESSING_FINISHED, 'salesListLoading', { root: true })
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'salesListLoading', { root: true })
      dispatch('logError', { salesList: error })
    })
}

export const loadEkSmartSalesList = ({ commit, dispatch, rootGetters }, payload = {}) => {
  commit(T.PROCESSING_STARTED, 'ekSmartSalesListLoading', { root: true })
  // Reset Data
  commit(T.SET_EK_SMART_SALES_LIST, [])

  dispatch('removeError', 'salesList')
  let toDate = moment(new Date()).format('YYYY-MM-DD')
  let pagination = rootGetters.getPagination('eksmartorderhistory') || {
    limit: rootGetters['orderhistory/getOrderHistoryPaginationSize'],
    offset: 0,
  }
  let searchText = payload.ekSmartSearchText || rootGetters['orderhistory/getEkSmartSearchText']
  let query = {
    to_date: toDate,
    search_text: searchText.doc,
    user_id: searchText.member.user_id !== '' ? searchText.member.user_id : null,
    is_evoucher: 0,
    is_rental_sale_order: 1,
    limit: pagination.limit,
    offset: pagination.offset || 0,
  }
  return post(U.SALES_LIST, query)
    .then(response => {
      commit(T.SET_EK_SMART_SALES_LIST, response.data.data)
      commit(T.SET_EK_SMART_SALES_LIST_TOTAL_ROWS, response.data.total)
      commit(T.PROCESSING_FINISHED, 'ekSmartSalesListLoading', { root: true })
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'ekSmartSalesListLoading', { root: true })
      dispatch('logError', { salesList: error })
    })
}

export const loadSalesListData = ({ commit, dispatch, rootGetters }, payload) => {
  commit(T.PROCESSING_STARTED, 'salesListLoading', { root: true })
  dispatch('removeError', 'salesList')
  let toDate = moment(new Date()).format('YYYY-MM-DD')
  let pagination = rootGetters.getPagination('orderhistory') || {
    limit: rootGetters['orderhistory/getOrderHistoryPaginationSize'],
    offset: 0,
  }
  let searchText = payload.searchText
  let isRentalSaleOrder = payload.isRentalSaleOrder
  let isRetalRecurring = payload.isRetalRecurring
  let query = {
    to_date: toDate,
    search_text: searchText.doc,
    user_id: searchText.member.user_id !== '' ? searchText.member.user_id : null,
    is_evoucher: 0,
    is_rental_recurring: isRetalRecurring,
    is_rental_sale_order: isRentalSaleOrder,
    limit: pagination.limit,
    offset: pagination.offset || 0,
  }
  return post(U.SALES_LIST, query)
    .then(response => {
      commit(T.SET_SALES_LIST_DATA, response.data.data)
      localStorage.setItem('TEST SALES', response.data.data)
      commit(T.SET_SALES_LIST_DATA_TOTAL_ROWS, response.data.total)
      commit(T.PROCESSING_FINISHED, 'salesListLoading', { root: true })
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'salesListLoading', { root: true })
      dispatch('logError', { salesList: error })
    })
}
export const loadSalesDetailsData = ({ commit, getters, dispatch }, { saleId, forceLoad = false }) => {
  commit(T.PROCESSING_STARTED, 'salesDetailsLoading', { root: true })
  dispatch('removeError', 'salesDetails')
  let load =
    forceLoad ||
    !(
      getters.getAppStatus('enrolment') === true ||
      getters.getAppStatus('thirdPartyAppsCheckout') === true ||
      getters.getAppStatus('thirdPartyAppsResumePayment') === true ||
      (getters.getAppStatus('eshop') === true && getters['eshop/getIsOrderingForDownLine'] === true)
    )
  if (load) {
    return post(U.SALES_DETAILS, { sale_id: saleId })
      .then(response => {
        commit(T.SALES_SET_SALE, response.data.sales_data)
        commit(T.PROCESSING_FINISHED, 'salesDetailsLoading', { root: true })
      })
      .catch(error => {
        dispatch('logError', { salesDetails: error })
        commit(T.PROCESSING_FINISHED, 'salesDetailsLoading', { root: true })
      })
  }
}

// eslint-disable-next-line no-unused-vars
export const loadCreditNotePdf = ({ commit, getters, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'creditNoteLoading')
  return post(U.SALES_CREDIT_NOTE_DOWNLOAD_PDF, { credit_note_id: data.credit_note_id, section: data.section })
    .then(response => {
      commit(T.SET_SALES_CREDIT_NOTE_PDF, response.data.download_link)
      commit(T.PROCESSING_FINISHED, 'creditNoteLoading')
    })
    .catch(error => {
      dispatch('logError', { creditNoteDetails: error })
      commit(T.PROCESSING_FINISHED, 'creditNoteLoading', { root: true })
    })
}

export const checkPaymentModePreOrder = ({ commit }, payload) => {
  if (['aeon', 'epp_moto'].includes(payload.payment_mode_code)) {
    commit(T.SET_SALES_PAYMENT_WILL_PEND, payload.sale_id)
  } else {
    commit(T.SET_SALES_PAYMENT_WILL_PEND, '')
  }
}

export const loadEvoucherBySale = ({ commit, getters, dispatch }) => {
  commit(T.PROCESSING_STARTED, 'evoucherLoading')
  dispatch('removeError', 'evoucherBySale')
  return post(U.EVOUCHER_GET_BY_SALE, { sale_id: getters.getCurrentSaleId, details: true })
    .then(response => {
      commit(T.SET_EVOUCHER_BY_SALE, response.data.data)
      commit(T.PROCESSING_FINISHED, 'evoucherLoading')
    })
    .catch(error => {
      dispatch('logError', { evoucherBySale: error })
      dispatch('clearSaleEvouchers')
      commit(T.PROCESSING_FINISHED, 'evoucherLoading')
    })
}

export const requestEvoucherOTP = ({ commit, getters, dispatch }) => {
  commit(T.PROCESSING_STARTED, 'evoucherOtpRequesting')
  dispatch('removeError', 'evoucherOtpRequest')
  return post(U.EVOUCHER_ACTIVATION, {
    user_id: helpers.getValue(getters, 'getLoggedInUser.id'),
    request_type: 'request',
  })
    .then(response => {
      commit(T.PROCESSING_FINISHED, 'evoucherOtpRequesting')
      return response.data
    })
    .catch(error => {
      dispatch('logError', { evoucherOtpRequest: error })
      commit(T.PROCESSING_FINISHED, 'evoucherOtpRequesting')
      return error.response.data
    })
}

export const activateEvoucher = ({ commit, getters, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'evoucherActivating')
  dispatch('removeError', 'evoucherActivate')
  return post(
    U.EVOUCHER_ACTIVATION,
    _.merge(
      {
        user_id: helpers.getValue(getters, 'getLoggedInUser.id'),
        request_type: 'activate',
      },
      data
    )
  )
    .then(response => {
      commit(T.PROCESSING_FINISHED, 'evoucherActivating')
      return response.data
    })
    .catch(error => {
      dispatch('logError', { evoucherActivate: error })
      commit(T.PROCESSING_FINISHED, 'evoucherActivating')
      return helpers.getValue(error, 'response.data.code[0]') || error.response.data
    })
}

export const redeemEvoucher = ({ commit, getters, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'evoucherRedempting')
  dispatch('removeError', 'evoucherRedeem')
  let query = _.defaults(data, {
    transaction_location_id: helpers.getValue(getters, 'getSelectedCountryLocation.id'),
    stock_location_id: 1,
    remarks: 'evoucher redemption',
    sizes: [],
    addresses: [],
  })
  return put(U.EVOUCHER_REDEEM + '/' + getters['orderhistory/getSalesVoucherToRedeem'], query)
    .then(response => {
      commit(T.PROCESSING_FINISHED, 'evoucherRedempting')
      return response.data
    })
    .catch(error => {
      dispatch('logError', { evoucherRedeem: error })
      commit(T.PROCESSING_FINISHED, 'evoucherRedempting')
      return error.response.data
    })
}

export const loadRedemptionReceipt = ({ commit, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'redemptionReceiptLoading')
  dispatch('removeError', 'redemptionReceipt')
  return get(U.EVOUCHER_RECEIPT + '/' + data)
    .then(response => {
      commit(T.SET_REDEMPTION_RECEIPT, response.data)
      commit(T.PROCESSING_FINISHED, 'redemptionReceiptLoading')
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'redemptionReceiptLoading')
      dispatch('logError', { redemptionReceipt: e.response.data })
    })
}

export const clearSaleEvouchers = ({ commit }) => {
  commit(T.SET_EVOUCHER_BY_SALE, [])
}

export const setCurrentSaleId = ({ commit }, saleId) => {
  commit(T.SALES_SET_SALE_ID, saleId)
}

export const setOnHoldPaymentMode = ({ commit }, data) => {
  commit(T.SALES_SET_ON_HOLD_PAYMENT_MODE, data)
}

export const loadSubscriptionSale = ({ commit, getters }, data) => {
  commit(
    T.PROCESSING_STARTED,
    data && data['create_sale'] && data['create_sale'] === 1 ? 'createSubscription' : 'loadingSubscription'
  )
  return post(
    U.SALES_SUBSCRIPTION,
    _.merge(
      {
        user_id: helpers.getValue(getters, 'getLoggedInUser.id'),
        location_id: helpers.getValue(getters, 'getAppLocationCountry.locationId'),
        is_eshop: 1,
        create_sale: 0,
      },
      data
    )
  )
    .then(response => {
      commit(T.SALES_SET_SUBSCRIPTION_SALE, response.data)
      commit(T.PROCESSING_FINISHED, 'loadingSubscription')
      return response.data
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'loadingSubscription')
      return helpers.getValue(error, 'response.data.code[0]') || error.response.data
    })
}

export const setShowLoadingPopup = ({ commit }, data) => {
  commit(T.SALES_SET_SHOW_LOADING_POPUP, data)
}

export const getPaymentQrCodeData = ({ commit, dispatch }, paymentId) => {
  commit(T.PROCESSING_STARTED, 'paymentQRCodeLoading')
  dispatch('removeError', 'paymentQRCode')
  return get(`${U.PAYMENT_QRCODE}/${paymentId}`)
    .then(response => {
      commit(T.SALES_SET_PAYMENT_QRCODE, response.data)
      commit(T.PROCESSING_FINISHED, 'paymentQRCodeLoading')
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'paymentQRCodeLoading')
      dispatch('logError', { paymentQRCode: e.response.data })
    })
}

export const clearPaymentStatus = ({ commit }) => {
  commit(T.SET_PAYMENT_STATUS, null)
}
