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

export const setBundleCountry = ({ commit }, countryId) => {
  commit(T.SET_BUNDLE_COUNTRY, countryId)
}

export const setBundleProductFilter = ({ commit }, payload) => {
  commit(T.SET_BUNDLE_PRODUCTS_FILTER, payload)
}

export const loadBundleList = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'loadingBundleList', { root: true })
  dispatch('removeError', 'bundleLoading', { root: true })
  let queryString = '?' + querystring.stringify(payload)
  return get(U.MY_BUNDLE_GET_BUNDLE_LIST + queryString)
    .then(response => {
      commit(T.SET_BUNDLE_LIST, response.data.data)
      commit(T.SET_BUNDLE_LIST_RECORD_TOTAL, response.data.total)
    })
    .catch(error => {
      commit(T.SET_BUNDLE_LIST, [])
      commit(T.SET_BUNDLE_LIST_RECORD_TOTAL, 0)
      dispatch('logError', { bundleLoading: error }, { root: true })
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingBundleList', { root: true })
    })
}

export const loadBundleDetails = async ({ commit, dispatch }, bundleId) => {
  commit(T.PROCESSING_STARTED, 'loadingBundleDetails', { root: true })
  dispatch('removeError', 'bundleDetails', { root: true })
  return await get(U.MY_BUNDLE_GET_BUNDLE_DETAILS + bundleId)
    .then(response => {
      commit(T.SET_BUNDLE_DETAILS_DATA, response.data)
      return response.data
    })
    .catch(error => {
      dispatch('logError', { bundleDetails: error }, { root: true })
      router.replace({ name: 'MyBundle' })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingBundleDetails', { root: true })
    })
}

export const addProductToBundleCart = async ({ commit, dispatch, getters }, payload) => {
  commit(T.PROCESSING_STARTED, `productsAddingToCart-${payload.productId}-${payload.kittingId}`, { root: true })
  let cartItems = _.cloneDeep(getters.getBundleCartDetails.bundleItems)
  let startIndex = cartItems.findIndex(product => product.product_sku === payload.productSku)
  if (startIndex !== -1) {
    if (payload.productQuantity > 0) {
      cartItems[startIndex].product_quantity = payload.productQuantity
    } else {
      cartItems.splice(startIndex, 1)
    }
  } else if (payload.productQuantity > 0) {
    cartItems.push({
      product_name: payload.productName,
      product_sku: payload.productSku,
      product_prices: payload.productPrice,
      kitting_id: payload.kittingId,
      product_id: payload.productId,
      product_quantity: payload.productQuantity,
      product_sale_type_id: payload.productSaleTypeId,
    })
  }
  await dispatch('setBundleCartDetails', { bundle_items: cartItems })
  commit(T.PROCESSING_FINISHED, `productsAddingToCart-${payload.productId}-${payload.kittingId}`, { root: true })
}

export const setBundleCartDetails = ({ commit }, payload = {}) => {
  commit(T.PROCESSING_STARTED, 'updatingBundleCart', { root: true })
  let data = {
    bundleItems: payload.bundle_items || [],
    bundleTotal: payload.bundle_total || { member_price: 0, retail_price: 0 },
    validate: payload.validate || false,
  }
  commit(T.SET_BUNDLE_CART_DETAILS, data)
  commit(T.PROCESSING_FINISHED, 'updatingBundleCart', { root: true })
}

export const removeBundle = async ({ commit, dispatch }, bundleId) => {
  dispatch('removeError', 'bundle_remove', { root: true })
  return await del(U.MY_BUNDLE_REMOVE_BUNDLE + bundleId)
    .then(() => true)
    .catch(error => {
      dispatch('logError', { bundleRemove: error }, { root: true })
      return false
    })
}

export const createBundle = async ({ commit, dispatch, getters, rootGetters }, payload) => {
  commit(T.PROCESSING_STARTED, 'creatingBundle', { root: true })
  dispatch('removeError', 'doBundleCreation', { root: true })
  let bundle = bundlePayloadFactory(
    payload,
    rootGetters.getAppLocationCountry,
    getters.getBundleCartDetails.bundleItems
  )

  return post(U.MY_BUNDLE_CREATE_BUNDLE, bundle)
    .then(response => {
      commit(T.CLEAR_LOADED_DATA, 'myBundle')
      return response.data
    })
    .catch(error => {
      dispatch('logError', { doBundleCreation: error }, { root: true })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'creatingBundle', { root: true })
    })
}

export const updateBundle = ({ commit, dispatch, getters, rootGetters }, payload) => {
  commit(T.PROCESSING_STARTED, 'updatingBundle', { root: true })
  dispatch('removeError', 'doBundleUpdate', { root: true })
  let bundle = bundlePayloadFactory(
    payload,
    rootGetters.getAppLocationCountry,
    getters.getBundleCartDetails.bundleItems
  )

  return patch(U.MY_BUNDLE_UPDATE_BUNDLE + payload.bundleId, bundle)
    .then(response => {
      commit(T.CLEAR_LOADED_DATA, 'myBundle')
      return response.data
    })
    .catch(error => {
      dispatch('logError', { doBundleUpdate: error }, { root: true })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'updatingBundle', { root: true })
    })
}

function bundlePayloadFactory(payload, appLocationCountry = {}, cart = []) {
  let items = cart.map(product => ({
    country_id: appLocationCountry.countryId,
    location_id: appLocationCountry.locationId,
    quantity: product.product_quantity,
    sales_type_id: product.product_sale_type_id,
    [(product.product_id && 'product_id') || 'kitting_id']: product.product_id || product.kitting_id,
  }))

  return {
    items,
    configs: payload.configs,
    name: payload.bundleName,
    image_url: payload.bundleImage,
    description: payload.bundleDescription,
  }
}
