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

export const loadSvTransferList = async ({ commit }, payload) => {
  commit(PROCESSING_STARTED, 'loadingSvTransferList')

  payload = {
    cw_id: payload.payCycle,
    ibo_from: payload.fromIbo,
    ibo_to: payload.toIbo,
    date_from: payload.fromDate,
    date_to: payload.toDate,
    document_no_from: payload.fromDocumentNumber,
    document_no_to: payload.toDocumentNumber,
    transaction_no_from: payload.fromTransactionNumber,
    transaction_no_to: payload.toTransactionNumber,
    product_sku: payload.productSku,
    view_as: payload.viewAs,
    offset: payload.offset,
    limit: payload.limit,
  }
  let query = '?' + querystring.stringify(_.pickBy(payload, _.identity))

  return await get(U.SV_TRANSFER_GET_SV_TRANSFER_LIST + query)
    .then(response => {
      return response.data
    })
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'loadingSvTransferList')
    })
}

export const loadSalesSvTransferProductMeta = async ({ commit }, payCycleId) => {
  commit(PROCESSING_STARTED, 'loadingSvTransferProductList')

  let query = '?' + querystring.stringify({ cw_id: payCycleId })

  return await get(U.SV_TRANSFER_GET_TRANSFER_PRODUCT_LIST + query)
    .then(response => response.data)
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'loadingSvTransferProductList')
    })
}

export const updateSvTransferFormData = ({ commit }, payload) => {
  commit(SET_SV_TRANSFER_DETAILS, payload)
}

export const createSvTransferTransaction = async ({ commit, dispatch }, payload) => {
  commit(PROCESSING_STARTED, 'creatingSvTransferRecord')

  payload = {
    user_to_id: payload.userToId,
    cw_id: payload.payCycleId,
    items: payload.items,
  }

  return await post(U.SV_TRANSFER_CREATE_SV_TRANSFER, payload)
    .then(response => response.data && response.data.data)
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'creatingSvTransferRecord')
    })
}

export const loadSvTransferDetails = async ({ commit }, recordId) => {
  commit(PROCESSING_STARTED, 'loadingSvTransferDetails')

  return await get(U.SV_TRANSFER_GET_SC_TRANSFER_DETAILS + recordId)
    .then(response => response.data && response.data.data)
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'loadingSvTransferDetails')
    })
}
