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

export const loadMyAccountInfo = async ({ commit, getters, dispatch }, payload = {}) => {
  let cancelToken = await dispatch('generateCancelToken', 'myaccount', { root: true })

  commit(T.PROCESSING_STARTED, 'myAccountInfo', { root: true })
  return post(U.MEMBER_DETAILS, { user_id: payload.user_id || getters.getMemberDetails.user_id }, cancelToken.token)
    .then(response => {
      commit(T.SET_MY_ACCOUNT_MEMBER_DETAILS, response.data.member_data)
      commit(T.MEMBER_SET_DETAILS, response.data.member_data.details)
      commit(T.MEMBER_SET_SUBSCRIPTION, response.data.member_data.member_subscription)
      commit(T.AUTH_SET_RULES, response.data.member_data.rules)
      commit(T.SET_MEMBER_AUTORITY, helpers.getValue(response.data, 'membership_role.permissions', []))
      commit(T.SET_MEMBER_AMP_ACCUMULATIONS, helpers.getValue(response.data, 'amp_accumulations', []))

      if (
        typeof response.data.member_data.details.avatar_image_link !== 'undefined' &&
        response.data.member_data.details.avatar_image_link !== null
      ) {
        commit(T.MEMBER_SET_AVATAR, response.data.member_data.details.avatar_image_link)
      }

      return true
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'myAccountInfo', { root: true })
    })
}

export const loadMyAccountCountries = ({ commit }) => {
  get(U.API_COUNTRIES_URL).then(response => {
    let i = response.data.data.length
    let result = []
    for (i; i > 0; i--) {
      let temp = {
        value: response.data.data[i - 1].id,
        text: response.data.data[i - 1].name,
      }
      result.push(temp)
    }
    commit(T.SET_COUNTRIES_LIST, result)
  })
}

// export const loadBankList = ({ commit, getters }, countryId = null) => {
//   let inputData = {
//     country_id: countryId === null ? getters.getMemberDetails.country_id : countryId,
//     relations: ['banks'],
//   }
//   return post(U.API_COUNTRY_RELATION, inputData).then(response => {
//     if (response.status === 200) {
//       var bankInfo = []
//       response.data.banks.map(item => {
//         bankInfo.push({ bankId: item.id, bankName: item.name, bankSwiftCode: item.swift_code })
//       })
//       commit(T.SET_BANK_LIST, bankInfo)
//     }
//   })
// }

export const loadCountryDynamicContent = ({ commit, getters }) => {
  commit(T.PROCESSING_STARTED, 'loadingCountryDynamicContent', { root: true })
  let inputDinamicContent = {
    country_id: getters.getMemberDetails.country_id,
    types: ['address', 'member_payout_options', 'taxpayer_info'],
  }
  return post(U.API_COUNTRY_DYNAMIC_CONTENT_TYPES, inputDinamicContent)
    .then(response => {
      if (response !== undefined && response.status === 200) {
        commit(T.SET_COUNTRY_DINAMIC_CONTENT, response.data)
        let memberPayoutOptions =
          typeof response.data['member_payout_options'] === 'string'
            ? JSON.parse(response.data['member_payout_options'])
            : response.data['member_payout_options']
        if (memberPayoutOptions) {
          memberPayoutOptions = customMemberPayoutProcessor(memberPayoutOptions)
          commit(T.DYNAMIC_CONTENT_POPULATE, {
            name: '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',
            },
          })
        }
        return true
      } else {
        return false
      }
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingCountryDynamicContent', { root: true })
    })
}

export const updateMemberDetails = ({ commit, getters }, data) => {
  commit(T.UPDATE_MY_ACCOUNT_MEMBER_DETAILS, data)
  let memberData = getters.getMyAccountMemberDetails
  // send back the to API
  let putUrl = U.MEMBER_PUT + '/' + getters.getMyAccountMemberDetails.details.user_id
  return put(putUrl, { member_data: memberData })
    .then(response => {
      if (response.status === 200) {
        commit(T.SET_MY_ACCOUNT_MEMBER_DETAILS, response.data.member_data)
        commit(T.MEMBER_SET_DETAILS, response.data.member_data.details)
        commit(T.MEMBER_SET_INFORMATION, response.data.member_data.information)
        if (typeof response.data.member_data.details.avatar_image_link !== 'undefined') {
          commit(T.MEMBER_SET_AVATAR, response.data.member_data.details.avatar_image_link)
        }
        return true
      } else {
        return false
      }
    })
    .catch(() => {
      return false
    })
}

export const updateMemberPaymentInfoByDynamicContent = ({ commit, getters }, dynamicContentName) => {
  let memberData = getters.getMyAccountMemberDetails

  let paymentData = getters.getDynamicContentForApi(dynamicContentName)

  if (paymentData !== undefined) {
    commit(T.PROCESSING_STARTED, 'updateMemberPayoutInfo', { root: true })

    let putUrl = U.MEMBER_PUT + '/' + getters.getMyAccountMemberDetails.details.user_id
    let bankingInfo = {
      payment_data: { ...paymentData },
    }
    let bankindId = helpers.getValue(getters, 'getMyAccountMemberDetails.banking.id', false)
    if (bankindId !== false) {
      bankingInfo.id = bankindId
    }
    return put(putUrl, {
      member_data: _.defaultsDeep(
        {
          banking: bankingInfo,
        },
        memberData
      ),
    })
      .then(response => {
        if (response.status === 200) {
          commit(T.SET_MY_ACCOUNT_MEMBER_DETAILS, response.data.member_data)
          commit(T.MEMBER_SET_DETAILS, response.data.member_data.details)
          commit(T.MEMBER_SET_INFORMATION, response.data.member_data.information)

          let memberPayoutOptions = helpers.getValue(response, 'data.member_data.banking.payment_data', [])
          memberPayoutOptions =
            typeof memberPayoutOptions === 'string' ? JSON.parse(memberPayoutOptions) : 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',
            },
          })

          if (typeof response.data.member_data.details.avatar_image_link !== 'undefined') {
            commit(T.MEMBER_SET_AVATAR, response.data.member_data.details.avatar_image_link)
          }
          return true
        } else {
          return false
        }
      })
      .catch(() => {
        return false
      })
      .finally(() => {
        commit(T.PROCESSING_FINISHED, 'updateMemberPayoutInfo', { root: true })
      })
  } else {
    return false
  }
}

export const updateMemberDetailsAddress = ({ commit, getters }, data) => {
  data.address.address_data.forEach(address => {
    if (address.fields.length > 0 && typeof address.unselected !== 'undefined') {
      delete address['unselected']
    }
  })
  commit(T.UPDATE_MY_ACCOUNT_MEMBER_DETAILS_ADDRESS, data)
  let memberData = getters.getMyAccountMemberDetails
  // send back the to API
  let putUrl = U.MEMBER_PUT + '/' + getters.getMyAccountMemberDetails.details.user_id
  return put(putUrl, { member_data: memberData })
    .then(response => {
      if (response.status === 200) {
        commit(T.SET_MY_ACCOUNT_MEMBER_DETAILS, response.data.member_data)
        return true
      } else {
        return false
      }
    })
    .catch(() => {
      return false
    })
}

export const loadEthnicGroupList = ({ commit, getters }) => {
  let eGroupList = getters.getMasterDataByKey('ethnic_group')
  let result = []
  eGroupList.forEach(item => {
    let temp = {
      text: helpers.getValue(item, 'translated_title.content', item.title),
      value: item.id,
    }
    result.push(temp)
  })
  commit(T.SET_MY_ACCOUNT_ETHNIC_GROUP, result)
}

export const loadMaritalStatusList = ({ commit, getters }) => {
  let maritalList = getters.getMasterDataByKey('martial_status') || []
  let result = []
  maritalList.forEach(item => {
    let temp = {
      text: helpers.getValue(item, 'translated_title.content', item.title),
      value: item.id,
    }
    result.push(temp)
  })
  commit(T.SET_MY_ACCOUNT_MARITAL_STATUS, result)
}

export const loadGenderList = ({ commit, getters }) => {
  let maritalList = getters.getMasterDataByKey('gender')
  let result = []
  maritalList.forEach(item => {
    let temp = {
      text: helpers.getValue(item, 'translated_title.content', item.title),
      value: item.id,
    }
    result.push(temp)
  })
  commit(T.SET_MY_ACCOUNT_GENDER_LIST, result)
}

export const loadCities = ({ commit }) => {
  get(U.API_CITIES_URL).then(response => {
    if (response.data.data !== undefined) {
      commit(T.SET_MY_ACCOUNT_CITIES, response.data.data)
    }
  })
}

export const loadPreferredContact = ({ commit, getters }) => {
  let prefContact = getters.getMasterDataByKey('preferred_contact')
  let result = []
  prefContact.forEach(item => {
    let temp = {
      text: helpers.getValue(item, 'translated_title.content', item.title),
      value: item.id,
    }
    result.push(temp)
  })
  commit(T.SET_MY_ACCOUNT_PREFERRED_CONTACT, result)
}

export const loadPlacementPreference = ({ commit }) => {
  return get(U.COMMISSION_PLACEMENT_PREFERENCE).then(response => {
    commit(T.SET_MY_ACCOUNT_PLACEMENT_PREFERENCE, {
      preference: response.data.preference,
      next_placement: response.data.next_placement,
    })
  })
}

export const updatePlacementPreference = ({ commit }, data) => {
  return post(U.COMMISSION_PLACEMENT_PREFERENCE, { preference: data.preference })
    .then(response => {
      if (response.status === 200) {
        commit(T.SET_MY_ACCOUNT_PLACEMENT_PREFERENCE, {
          preference: response.data.preference,
          next_placement: response.data.next_placement,
        })

        return true
      } else {
        return false
      }
    })
    .catch(() => {
      return false
    })
}

export const changePassword = ({ commit, dispatch, getters }, data) => {
  commit(T.PROCESSING_STARTED, 'changePassword')
  dispatch('removeError', 'changePassword')
  let inputData = {
    user_id: data.user_id || getters.getMyAccountMemberDetails.details.user_id,
    current_password: data.currentPassword,
    new_password: data.newPassword,
    new_password_confirmation: data.retypeNewPassword,
  }
  return post(U.API_USER_CHANGE_PASSWORD_URL, inputData)
    .then(response => {
      commit(T.PROCESSING_FINISHED, 'changePassword')
      return response.status === 200
    })
    .catch(error => {
      commit(T.PROCESSING_FINISHED, 'changePassword')
      dispatch('logError', { changePassword: error.response.data })
      return false
    })
}

export const requestNewCode = ({}, data) => {
  let ret = {
    message: 'undefine error',
    status: 'error',
  }
  return post(U.EWALLET_MOBILE_VALIDATION, data)
    .then(response => {
      if (response.status === 200 || response.status === 201) {
        if (typeof response.data.status !== 'undefined') {
          ret = {
            message: response.data.status,
            status: 'already_verified',
          }
        } else {
          ret = {
            message: '',
            status: 'ok',
          }
        }
        return ret
      } else {
        return ret
      }
    })
    .catch(e => {
      ret.message = e.response.data
      if (typeof e.response.data.mobile_1_num !== 'undefined') {
        ret.message = e.response.data.mobile_1_num.toString()
      }
      if (typeof e.response.data.mobile_1_country_code_id !== 'undefined') {
        ret.message = e.response.data.mobile_1_country_code_id.toString()
      }
      return ret
    })
}

export const validateEmail = ({}, data) => {
  let ret = {
    message: 'undefine error',
    status: 'error',
  }
  return post(U.MEMBER_EMAIL_VALIDATE, data)
    .then(response => {
      if (response.status === 200 || response.status === 201) {
        if (typeof response.data.status !== 'undefined') {
          ret = {
            message: response.data.status,
            status: 'already_verified',
          }
        } else {
          ret = {
            message: '',
            status: 'ok',
          }
        }
        return ret
      } else {
        return ret
      }
    })
    .catch(e => {
      ret.message = e.response.data
      if (typeof e.response.data.email !== 'undefined') {
        ret.message = e.response.data.email.toString()
      }
      if (typeof e.response.data.code !== 'undefined') {
        ret.message = e.response.data.code.toString()
      }
      return ret
    })
}

export const activateMobileCode = ({}, data) => {
  let ret = {
    message: 'undefine error',
    status: 'error',
  }
  return post(U.EWALLET_MOBILE_VALIDATION, data)
    .then(response => {
      if (response.status === 200) {
        ret.status = 'ok'
        return ret
      } else {
        return ret
      }
    })
    .catch(e => {
      if (typeof e.response.data.code !== 'undefined') {
        ret.message = e.response.data.code.toString()
      } else if (typeof e.response.data.mobile_1_num !== 'undefined') {
        ret.message = e.response.data.mobile_1_num.toString()
      } else if (typeof e.response.data.mobile_1_country_code_id !== 'undefined') {
        ret.message = e.response.data.mobile_1_country_code_id.toString()
      } else {
        ret.message = e.response.data
      }
      return ret
    })
}

export const loadMemberAmpPreference = async ({ commit, dispatch }) => {
  commit(T.PROCESSING_STARTED, 'loadingAmpPreference')
  dispatch('removeError', 'memberAmpPreference')
  return await get(U.MEMBER_AMP_PREFERENCE_DETAIL)
    .then(response => {
      return response.data && response.data.preference
    })
    .catch(error => {
      dispatch('logError', { memberAmpPreference: error })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingAmpPreference')
    })
}

export const updateMemberAmpPreferences = async ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'updatingAmpPreference')
  dispatch('removeError', 'memberAmpPreferenceUpdate')
  return await post(U.MEMBER_AMP_PREFERENCE_DETAIL_UPDATE, payload)
    .then(response => {
      return response.data && response.data.preference
    })
    .catch(error => {
      dispatch('logError', { memberAmpPreferenceUpdate: error })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'updatingAmpPreference')
    })
}

export const loadUserAmpChangeLog = async ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'loadingAmpChangeLog')
  dispatch('removeError', 'loadMemberAmpLog')
  let query = '?' + queryString.stringify(payload)
  return await get(U.MEMBER_AMP_PREFERENCE_LOG + query)
    .then(response => {
      return response.data
    })
    .catch(err => {
      dispatch('logError', { loadMemberAmpLog: err })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingAmpChangeLog')
    })
}
