import * as T from '../../utils/types'
import { get, post } from '../../utils/api'
import * as U from '../../utils/apiUrls'
import helpers from '@/helpers'
import querystring from 'querystring'
import _ from 'lodash'
import customMemberPayoutProcessor from '../dynamic-content/custom-content-processor/member-payout-process'

export const loadMemberDetails = async ({ commit, getters, dispatch }, data = {}) => {
  commit(T.PROCESSING_STARTED, 'memberDetails', { root: true })
  let cancelToken = await dispatch('generateCancelToken', 'products', { root: true })
  return post(
    U.MEMBER_DETAILS,
    {
      user_id: data.user_id || getters.getLoggedInUser.id,
    },
    cancelToken.token
  )
    .then(response => {
      commit(T.MEMBER_SET_DETAILS, response.data.member_data.details)
      commit(T.MEMBER_SET_MEMBER_FOUNDER, response.data.member_data.bonus_member_founder)
      commit(T.MEMBER_SET_SUBSCRIPTION, response.data.member_data.member_subscription)
      commit(T.MEMBER_SET_INFORMATION, response.data.member_data.information)
      commit(T.AUTH_SET_RULES, response.data.member_data.rules)
      commit(T.SET_MEMBER_AUTORITY, helpers.getValue(response.data, 'membership_role.permissions', []))

      let memberPayoutOptions = helpers.getValue(response, 'data.member_data.banking.payment_data', [])
      memberPayoutOptions =
        typeof memberPayoutOptions === 'string' ? JSON.parse(memberPayoutOptions) : memberPayoutOptions
      memberPayoutOptions = customMemberPayoutProcessor(memberPayoutOptions)
      commit(T.DYNAMIC_CONTENT_POPULATE, {
        name: 'logged_in_member_payout_options',
        data: memberPayoutOptions,
        grouped: {
          name: 'bank_data',
          matchPlace: {
            match: { id: memberPayoutOptions['selected'] },
            place: { selected: true },
          },
          ungroupPlace: {
            selected: {
              match: { selected: true },
              placeValue: 'id',
            },
          },
          type: 'radio',
        },
      })
    })
    .catch(e => {})
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'memberDetails', { root: true })
    })
}

export const loadEnrollmentRanks = ({ commit, dispatch }) => {
  commit(T.PROCESSING_STARTED, 'genealogyGetMemberListLoading', { root: true })
  dispatch('removeError', 'enrolmentRankLoading')
  return post(U.MEMBER_RANKS_LIST, {})
    .then(async response => {
      if (response.data !== undefined) {
        await commit(T.MEMBER_SET_RANK_LIST, response.data.data)
      } else {
        await commit(T.MEMBER_SET_RANK_LIST, [])
      }
    })
    .catch(e => {
      dispatch('logError', { enrolmentRankLoading: e })
      commit(T.PROCESSING_FINISHED, 'genealogyGetMemberListLoading', { root: true })
    })
}

export const fetchMemberGender = ({ commit, getters }) => {
  return post(U.MEMBER_DETAILS, { user_id: getters.getMemberDetails.user_id }).then(response => {
    if (response.status === 200) {
      if (response.data.member_data.information !== null) {
        let gender = response.data.member_data.information.gender_data.title
        commit(T.MEMBER_SET_GENDER, gender)
        return gender
      }
    }
    return false
  })
}

export const loadIBODetails = ({ commit, getters }) => {
  let member = getters.getMemberDetails
  let country = getters.getCountryById(member.country_id)
  let iboData = []
  if (country !== null) {
    let iboId = country.code + member.id.toString().padStart(11, '0')
    iboData.push({
      id: iboId,
      name: member.name,
    })
    commit(T.MEMBER_SET_IBO_DETAILS, iboData)
  }
}

export const getSelectedMemberDetail = ({ commit, getters }, userId) => {
  return post(U.GET_MEMBER_DETAILS, { user_id: userId }).then(response => {
    commit(T.MEMBER_SET_SELECTED_DETAILS, response.data.member_data)
  })
}

export const searchMemberList = ({ commit, getters, dispatch }, searchText) => {
  return dispatch('loadMemberList', {
    searchText: searchText,
  })
}

export const searchMemberListExcludeSelf = ({ commit, getters, dispatch }, searchText) => {
  return dispatch('loadMemberList', {
    searchText: searchText,
    includeSelf: false,
    excludeNonActive: true,
  })
}

export const loadMemberList = async ({ commit, getters, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'memberListLoading')
  let cancelToken = await dispatch('generateCancelToken', 'memberListLoading')
  payload = {
    limit: payload.limit || 10,
    search_text: payload.searchText,
    exact_text: payload.exactText,
    minimal: payload.minimal || false,
    country_id: payload.countryId || 0,
    include_self: payload.includeSelf !== undefined ? payload.includeSelf : true,
    exclude_non_active: payload.excludeNonActive !== undefined ? payload.excludeNonActive : false,
  }

  if (payload.exact_text) {
    delete payload.search_text
  } else {
    delete payload.exact_text
  }

  return post(U.GET_MEMBER_LIST, payload, cancelToken.token)
    .then(response => {
      commit(T.MEMBER_SET_MEMBER_LIST, response.data.data)
      return response.data.data
    })
    .catch(() => false)
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'memberListLoading')
    })
}

export const loadMemberDashBoardDetail = ({ commit }, cwId) => {
  commit(T.PROCESSING_STARTED, 'loadingMemberDetail')
  let query = ''

  if (cwId) {
    query = '?' + querystring.stringify({ cwId })
  }

  return get(U.DASHBOARD_DETAIL_ENDPOINT + query)
    .then(response => {
      commit(T.MEMBER_SET_DASHBOARD_DETAIL, response.data)
      return response.data
    })
    .catch(e => {})
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingMemberDetail')
    })
}

export const loadTvcRankInfo = ({ commit, getters }) => {
  commit(T.PROCESSING_STARTED, 'loadingTvcRankInfo')
  let payload = { country_code: getters.getSelectedCountry.code_iso_2 }
  let query = '?' + querystring.stringify(_.pickBy(payload, _.identity))
  return get(U.DASHBOARD_TVC_LEVEL_INFO + query)
    .then(response => {
      commit(T.MEMBER_SET_TVC_RANK_INFO, response.data)
    })
    .catch(e => {})
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingTvcRankInfo')
    })
}
