import * as T from '@/store/utils/types'
import querystring from 'querystring'
import { get } from '@/store/utils/api'
import { REPORT_BUSINESS_SNAPSHOT } from '@/store/utils/apiUrls'
import { weekDataPostProcessor } from '@/store/modules/business-snapshot/custom-data-pocessor/business-snapshot-data-porcess'
import _ from 'lodash'

export const loadBusinessSnapshotData = ({ commit, dispatch, rootGetters }, payCycle) => {
  dispatch('removeError', 'businessSnapshotData')
  commit(T.PROCESSING_STARTED, 'loadingBusinessSnapshotData')
  if (!payCycle) {
    payCycle = rootGetters['eshop/getCwInfo'].currentCwId
  }
  let payload = { pay_cycle_id: payCycle }

  let query = '?' + querystring.stringify(_.pickBy(payload, _.identity))
  get(REPORT_BUSINESS_SNAPSHOT + query)
    .then(response => {
      let result = weekDataPostProcessor(response.data)
      commit(T.SET_BUSINESS_SNAPSHOT_DATA, result)
    })
    .catch(error => {
      dispatch('logError', { businessSnapshotData: error })
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingBusinessSnapshotData')
    })
}
