import { get, post } from '../../utils/api'
import * as U from '../../utils/apiUrls'
import * as T from '../../utils/types'
import queryString from 'querystring'
import _ from 'lodash'

export const loadSponserDownlineListingData = ({ commit, dispatch, getters }, data) => {
  commit(T.PROCESSING_STARTED, 'genealogySponsorDownlineListingLoading')
  dispatch('removeError', 'genealogy_sponsor_downline_listing_loading')
  data.user_id = getters.getMemberDetails.user_id
  return post(U.API_SPONSOR_DOWNLINE_LISTING_URL, data)
    .then(response => {
      commit(T.SET_GENEALOGY_SPONSOR_DOWNLINE_LISTING, response.data)
      commit(T.PROCESSING_FINISHED, 'genealogySponsorDownlineListingLoading')
    })
    .catch(e => {
      dispatch('logError', { genealogy_sponsor_downline_listing_loading: e })
      commit(T.PROCESSING_FINISHED, 'genealogySponsorDownlineListingLoading')
    })
}

export const loadSponserNetworkTreeData = ({ commit, dispatch, getters }, data) => {
  commit(T.PROCESSING_STARTED, 'genealogySponsorNetworkTreeLoading')
  data.tree_type = 'sponsor'
  data.user_id = getters.getGenealogyUserId
  return post(U.API_SPONSOR_NETWORK_TREE_URL, data)
    .then(response => {
      commit(T.SET_GENEALOGY_SPONSOR_NETWORK_TREE, response.data)
      commit(T.PROCESSING_FINISHED, 'genealogySponsorNetworkTreeLoading')
    })
    .catch(e => {
      dispatch('logError', { genealogy_sponsor_network_tree_loading: e })
      commit(T.PROCESSING_FINISHED, 'genealogyGetMemberListLoading')
    })
}

export const loadGenealogyMemberList = ({ commit, dispatch, getters }, data) => {
  commit(T.PROCESSING_STARTED, 'genealogyGetMemberListLoading')
  return post(U.API_GET_GENEALOGY_MEMBER_LIST_URL, data)
    .then(response => {
      commit(T.SET_GENEALOGY_MEMBER_LIST, response.data.data)
      commit(T.PROCESSING_FINISHED, 'genealogyGetMemberListLoading')
    })
    .catch(e => {
      dispatch('logError', { genealogy_get_member_list_loading: e })
      commit(T.PROCESSING_FINISHED, 'genealogyGetMemberListLoading')
    })
}

export const loadPlacementNetworkPerformanceData = ({ commit, dispatch, getters }, data) => {
  commit(T.PROCESSING_STARTED, 'genealogyPlacementNetworkPerformanceLoading')
  return post(U.API_PLACEMENT_NETWORK_PERFORMANCE_URL, data)
    .then(response => {
      commit(T.SET_GENEALOGY_PLACEMENT_NETWORK_PERFORMANCE, response.data)
      commit(T.PROCESSING_FINISHED, 'genealogyPlacementNetworkPerformanceLoading')
    })
    .catch(e => {
      dispatch('logError', { genealogy_placement_network_performance_loading: e })
      commit(T.PROCESSING_FINISHED, 'genealogyGetMemberListLoading')
    })
}

export const getMemberTreeActionGenealogy = ({ commit, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'memberTreeLoading')
  if (data.external_data_source !== undefined) {
    commit(T.SET_GENEALOGY_MEMBER_TREE, data.external_data_source)
    commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
    return true
  } else {
    return post(U.API_GENEALOGY_MEMBER_PLACEMENT_TREE, data)
      .then(response => {
        commit(T.SET_GENEALOGY_MEMBER_TREE, response.data)
        commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
        return true
      })
      .catch(error => {
        dispatch('logError', { genealogy_get_member_tree_action: error })
        commit(T.SET_GENEALOGY_MEMBER_TREE, {})
        commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
        return false
      })
  }
}

export const getMembersOuterTreeActionGenealogy = ({ commit, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'memberTreeLoading')
  return post(U.API_GENEALOGY_MEMBER_PLACEMENT_TREE_OUTER, data)
    .then(response => {
      if (response.status === 200) {
        commit(T.SET_GENEALOGY_MEMBER_TREE, response.data)
        commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
        return true
      } else {
        dispatch('logError', { genealogy_get_member_tree_outer_action: 'error' })
        commit(T.SET_GENEALOGY_MEMBER_TREE, {})
        commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
        return false
      }
    })
    .catch(error => {
      dispatch('logError', { genealogy_get_member_tree_outer_action: error })
      commit(T.SET_GENEALOGY_ERROR_MESSAGE, error.response.data.error.message)
      commit(T.SET_GENEALOGY_MEMBER_TREE, {})
      commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
      return false
    })
}

export const getMemberSearchTreeActionGenealogy = ({ commit, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'memberTreeLoading')
  return post(U.GET_MEMBER_LIST, data)
    .then(response => {
      if (response.status === 200) {
        let list = []
        response.data.data.forEach(item => {
          let countryCode = typeof item.country !== 'undefined' ? item.country.code : ''
          let iboId = countryCode + (item.old_member_id || item.user.old_ibs_user_id) // .toString().padStart(11, '0')

          list.push({
            value: item.user_id,
            label: iboId,
            name: item.name,
            email: item.email,
          })
        })
        commit(T.SET_GENEALOGY_MEMBER_SEARCH_TREE, list)
        commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
        return true
      } else {
        commit(T.SET_GENEALOGY_MEMBER_SEARCH_TREE, [])
        commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
        return false
      }
    })
    .catch(error => {
      dispatch('logError', { genealogy_get_member_tree_outer_action: error })
      commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
      commit(T.SET_GENEALOGY_MEMBER_SEARCH_TREE, [])
      return false
    })
}

export const searchDownlineTreeActionGenealogy = async ({ commit, dispatch }, data) => {
  let cancelToken = await dispatch('generateCancelToken', 'searchDownlineCancelToken')
  commit(T.PROCESSING_STARTED, 'memberTreeLoading')
  return post(U.API_GET_GENEALOGY_MEMBER_LIST_URL, data, cancelToken.token)
    .then(response => {
      if (response.status === 200) {
        let list = []
        response.data.data.forEach(item => {
          let countryCode = typeof item.country !== 'undefined' ? item.country.code : ''
          let iboId = countryCode + (item.old_member_id || item.user.old_ibs_user_id) // .toString().padStart(11, '0')

          list.push({
            value: item.user_id,
            label: iboId,
            name: item.name,
            email: item.email,
          })
        })
        commit(T.SET_GENEALOGY_MEMBER_SEARCH_TREE, list)
        commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
        return true
      }
    })
    .catch(e => {
      dispatch('logError', { search_downline: e })
      commit(T.PROCESSING_FINISHED, 'memberTreeLoading')
      return false
    })
}

export const clearSearchTreeResult = ({ commit }) => {
  commit(T.SET_GENEALOGY_MEMBER_SEARCH_TREE, [])
}

export const memberVerifyTreeNetwork = async ({ commit, dispatch }, data) => {
  let cancelToken = await dispatch('generateCancelToken', 'searchDownlineCancelToken')
  commit(T.PROCESSING_STARTED, 'verifyMemberTreeLoading')
  return post(U.MEMBER_TREE_NETWORK_VERIFY, data, cancelToken.token)
    .then(response => {
      if (typeof response.data.error !== 'undefined') {
        return {
          status: false,
          msg: response.data.error,
        }
      }
      return {
        status: true,
        msg: response.data.result,
      }
    })
    .catch(e => {
      dispatch('logError', { verify_downline: e })
      commit(T.PROCESSING_FINISHED, 'verifyMemberTreeLoading')
      return {
        status: false,
        msg: e.response.data,
      }
    })
}

export const searchMemberSponsor = async ({ commit, dispatch }, data) => {
  let cancelToken = await dispatch('generateCancelToken', 'searchDownlineCancelToken')
  commit(T.PROCESSING_STARTED, 'verifyMemberTreeLoading')
  return post(U.MEMBER_SPONSOR_SEARCH, data, cancelToken.token)
    .then(response => {
      commit(T.PROCESSING_FINISHED, 'verifyMemberTreeLoading')
      if (typeof response.data.error !== 'undefined') {
        return {
          status: false,
          msg: response.data.error,
        }
      }
      return {
        status: true,
        msg: response.data.data[0],
      }
    })
    .catch(e => {
      dispatch('logError', { verify_downline: e })
      commit(T.PROCESSING_FINISHED, 'verifyMemberTreeLoading')
      if (typeof e.response.data.old_member_id !== 'undefined') {
        return {
          status: false,
          msg: e.response.data.old_member_id.toString(),
        }
      }
      return {
        status: false,
        msg: e.response.data,
      }
    })
}

export const loadCouncilRankList = async ({ commit }) => {
  commit(T.PROCESSING_STARTED, 'loadingCouncilRankList')

  return await get(U.MEMBER_COUNCIL_RANK_LIST)
    .then(response => response.data.data)
    .catch(() => false)
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingCouncilRankList')
    })
}

export const loadSponsorDownlineList = async ({ commit }, payload) => {
  commit(T.PROCESSING_STARTED, 'loadingSponsorDownlineList')
  payload = sponsorDownlineListingPayloadFactory(payload)

  return await post(U.MEMBER_SPONSOR_DOWNLINE_LISTING, payload)
    .then(response => response.data.data)
    .catch(() => false)
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingSponsorDownlineList')
    })
}

export const loadSponsorDownlineFilterList = async ({ commit }, cwId) => {
  commit(T.PROCESSING_STARTED, 'loadingSponsorDownlineFilterList')
  let query = '?' + queryString.stringify(_.pickBy({ cw_id: cwId }, _.identity()))

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

export const requestSponsorDownlineStatement = async ({ commit }, payload) => {
  commit(T.PROCESSING_STARTED, 'requestingSponsorDownlineStatement')
  payload = sponsorDownlineListingPayloadFactory(payload)

  return post(U.MEMBER_SPONSOR_DOWNLINE_REPORT, payload)
    .then(response => response.data)
    .catch(() => false)
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'requestingSponsorDownlineStatement')
    })
}

function sponsorDownlineListingPayloadFactory(data) {
  return {
    sort_by: data.sortBy,
    depth: data.depth || 1,
    order_by: data.orderBy || 'DESC',
    breakaway: Boolean(data.breakaway),
    downline_user_id: data.downlineUserId,
    active_until_cw_id: data.activeUntilCwId,
    council_rank_ids: data.councilRankIds || [],
    dynamic_filters: data.dynamicFilters || [],
  }
}
