import { SET_PAGINATION, SET_ORDER_HISTORY_SEARCH_TEXT, SET_EK_SMART_ORDER_HISTORY_SEARCH_TEXT } from '../utils/types'
import router from '@/router'

export default store => {
  store.subscribe(async mutation => {
    if (
      [
        'orderhistory/' + SET_ORDER_HISTORY_SEARCH_TEXT,
        mutation.type === SET_PAGINATION && mutation.payload.name === 'orderhistory' ? SET_PAGINATION : null,
      ].indexOf(mutation.type) !== -1
    ) {
      let pagination = store.getters.getPagination('orderhistory') || { offset: 0 }
      let searchText = store.getters['orderhistory/getSearchText'] || { doc: '' }
      if (
        mutation.type !== SET_PAGINATION &&
        pagination.offset !== 0 &&
        (searchText.member.user_id !== '' || searchText.doc.trim() !== '')
      ) {
        router.push({ name: 'OrderHistoryEshopHomePaginated', params: { page: 1 } })
      } else {
        store.dispatch('loadSalesList')
      }
    } else if (
      [
        'orderhistory/' + SET_EK_SMART_ORDER_HISTORY_SEARCH_TEXT,
        mutation.type === SET_PAGINATION && mutation.payload.name === 'eksmartorderhistory' ? SET_PAGINATION : null,
      ].indexOf(mutation.type) !== -1
    ) {
      let pagination = store.getters.getPagination('eksmartorderhistory') || { offset: 0 }
      let searchText = store.getters['orderhistory/getEkSmartSearchText'] || { doc: '' }
      if (mutation.type !== SET_PAGINATION && searchText.doc.trim() !== '' && pagination.offset !== 0) {
        router.push({ name: 'OrderHistoryEkSmartHomePaginated', params: { page: 1 } })
      } else {
        store.dispatch('loadEkSmartSalesList')
      }
    }
  })
}
