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

export const getMember = async ({ commit, dispatch, rootDispatch, rootGetters }, query) => {
  commit(T.PROCESSING_STARTED, 'getMember', { root: true })
  if (rootGetters.getAppStatus('enrolment')) {
    query['is_ba_only'] = true
  }
  await post(U.GET_MEMBER_LIST, query)
    .then(async response => {
      if (query.upgradeMember !== undefined && query.upgradeMember === 1) {
        await commit(T.MEMBER_SET_UPGRADE_USER, null)
        if (response.data.data.length > 0) {
          let userID = response.data.data[0].user_id
          await post(U.MEMBER_DETAILS, { user_id: userID })
            .then(async () => {
              await commit(T.MEMBER_SET_UPGRADE_USER, response.data.member_data)
            })
            .catch(async e => {
              await commit(T.MEMBER_SET_UPGRADE_USER, {})
              dispatch('logError', { get_upgrade_member_failed: e }, { root: true })
              throw e
            })
        }
      } else if (query.placementMember !== undefined && query.placementMember === 1) {
        if (response.data.data.length > 0) {
          commit(T.MEMBER_SET_MEMBER_PLACEMENT_LIST_ENROLMENT, response.data.data)
        } else {
          let customError = [Vue.prototype.$t('Enrolment.PlacementMemberIBOIDNotValid.Message')]
          dispatch('logError', { get_member_failed: customError }, { root: true })
          throw customError
        }
      } else {
        commit(T.MEMBER_SET_MEMBER_SPONSOR_ENROLMENT, response.data.data)
      }
      commit(T.PROCESSING_FINISHED, 'getMember', { root: true })
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'getMember', { root: true })
      dispatch('logError', { get_member_failed: e }, { root: true })
      throw e
    })
}
export const getCode = async ({ commit, dispatch }, query) => {
  let url = ''
  if (query.type === 'email') {
    url = U.API_GET_VERIFY_CODE_EMAIL
  } else {
    url = U.API_GET_VERIFY_CODE_PHONE
  }
  commit(T.PROCESSING_STARTED, 'getEnrolmentCode', { root: true })
  await post(url, query)
    .then(response => {
      commit(T.SET_VERIFICATION_GET, response.data)
      commit(T.PROCESSING_FINISHED, 'getEnrolmentCode', { root: true })
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'getEnrolmentCode', { root: true })
      dispatch('logError', { get_verification_code_failed: e.response.data }, { root: true })
      throw e
    })
}

export const removeVerifications = ({ commit }) => {
  commit(T.REMOVE_VERIFICATIONS)
}

export const postCode = async ({ commit, dispatch }, query) => {
  let url = ''
  if (query.type === 'email') {
    url = U.API_POST_VERIFY_CODE_EMAIL
  } else {
    url = U.API_POST_VERIFY_CODE_PHONE
  }
  commit(T.PROCESSING_STARTED, 'postEnrolmentCode', { root: true })
  await post(url, query)
    .then(response => {
      commit(T.SET_VERIFICATION_POST, response.data)
      commit(T.PROCESSING_FINISHED, 'postEnrolmentCode', { root: true })
    })
    .catch(e => {
      dispatch('logError', { post_verification_code_failed: e.response.data }, { root: true })
      commit(T.PROCESSING_FINISHED, 'postEnrolmentCode', { root: true })
      throw e
    })
}

export const setEnrolForm = ({ commit }, data) => {
  commit(T.SET_ENROL_FORM, data)
}

export const loadEnrolmentCountryDynamicContent = ({ commit, getters }) => {
  let inputDynamicContent = {
    country_id: getters.getEnrolCountryId,
    types: ['card_recurring_information', 'member_payout_options', 'taxpayer_info'],
  }
  return post(U.API_COUNTRY_DYNAMIC_CONTENT_TYPES, inputDynamicContent).then(response => {
    if (response.status === 200) {
      commit(T.SET_ENROLMENT_COUNTRY_DINAMIC_CONTENT, JSON.parse(response.data))
      return true
    } else {
      return false
    }
  })
}

export const getDynamicRecurringInfo = ({ commit }, query) => {
  return post(U.API_COUNTRY_DYNAMIC_CONTENT_TYPES, query).then(response => {
    if (response.status === 200) {
      let json = JSON.parse(response.data.recurring_information)
      commit(T.SET_DYNAMIC_RECURRING_INFO, json)
      return true
    } else {
      return false
    }
  })
}

export const getDynamicEmploymentDetails = ({ commit }, query) => {
  if (query.membership_type === 'EK Smart') {
    return post(U.API_COUNTRY_DYNAMIC_CONTENT_TYPES, query).then(response => {
      if (response.data.error === undefined) {
        commit(T.SET_DYNAMIC_EMPLOYMENT_DETAILS, response.data.employment_details)
      } else {
        commit(T.SET_DYNAMIC_EMPLOYMENT_DETAILS, null)
      }
    })
  } else {
    commit(T.SET_DYNAMIC_EMPLOYMENT_DETAILS, null)
  }
}

export const setSupportingDocDetails = ({ commit }, payload) => {
  commit(T.SET_SUPPORTING_DOC_DETAILS, payload)
}

export const setSelectedRecurringInfoType = ({ commit }, payload) => {
  commit(T.SET_SELECTED_RECURRING_INFO_TYPE, payload)
}

export const setNRICDocDetails = ({ commit }, payload) => {
  commit(T.SET_NRIC_DOC_DETAILS, payload)
}
export const setRentalCardDetails = ({ commit, getters, rootGetters }, payload) => {
  commit(T.SET_CART_RENTAL_DETAILS, { ...payload, isEnrolment: rootGetters.getAppStatus('enrolment') })
}
export const setBankCardDetails = ({ commit }, payload) => {
  commit(T.SET_BANK_CARD_DETAILS, payload)
}
export const setMPayDetails = ({ commit }, payload) => {
  commit(T.SET_MPAY_DETAILS, payload)
}

export const getDynamicPayeeInfo = async ({ commit }, query) => {
  try {
    let res = await post(U.API_DYNAMIC_CONTENT, query)
    let json = JSON.parse(res.data.member_payout_options)
    commit(T.SET_DYNAMIC_PAYEE_INFO, json)
  } catch (e) {
    throw e
  }
}

export const isValidCardInfoFields = ({ getters }) => {
  let selectedType = getters.getSelectedRecurringInfoType
  let value = getters.getRentalCardDetails
  let isValid = false
  if (selectedType === 'CARD') {
    if (
      value.card_type_id !== '' &&
      value.card_company_id !== '' &&
      value.country_bank_id !== '' &&
      value.card_holder_name !== '' &&
      value.card_number !== '' &&
      value.card_expiry_date !== '' &&
      value.credit_card_photocopy.length > 0
    ) {
      isValid = true
    }
  } else {
    isValid = true
  }

  return Promise.resolve(isValid)
}

export const getEnrolmentsTypes = async ({ commit, dispatch }, query) => {
  commit(T.PROCESSING_STARTED, 'getEnrolmentTypes', { root: true })
  let filter = ''
  if (query.is_ek_smart === undefined) {
    query.is_ek_smart = 0
  }
  if (query.sort !== undefined && query.order !== undefined) {
    filter = '&sort=' + query.sort + '&order=' + query.order
  }

  return await get(U.API_GET_ENROLMENT_TYPES + '/' + query.country_id + '?ek_smart=' + query.is_ek_smart + filter)
    .then(async response => {
      await commit(T.SET_ENROLMENT_TYPES, response.data)
      commit(T.PROCESSING_FINISHED, 'getEnrolmentTypes', { root: true })
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'getEnrolmentTypes', { root: true })
      dispatch('logError', { get_enrolment_types_failed: e.data }, { root: true })
      throw e
    })
}

export const getPlacementValidity = async ({ commit, dispatch }, query) => {
  commit(T.PROCESSING_STARTED, 'getPlacementValidity', { root: true })
  await post(U.API_MEMBER_PLACEMENT_VERIFY, query)
    .then(response => {
      commit(T.SET_MEMBER_PLACEMENT_VERIFY, response.data)
      commit(T.PROCESSING_FINISHED, 'getPlacementValidity', { root: true })
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'getPlacementValidity', { root: true })
      dispatch('logError', { member_placement_verify_failed: e.response.data }, { root: true })
      throw e
    })
}

export const setEnrolGuideStatus = async ({ commit }, data) => {
  await commit(T.SET_ENROL_GUIDE_STATUS, data)
}

export const setEnrolCountryId = async ({ commit }, data) => {
  await commit(T.SET_ENROL_COUNTRY_ID, data)
}

export const loadEnrolProductCategories = ({ commit, dispatch, getters }) => {
  commit(T.PROCESSING_STARTED, 'enrolCategoriesLoading', { root: true })
  return get(U.ESHOP_PRODUCT_GET_PRODUCT_CATEGORIES)
    .then(response => {
      let categories = response.data
      commit(T.SET_ENROL_PRODUCT_CATEGORIES, categories)
      commit(T.PROCESSING_FINISHED, 'enrolCategoriesLoading', { root: true })
    })
    .catch(e => {
      dispatch('logError', { enrol_category_loading: e }, { root: true })
      throw e
    })
}

export const getStepValidationStatus = async ({ getters }, payload) => {
  let form = getters.getEnrolForm
  if (form !== undefined && form !== null && Object.keys(form).length > 0) {
    return Promise.resolve(form.step_states[payload])
  }
  return Promise.resolve(false)
}

export const postTempEnrolment = async ({ commit, dispatch, rootGetters, getters }, payload) => {
  commit(T.PROCESSING_STARTED, 'saveTempEnrolment', { root: true })
  let params = [constants.masterKey['PREFERRED_CONTACT'], constants.masterData['EMAIL']]
  // Data consistency for preferred contact
  if (
    helpers.getValue(payload, 'member_data.contact_info.preferred_contact_id') ===
      rootGetters.getEnrolmentMasterDataIdByKeyAndTitle(params[0], params[1]) ||
    helpers.getValue(payload, 'member_data.contact_info.preferred_contact_id') ===
      rootGetters.getMasterDataIdByKeyAndTitle(params[0], params[1])
  ) {
    payload.member_data.contact_info.mobile_1_country_code_id = null
    payload.member_data.contact_info.mobile_1_num = ''
  } else {
    payload.member_data.contact_info.email = ''
  }
  payload.rental_card_detail = {
    rental_card_data: getters['getRentalCardDataPayload'],
  }
  payload.is_rp = rootGetters['eshop/isShowRetailPrice']
  await post(U.API_POST_ENROLMENT, payload)
    .then(response => {
      commit(T.SET_POST_ENROLMENT, response.data)
      commit(T.PROCESSING_FINISHED, 'saveTempEnrolment', { root: true })
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'saveTempEnrolment', { root: true })
      dispatch('logError', { saveTempEnrolment: e.response.data }, { root: true })
      throw e
    })
}

export const getEnrolmentData = async ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'getEnrolmentData', { root: true })
  await post(U.API_GET_ENROLMENT, payload)
    .then(response => {
      commit(T.SET_GET_ENROLMENT, response.data)
      commit(T.PROCESSING_FINISHED, 'getEnrolmentData', { root: true })
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'getEnrolmentData', { root: true })
      dispatch('logError', { getEnrolmentData: helpers.getValue(e, 'response.data', {}) }, { root: true })
      throw e
    })
}

export const getIsEnrolTypeIsMember = ({ getters }) => {
  let isNotMemberEnrol = true
  if (getters.getEnrolForm !== null) {
    let typeID = getters.getEnrolForm.enrolment_type
    let isMemberType = getters.getEnrolmentTypes.find(
      type => type.id === typeID && (type.title === 'Member' || type.title === 'member')
    )
    if (isMemberType !== undefined) {
      isNotMemberEnrol = false
    }
  }
  return isNotMemberEnrol
}

export const loadEnrolmentTaiwanFiles = ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'enrolTaiwanFilesLoading', { root: true })
  return get(U.API_GET_ENROLMENT_TAIWAN_FILES + '/' + payload)
    .then(response => {
      commit(T.SET_ENROL_TAIWAN_FILES, response.data)
      commit(T.PROCESSING_FINISHED, 'enrolTaiwanFilesLoading', { root: true })
    })
    .catch(e => {
      commit(T.PROCESSING_FINISHED, 'enrolTaiwanFilesLoading', { root: true })
      if (e.response.data.token !== undefined) {
        dispatch('logError', { enrol_taiwan_files_loading: e.response.data.token[0] }, { root: true })
      } else {
        dispatch('logError', { enrol_taiwan_files_loading: e.response.data }, { root: true })
      }
      throw e
    })
}

export const updateEnrolmentLanguage = ({ commit, dispatch, getters, rootGetters }, language) => {
  if (rootGetters.getAppStatus('thirdparty') === false || localStorage.getItem(L.ENROL_SELECTED_LANGUAGE) !== null) {
    commit(T.SET_ENROLMENT_LANGUAGE, language)
  }
}

export const enrolmentTabStatus = ({ commit, state }) => {
  if (typeof window.__tabChecker === 'undefined' && process.env.VUE_APP_ENROLMENT_TABS_CHECKER === 'true') {
    let tabId = sessionStorage.tabId ? parseInt(sessionStorage.tabId) : (sessionStorage.tabId = new Date().getTime())
    // Detect if the tab was duplicated
    if (state.enrolmentTabStatus.tabs.find(x => x.id === tabId)) {
      tabId = sessionStorage.tabId = new Date().getTime()
    }

    commit(T.SET_ENROLMENT_TAB_STATUS, {
      tabId: tabId,
    })

    // Use worker to set timer because inactive tabs will give less priority to timer
    let worker = helpers.CreateWorker(function() {
      setInterval(function() {
        postMessage(1)
      }, 1000)
    })
    worker.onmessage = function() {
      commit(T.SET_ENROLMENT_TAB_STATUS, {
        tabId: tabId,
      })
    }
    window.__tabChecker = true
  }
}
export const loadBankList = ({ commit, getters }, countryId = null) => {
  let inputData = {
    country_id: countryId === null ? getters.getEnrolCountryId : 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 loadSalaryRangeList = ({ commit }) => {
  let inputData = {
    keys: ['salary_range'],
  }
  return post(U.MASTER_KEY_URL, inputData).then(response => {
    if (response.status === 200) {
      var salaryRanges = []
      response.data.salary_range.map(item => {
        salaryRanges.push({ salaryRangeId: item.id, salaryRangeName: item.title })
      })
      commit(T.SET_SALARY_RANGES_LIST, salaryRanges)
    }
  })
}
export const loadMembershipsList = ({ commit, getters }, countryId = null) => {
  let inputData = {
    country_id: countryId === null ? getters.getEnrolCountryId : countryId,
    keys: ['membership_type'],
  }
  return post(U.MASTER_KEY_URL, inputData).then(response => {
    if (response.status === 200) {
      var membershipTypes = []
      response.data.membership_type.map(item => {
        membershipTypes.push(item)
      })
      commit('SET_ENROLMENT_MEMBERSHIP_TYPES', membershipTypes)
    }
  })
}

export const resetMemberSponsor = ({ state, commit }, data = false) => {
  commit(T.MEMBER_SET_MEMBER_SPONSOR_ENROLMENT, data)
}

export const setEnrolProductSearchFilter = ({ commit }, data) => {
  commit(T.SET_ENROL_PRODUCT_SEARCH_FILTER, data)
}

export const updateEmploymentFormStatus = ({ commit, getters, rootGetters }, data) => {
  let platform =
    (rootGetters.getAppStatus('eshop') && 'eshop') || (rootGetters.getAppStatus('enrolment') && 'enrolment')
  commit(T.SET_EMPLOYMENT_FORM_STATUS, { platform: platform, value: data })
}
