<template>
  <div>
    <div v-if="dynamicFieldContent.length > 0">
      <b-form-group>
        <b-form-radio-group id="bonus-info-type" name="Bank Radio" v-model="bonusInfoTypeValue">
          <b-row>
            <b-col cols="12">
              <b-row class="m-0">
                <b-col
                  v-for="(group, groupIndex) in getDynamicContentComputed(dynamicContentVariable).elements"
                  :key="`group-${groupIndex}`"
                  class="py-2 border"
                >
                  <component
                    v-for="(processElement, processIndex) in processElements(group)"
                    :key="`element-${processIndex}`"
                    radio-type="b-form-radio"
                    :radio-show-label="false"
                    :readonly="disabledStatus"
                    v-model="bonusInfoTypeValue"
                    :is="processElement()"
                  />
                </b-col>
              </b-row>
            </b-col>
          </b-row>
        </b-form-radio-group>
      </b-form-group>

      <b-row>
        <b-col>
          <keep-alive v-for="(fieldElement, fieldIndex) in dynamicFieldContent" :key="`element-value-${fieldIndex}`">
            <!-- element that has 2 fields -->
            <div v-if="Array.isArray(fieldElement.subs)">
              <component :is="fieldTemplateComponent">
                <label slot="label">{{ fieldElement.field.label }}</label>
                <component
                  v-for="(subEl, subI) in fieldElement.subs"
                  :key="`element-value-${fieldIndex}-sub-${subI}`"
                  :is="subEl.component"
                  v-model="dynamicDataModel[subEl.field.index]"
                  :readonly="disabledStatus"
                  @triggerIndex="triggered"
                />
              </component>
            </div>
            <!-- element that has single field -->
            <div v-else>
              <component
                :is="fieldElement.component"
                :key="`element-value-${fieldIndex}-sub-1`"
                :readonly="disabledStatus"
                v-model="dynamicDataModel[fieldElement.field.index]"
                @triggerIndex="triggered"
              />
            </div>
          </keep-alive>
        </b-col>
      </b-row>
      <b-row class="pt-3">
        <b-col>
          <span v-if="disabledStatus" class="font-weight-bold-extra">
            * {{ $t('MyAccount.BonusInfo.ContactSupport') }}
          </span>
          <span ref="saveButton">
            <template v-if="!isLoading('updateMemberPayoutInfo')">
              <span v-if="responseStatus === true" class="text-info-green pr-3">
                {{ $t('MyAccount.PersonalInfo.SaveChanges.Success') }}
              </span>
              <span v-else-if="responseStatus === false" class="text-danger pr-3">
                {{ $t('MyAccount.PersonalInfo.SaveChanges.Failed') }}
              </span>
            </template>
            <b-button
              v-if="!disabledStatus"
              variant="primary"
              @click="saveBonusInfo"
              :class="saveButtonClass"
              class="d-flex align-items-center"
              :disabled="isLoading('updateMemberPayoutInfo')"
              :data-qa="`${dataQaPrefix}-saveChanges-btn`"
            >
              <b-spinner v-show="isLoading('updateMemberPayoutInfo')" small class="mr-2" />
              <span>{{ saveButtonLabel || $t('Common.SaveChanges') }}</span>
            </b-button>
          </span>
        </b-col>
      </b-row>
    </div>
    <div v-else-if="hasLoaded('loadingCountryDynamicContent') && dynamicFieldContent.length === 0" class="my-4">
      <!--      This scenario will happen when no backend dynamic content was return -->
      <h6>{{ $t('Common.UnexpectedErrorHeader.Msg') }}</h6>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import { mapActions, mapGetters } from 'vuex'
import ProcessElements from '@/app/_global/utils/process-elements'

export default {
  name: 'BackAccountInfo',
  $_veeValidate: {
    validator: 'new',
  },
  props: {
    dataQaPrefix: { type: String, required: true },
    fieldLabelClass: { type: String, default: '' },
    saveButtonLabel: { type: String, default: '' },
    saveButtonClass: { type: [String, Array], default: () => ['float-right'] },
  },
  data() {
    return {
      bonusInfoTypeValue: null,
      disabledStatus: false,
      fieldsTemplate: {
        template: {
          default: `<b-row class="py-2">
                        <b-col cols="12" class="${this.fieldLabelClass}">
                          <slot name="label"/>
                        </b-col>
                        <b-col >
                          <slot/>
                        </b-col>
                      </b-row>`,
        },
      },
      shareFieldRow: {
        template: {
          default: `<b-row class="py-2">
                        <b-col cols="12" class="${this.fieldLabelClass}">
                          <slot name="label"/>
                        </b-col>
                        <b-col>
                          <b-row class="ml-0">
                            <slot/>
                          </b-row>
                        </b-col>
                      </b-row>`,
        },
      },
      shareFieldsTemplate: {
        template: {
          default: `<b-col class="pl-0">
                        <slot/>
                      </b-col>`,
        },
      },
      dynamicDataModel: [],
      calledDynamicContentActions: [],
      dynamicContentVariable: 'logged_in_member_payout_options',
      responseStatus: null,
    }
  },
  watch: {
    getMemberPayoutDynamicData(to) {
      if (to.elements.length === 0) {
        this.dynamicContentVariable = 'member_payout_options'
      } else {
        this.disabledStatus = true
      }
    },
    getMyAccountMemberDetails(to) {
      let banking = to.banking
      if (typeof banking.payment_data.selected !== 'undefined' && banking.payment_data.selected !== '') {
        this.disabledStatus = true
      }
    },
    dynamicActions(to, from) {
      let actions = _.difference(to, from)
      let self = this
      if (actions.length) {
        actions.forEach(action => {
          if (!_.find(self.calledDynamicContentActions, action)) {
            self.calledDynamicContentActions.push(action)
            self.$store.dispatch(action.action, action.payload)
          }
        })
      }
    },
    bonusInfoTypeValue() {
      // force selected dynamic fields update
      this.dynamicDataModel = []
    },
    dynamicDataModel() {
      for (let i in this.dynamicDataModel) {
        if (this.dynamicDataModel.hasOwnProperty(i)) {
          if (this.dynamicDataModel[i] !== undefined && this.dynamicDataModel[i] !== null) {
            this.updateDynamicByIdValue({
              name: this.dynamicContentVariable,
              elementIndex: this.bonusInfoTypeValue,
              fieldIndex: parseInt(i),
              fieldValue: this.dynamicDataModel[i],
            })
          }
        }
      }
    },
  },
  computed: {
    ...mapGetters([
      'getMyAccountMemberDetails',
      'getDynamicContentComputed',
      'getDynamicContentActions',
      'isLoading',
      'hasLoaded',
    ]),
    element() {
      let elements = this.processElements({
        link: {
          url: 'https://',
          text: 'test',
        },
      })

      return elements
        ? elements[0]
        : {
            is: '',
            bind: {},
          }
    },
    fieldTemplateComponent() {
      return {
        template: this.shareFieldRow.template.default,
      }
    },
    dynamicActions() {
      return this.getDynamicContentActions(this.dynamicContentVariable)
    },
    getMemberPayoutDynamicData() {
      return this.getDynamicContentComputed('logged_in_member_payout_options')
    },
    selectedDynamicFields() {
      let elements = this.getDynamicContentComputed(this.dynamicContentVariable).elements
      if (elements.length === 0) {
        return []
      } else if (elements.length > 1) {
        let selectedFields = _.find(elements, { value: this.bonusInfoTypeValue })

        if (selectedFields) {
          return selectedFields.fields
        } else {
          return elements[0].fields
        }
      } else {
        return elements[0].fields
      }
    },
    dynamicFieldContent() {
      let fields = []

      let shared = []
      for (let i in this.selectedDynamicFields) {
        let field = this.selectedDynamicFields[i]

        if (field.share) {
          let elements = this.processElements(field, this.shareFieldsTemplate)

          let shareInserted = _.find(fields, { locate: 'share', index: field.index })

          let shareInsertedWith = _.find(fields, { locate: 'share', with: field.index })

          if (shareInserted === undefined && shareInsertedWith === undefined) {
            fields.push({
              locate: 'share',
              field: field,
              index: field.index,
              with: field.share.index,
            })
          }

          shared.push({
            index: field.index,
            element: {
              field: field,
              component: elements[0]({
                hideLabel: true,
              }),
            },
          })
        } else {
          let elements = this.processElements(field, this.fieldsTemplate)

          elements.forEach(element => {
            fields.push({
              field: field,
              component: element(),
            })
          })
        }
      }

      // process shared
      fields = fields.map(field => {
        if (field.locate) {
          return {
            field: field.field,
            subs: [_.find(shared, { index: field.index }).element, _.find(shared, { index: field.with }).element],
          }
        } else {
          return field
        }
      })

      return fields
    },
  },
  methods: {
    ...mapActions(['updateDynamicByIdValue', 'updateMemberPaymentInfoByDynamicContent']),
    processElements: ProcessElements,
    triggered(value) {
      this.updateDynamicByIdValue({
        name: this.dynamicContentVariable,
        elementIndex: this.bonusInfoTypeValue,
        fieldIndex: value.index,
        fieldValue: value.value,
      })
    },
    saveBonusInfo() {
      let self = this
      this.$validator.validateAll().then(valid => {
        if (valid) {
          this.updateMemberPaymentInfoByDynamicContent(this.dynamicContentVariable).then(status => {
            self.responseStatus = status
            this.$emit('submit', status)
          })
        }
      })
    },
  },
}
</script>
