import { mapActions, mapGetters } from 'vuex'
import { getValue } from '@/helpers/variable-handling'

export default {
  async mounted() {
    await this.loadBankList()
  },
  computed: {
    ...mapGetters(['getBankName', 'getMyAccountMemberDetails', 'getMasterDataByKey']),
  },
  methods: {
    ...mapActions(['loadBankList']),
    getBankDetails(rawBankData) {
      let result = []
      if (rawBankData) {
        let selectedBankData = (rawBankData.bank_data || []).find(
          data => data.id !== undefined && data.id === rawBankData.selected
        )

        if (selectedBankData) {
          result = (selectedBankData.fields || [])
            .filter(field => !field.hidden)
            .map(field => {
              let { label, order, value, autofill, key, type } = field

              if (value === '' && autofill) {
                value = getValue(this.getMyAccountMemberDetails, autofill, '')
              }

              if (key === 'banks') {
                value = this.getBankName(value)
              } else if (key === 'master') {
                if (type === 'masters-select') {
                  let options = this.getMasterDataByKey(field.identifier) || []
                  value = (options.find(option => option.id === value) || {}).title
                }
              } else if (type === 'custom-select' && field.options) {
                value = (field.options.find(option => option.value === value) || {}).label
              }

              return { label, order, value }
            })
            .sort((a, b) => a.order - b.order)
        }
      }
      return result
    },
  },
}
