import helpers from '@/helpers'
import constants from '@/config/const'
import * as T from '@/store/utils/types'
import * as U from '@/store/utils/apiUrls'
import * as querystring from 'querystring'
import { post, get } from '@/store/utils/api'

export const loadCampaignList = ({ commit, dispatch, getters }, data) => {
  commit(T.PROCESSING_STARTED, 'campaignListLoading')
  let selectedCountryFromStorage = helpers.getValue(getters, 'getAppLocationCountry.countryId')
  return post(U.CAMPAIGN_LIST_URL, { country_id: data || selectedCountryFromStorage, ibs_active: 1 })
    .then(response => {
      commit(T.SET_CAMPAIGN_LIST, response.data.data)
      commit(T.PROCESSING_FINISHED, 'campaignListLoading')
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'campaignListLoading')
      dispatch('logError', { campaignList: error })
    })
}

/**
 * Load Commission Week schedule list based on filter type specified
 * @param filterType value included : past,current,current_back_date,next,future,current_future,
 * custom,custom_past,custom_current_past,custom_future,custom_current_future,all
 * @returns {*}
 */
export const loadCwScheduleList = ({ commit }, filterType) => {
  commit(T.PROCESSING_STARTED, 'cwScheduleList')
  return post(U.CW_SCHEDULES_LIST_URL, filterType || { filter_type: 'all', limit: 1000, sort: 'id', order: 'desc' })
    .then(response => {
      if (response.data.data !== undefined) {
        if (filterType !== undefined && filterType.filter_type === 'past') {
          commit(T.SET_CW_SCHEDULE_LIST_PAST, response.data.data)
        } else {
          commit(T.SET_CW_SCHEDULE_LIST, response.data.data)
        }
      }
      return helpers.getValue(response, 'data.data')
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'cwScheduleList')
    })
}

/**
 * Retrieve Bonus Statement report based on selected Commission Week
 * @param commit
 * @param getters
 * @param dispatch
 * @param cwId Commission Week id
 */
export const getWeeklyBonusStatement = ({ commit, getters, dispatch }, cwId) => {
  commit(T.PROCESSING_STARTED, 'weeklyBonusStatementLoading')
  dispatch('removeError', 'weeklyBonusStatement')
  let selectedWeek = getters.getCwScheduleListPast.find(cw => cw.id === cwId)
  let member = getters.getMemberDetails
  return post(U.WEEKLY_BONUS_STATEMENT_URL, { cw_id: selectedWeek.id, user_ids: [{ user_id: member.user_id }] })
    .then(response => {
      commit(T.SET_WEEKLY_BONUS_STATEMENT_DATA, response.data[0])
      commit(T.PROCESSING_FINISHED, 'weeklyBonusStatementLoading')
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'weeklyBonusStatementLoading')
      if (typeof error.response.data[member.user_id] === 'undefined') {
        dispatch('logError', { weeklyBonusStatement: error.response.data['error'].message })
      } else {
        dispatch('logError', { weeklyBonusStatement: error.response.data[member.user_id][0] })
      }
    })
}

// eslint-disable-next-line no-unused-vars
export const getMemberCampaignReport = ({ commit, getters, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'memberCampaignReportLoading')
  return post(U.GET_MEMBER_CAMPAIGN_REPORT, data)
    .then(response => {
      commit(T.PROCESSING_FINISHED, 'memberCampaignReportLoading')
      commit(T.SET_MEMBER_CAMPAIGN_REPORT, response.data)
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'memberCampaignReportLoading')
      dispatch('logError', { weeklyBonusStatement: error.response.data['user_id'] })
    })
}

/**
 * Retrieve Annual Income Statement report based on selected Year
 * @param year Year
 */
export const loadStatement = ({ getters, commit, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'statementLoading')
  dispatch('removeError', 'annualIncomeStatement')
  let member = getters.getMemberDetails
  let query = {
    ...data,
    country_id: member.country_id,
    ids: [
      {
        hasUserSelected: true,
        id: member.user_id,
        user_name: member.name,
      },
    ],
  }
  return post(U.ANNUAL_INCOME_STATEMENT_URL, query)
    .then(response => {
      commit(T.SET_ANNUAL_INCOME_STATEMENT_DATA, response.data)
      commit(T.PROCESSING_FINISHED, 'statementLoading')
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'statementLoading')
      if (typeof error.response.data[member.user_id] === 'undefined') {
        dispatch('logError', { annualIncomeStatement: error.response.data['error'].message })
      } else {
        dispatch('logError', { annualIncomeStatement: error.response.data[member.user_id][0] })
      }
    })
}

export const loadAnnualIncomeStatement = ({ getters, dispatch }, year) => {
  let reportId = getters.getMasterDataIdByKeyAndTitle(
    constants.masterKey['YEARLY_REPORT_TYPE'],
    constants.masterData['STATEMENT_REPORT']
  )
  return dispatch('loadStatement', { year: year, report_type: reportId })
}

export const loadCP58Statement = ({ getters, dispatch }, year) => {
  let reportId = getters.getMasterDataIdByKeyAndTitle(
    constants.masterKey['YEARLY_REPORT_TYPE'],
    constants.masterData['CP58_REPORT']
  )
  return dispatch('loadStatement', { year: year, report_type: reportId })
}

/**
 * Retrieve Welcome Bonus Daily report based on selected date
 * @param year Year
 * @param data
 */
// eslint-disable-next-line no-unused-vars
export const loadWelcomeBonusDaily = ({ getters, commit, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'welcomeBonusDailyLoading')
  dispatch('removeError', 'welcomeBonusDaily')
  return post(U.WELCOME_BONUS_DAILY_URL, data)
    .then(response => {
      commit(T.SET_WELCOME_BONUS_DAILY_DATA, response.data.data !== undefined ? response.data.data : [])
      commit(T.PROCESSING_FINISHED, 'welcomeBonusDailyLoading')
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'welcomeBonusDailyLoading')
      dispatch('logError', { welcomeBonusDaily: error.response.data })
    })
}

/**
 * Get list of available annual report
 */
export const loadAuthorizedReportList = ({ commit, dispatch }) => {
  commit(T.PROCESSING_STARTED, 'authorizedReportListLoading')
  dispatch('removeError', 'authorizedReportList')
  return get(U.GET_USER_AUTHORIZED_REPORT_URL)
    .then(response => {
      commit(T.SET_AUTHORIZED_REPORT_LIST, response.data)
      commit(T.PROCESSING_FINISHED, 'authorizedReportListLoading')
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'authorizedReportListLoading')
      dispatch('logError', { authorizedReportList: error.response.data })
    })
}

export const loadBvSvInfoStatement = async ({ commit }, payload) => {
  commit(T.PROCESSING_STARTED, 'loadingBvSvInfoStatement')
  let query = '?' + querystring.stringify({ downline_id: payload.downlineId })

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