import * as T from '../../../utils/types'
import * as L from '../../../utils/localStorageKeys'
import defaultState from './index'
import Vue from 'vue'
import _ from 'lodash'
import helpers from '@/helpers'

export default {
  [T.MEMBER_SET_MEMBER_SPONSOR_ENROLMENT](state, payload) {
    state.sponsorMemberDetails = payload
    localStorage.setItem(L.ENROL_SPONSOR_MEMBER, JSON.stringify(payload))
  },
  [T.SET_SUPPORTING_DOC_DETAILS](state, payload) {
    state.supportingDocDetails = payload
    localStorage.setItem(L.SUPPORTING_DOC_DETAILS, JSON.stringify(payload))
  },
  [T.SET_NRIC_DOC_DETAILS](state, payload) {
    state.nricDocsDetails = payload
    localStorage.setItem(L.NRIC_DOCS_DETAILS, JSON.stringify(payload))
  },
  [T.SET_CART_RENTAL_DETAILS](state, payload) {
    if (payload.isEnrolment === true) {
      state.rentalCardDetails = payload
      localStorage.setItem(L.CARD_RENTAL_DETAILS, JSON.stringify(payload))
    } else {
      state.rentalCardDetailsEshop = payload
      localStorage.setItem(L.CARD_RENTAL_DETAILS_ESHOP, JSON.stringify(payload))
    }
  },
  [T.SET_SELECTED_RECURRING_INFO_TYPE](state, payload) {
    state.selectedRecurringInfoType = payload
    localStorage.setItem(L.SELECTED_RECURRING_INFO_TYPE, JSON.stringify(payload))
  },
  [T.SET_BANK_CARD_DETAILS](state, payload) {
    state.bankCardDetails = payload
    localStorage.setItem(L.BANK_CARD_DETAILS, JSON.stringify(payload))
  },
  [T.SET_MPAY_DETAILS](state, payload) {
    state.mPayDetails = payload
    localStorage.setItem(L.MPAY_DETAILS, JSON.stringify(payload))
  },
  [T.MEMBER_SET_MEMBER_PLACEMENT_LIST_ENROLMENT](state, payload) {
    state.placementMemberDetails = payload
    localStorage.setItem(L.ENROL_PLACEMENT_MEMBER, JSON.stringify(payload))
  },
  [T.MEMBER_SET_UPGRADE_USER](state, payload) {
    state.upgradeMemberDetails = payload
    localStorage.setItem(L.ENROL_UPGRADE_MEMBER, JSON.stringify(payload))
  },
  [T.SET_VERIFICATION_GET](state, payload) {
    state.verification.get = payload
  },
  [T.SET_VERIFICATION_POST](state, payload) {
    state.verification.post = payload
  },
  [T.SET_ENROL_FORM](state, payload) {
    state.enrolForm = { ...payload }
    localStorage.setItem(L.ENROL_FORM, JSON.stringify({ ...payload }))
  },
  [T.REMOVE_VERIFICATIONS](state) {
    state.verification.get = {}
  },
  [T.SET_ENROLMENT_TYPES](state, payload) {
    state.enrolmentTypes = payload
    localStorage.setItem(L.ENROL_TYPES, JSON.stringify(payload))
  },
  [T.SET_MEMBER_PLACEMENT_VERIFY](state, payload) {
    state.memberPlacementVerify = payload
  },
  [T.SET_ENROL_GUIDE_STATUS](state, payload) {
    state.guide = payload
    localStorage.setItem(L.ENROL_GUIDE_STATUS, payload)
  },
  [T.SET_ENROL_COUNTRY_ID](state, payload) {
    state.country_id = payload.country_id
    localStorage.setItem(L.ENROL_COUNTRY_ID, JSON.stringify(payload.country_id))
  },
  [T.SET_ENROL_PRODUCT_CATEGORIES](state, data) {
    state.categories = data
    localStorage.setItem(L.ENROL_PRODUCT_CATEGORIES, JSON.stringify(state.categories))
  },
  [T.SET_POST_ENROLMENT](state, payload) {
    state.enrolmentData = payload
  },
  [T.SET_GET_ENROLMENT](state, payload) {
    // TODO: remove and load from dynamic content itself
    let tempdata = payload.temp_data
    if (typeof tempdata === 'string') {
      tempdata = JSON.parse(tempdata)
    }
    let rentalCardInformation = helpers.getValue(tempdata, 'rental_card_detail.rental_card_data', false)
    if (['string', 'object'].includes(typeof rentalCardInformation) && !helpers.isEmpty(rentalCardInformation)) {
      let rentalCardData = {
        'Card Type': 'card_type_id',
        'Card Network': 'card_company_id',
        'Issuing Bank': 'country_bank_id',
        'Name on Card': 'card_holder_name',
        'Card No': 'card_number',
        'Credit/ Debit Card': 'credit_card_photocopy',
        'Expiry Date': 'card_expiry_date',
      }
      let rentalCardPayload = {
        card_type_id: '',
        card_company_id: '',
        country_bank_id: '',
        card_holder_name: '',
        card_number: '',
        credit_card_photocopy: '',
        card_expiry_date: '',
      }
      if (typeof rentalCardInformation === 'string') {
        rentalCardInformation = JSON.parse(rentalCardInformation)
      }
      let rentalFields = false
      if (rentalCardInformation.recurring_info !== undefined && rentalCardInformation.selected !== undefined) {
        let selectedRental = _.find(rentalCardInformation.recurring_info, { id: rentalCardInformation.selected })
        if (selectedRental.fields !== undefined) {
          rentalFields = selectedRental.fields
        }
      }
      if (rentalFields !== false) {
        for (let i in rentalFields) {
          let rentalCardKey = _.find(Object.keys(rentalCardData), o => {
            return new RegExp(o).test(rentalFields[i].label) === true
          })
          if (rentalCardKey) {
            rentalCardPayload[rentalCardData[rentalCardKey]] = rentalFields[i].value
          }
        }
        state.rentalCardDetails = rentalCardPayload
        localStorage.setItem(L.CARD_RENTAL_DETAILS, JSON.stringify(rentalCardPayload))
      }
    }
    state.tempEnrolmentData = payload
  },
  [T.SET_ENROL_TAIWAN_FILES](state, payload) {
    state.enrolmentTaiwanFiles = payload
  },
  [T.CLEAR_LOADED_DATA](state, type) {
    if (type === 'enrolment' || !type) {
      localStorage.removeItem(L.ENROL_PRODUCT_CATEGORIES)
      localStorage.removeItem(L.ENROL_COUNTRY_ID)
      localStorage.removeItem(L.ENROL_GUIDE_STATUS)
      localStorage.removeItem(L.ENROL_FORM)
      localStorage.removeItem(L.ENROL_TYPES)
      localStorage.removeItem(L.ENROL_UPGRADE_MEMBER)
      localStorage.removeItem(L.ENROL_SPONSOR_MEMBER)
      localStorage.removeItem(L.ENROL_ADDRESS)
      localStorage.removeItem(L.SUPPORTING_DOC_DETAILS)
      localStorage.removeItem(L.BANK_CARD_DETAILS)
      localStorage.removeItem(L.MPAY_DETAILS)
      localStorage.removeItem(L.CARD_RENTAL_DETAILS)
      state = defaultState.state
      state.enrolForm = {}
    }
  },
  [T.SET_ENROLMENT_LANGUAGE](state, data) {
    state.selectedEnrolLanguage = data
    if (
      state.selectedEnrolLanguage !== null &&
      state.selectedEnrolLanguage !== undefined &&
      state.selectedEnrolLanguage.key !== undefined
    ) {
      localStorage.setItem(L.ENROL_SELECTED_LANGUAGE, JSON.stringify(state.selectedEnrolLanguage))
      Vue.i18n.set(state.selectedEnrolLanguage.key.toLowerCase())
    }
  },
  [T.SET_ENROLMENT_TAB_STATUS](state, data) {
    state.enrolmentTabStatus.disableChecker = false
    let tabStatus = JSON.parse(localStorage.getItem(L.ENROL_TAB_STATUS))
    if (tabStatus !== undefined && tabStatus !== null) {
      state.enrolmentTabStatus = tabStatus
    }
    data.tabId = parseInt(data.tabId)
    // Detect first enrolment tab
    if (state.enrolmentTabStatus.activeTabId === undefined || state.enrolmentTabStatus.activeTabId === false) {
      state.enrolmentTabStatus.activeTabId = data.tabId
    }
    let tabIndex = _.findIndex(state.enrolmentTabStatus.tabs, ['id', data.tabId])
    // Add tab if its not found
    if (tabIndex === -1) {
      state.enrolmentTabStatus.tabs.push({
        id: data.tabId,
        timestamp: new Date().getTime(),
      })
    } else {
      // Update tab if its found
      state.enrolmentTabStatus.tabs[tabIndex].timestamp = new Date().getTime()
    }
    // remove inactive tabs
    state.enrolmentTabStatus.tabs = _.filter(state.enrolmentTabStatus.tabs, function(tab) {
      return new Date().getTime() - tab.timestamp < 3000
    })
    if (
      state.enrolmentTabStatus.activeTabId !== false &&
      _.find(state.enrolmentTabStatus.tabs, ['id', state.enrolmentTabStatus.activeTabId]) === undefined
    ) {
      state.enrolmentTabStatus.activeTabId = false
    }
    localStorage.setItem(L.ENROL_TAB_STATUS, JSON.stringify(_.omit(state.enrolmentTabStatus, 'status')))
  },
  [T.SET_BANK_LIST](state, data) {
    state.bankList = data
  },
  [T.SET_SALARY_RANGES_LIST](state, data) {
    state.salaryRanges = data
  },
  [T.SET_ENROLMENT_MEMBERSHIP_TYPES](state, data) {
    state.membershipTypes = data
    localStorage.setItem('MEMBERSHIP_TYPES', JSON.stringify(state.membershipTypes))
  },
  [T.SET_ENROLMENT_MEMBERSHIP_TYPE](state, data) {
    state.membership_type = data
    localStorage.setItem('MEMBERSHIP_TYPE', JSON.stringify(state.membership_type))
  },
  [T.SET_DYNAMIC_RECURRING_INFO](state, data) {
    state.cardRecurringInfoFields = data
    localStorage.setItem(L.ENROL_RECURRING_INFO, JSON.stringify(state.cardRecurringInfoFields))
  },
  [T.SET_DYNAMIC_PAYEE_INFO](state, data) {
    state.payeeInfoFields = data
    localStorage.setItem(L.ENROL_PAYEE_INFO, JSON.stringify(state.payeeInfoFields))
  },
  [T.SET_DYNAMIC_EMPLOYMENT_DETAILS](state, data) {
    if (data !== undefined) {
      data = JSON.parse(data)
      if (typeof data === 'object' && data !== null) {
        data = _.sortBy(
          data.filter(x => x.platform === 'eshop'),
          'order'
        )
      }
    }
    state.employmentDetailsFields = data
    try {
      localStorage.setItem(L.ENROL_EMPLOYMENT_DETAILS, JSON.stringify(state.employmentDetailsFields))
    } catch (e) {
      /* eslint no-console: ["error", { allow: ["warn", "error"] }] */
      console.error(e)
    }
  },
  [T.SET_EMPLOYMENT_FORM_STATUS](state, data) {
    state.employmentFormStatus[data.platform] = data.value
    sessionStorage.setItem(L.ENROL_EMPLOYMENT_FORM_STATUS, JSON.stringify(state.employmentFormStatus))
  },
  [T.SET_ENROL_PRODUCT_SEARCH_FILTER](state, data) {
    state.productSearchFilter = data
  },
}
