<template>
  <div class="page signup-page membership">
    <div class="container">
      <div v-show="!isShowRetailPrice" class="row">
        <div class="col-12">
          <h5>
            {{ $t('3rdParty.Checkout.Membership.ChooseMembership.Title') }}
          </h5>
          <p>
            {{ $t('3rdParty.Checkout.Membership.ChooseMembership.SubTitle') }}
          </p>
        </div>
        <div class="col-md-4" v-for="(enrolment, index) in enrolmentTypes" :key="`${index}-enrolment-types`">
          <div class="card mb-3">
            <div class="card-header p-2">
              <div class="custom-control custom-checkbox">
                <b-form-checkbox
                  :name="$t('Common.MembershipType')"
                  :class="fields[$t('Common.MembershipType')]"
                  v-model="membership.enrolment_type_id"
                  :value="enrolment.id"
                  :unchecked-value="null"
                  v-validate="{ required: !isShowRetailPrice }"
                >
                  {{ getEnrolmentRankTitle(enrolment.title) }}
                </b-form-checkbox>
              </div>
            </div>
            <div
              @click="membership.enrolment_type_id = enrolment.id"
              class="card-body"
              style="font-size: 14px; font-size: 0.9rem; line-height: 23px;"
              v-html="getEnrolmentInfo(enrolment.title)"
            ></div>
          </div>
        </div>
        <div class="col-12">
          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Common.MembershipType')" />
        </div>
      </div>
      <div class="row mt-5">
        <div class="col-12">
          <h5>
            {{ $t('3rdParty.Checkout.Membership.MembershipDetails.Title') }}
          </h5>
        </div>
        <div class="col-md-6">
          <h6 class="font-weight-light">
            {{ $t('3rdParty.Checkout.Membership.MembershipDetails1.SubTitle') }}
          </h6>
          <div class="mw-xl-50 mw-lg-100">
            <b-form-group label-for="input-1" :label="$t('Enrolment.Country.Label')">
              <b-form-select disabled v-model="membership.country_id" v-validate="'required'">
                <template v-for="(country, index) in getCountries">
                  <option :value="country.value" :key="index">{{ country.custom_text }}</option>
                </template>
              </b-form-select>
              <field-errors :cerrors="errors" :cfields="fields" :name="$t('Enrolment.Country.Label')" />
            </b-form-group>
          </div>
          <div class="mw-xl-50 mw-lg-100">
            <div class="form-group">
              <b-form-group label-for="input-1" :label="$t('Common.Language')">
                <b-form-select
                  :name="$t('Common.Language')"
                  v-model="membership.language_id"
                  :options="getLanguageList"
                  v-validate="'required'"
                />
                <field-errors :cerrors="errors" :cfields="fields" :name="$t('Common.Language')" />
              </b-form-group>
            </div>
          </div>
        </div>
        <div class="col-md-6" v-if="membership.sponsor">
          <h6 class="font-weight-light text-dark" v-html="getIntroducedTitleTranslation"></h6>
          <div class="mt-2">
            <div class="form-group mw-lg-50 mw-lg-100" style="position: relative;">
              <b-form-group label-for="input-1" :label="$t('3rdParty.Checkout.Membership.Sponsor.Label')">
                <b-form-input
                  :data-vv-as="$t('3rdParty.Checkout.Membership.Sponsor.Label')"
                  name="MembershipSponsor"
                  @blur="searchSponsor(false)"
                  v-model="membership.sponsor.sponsor_member_id"
                  :class="fields[$t('3rdParty.Checkout.Membership.Sponsor.Label')]"
                  v-validate="'required'"
                />
                <field-errors :cerrors="errors" :cfields="fields" name="MembershipSponsor" />
              </b-form-group>
              <div class="text-center control-spinner" id="divSponsorSpinner" v-if="isLoading('getMember')">
                <div class="spinner-border" role="status">
                  <span class="sr-only"> Loading...</span>
                </div>
              </div>
            </div>
            <div id="divSponsorInfo">
              <div
                class="form-text text-danger"
                v-if="errors.has('MembershipSponsor') && getSponsorDetails.is_empty === true"
              >
                Cannot found sponsor name
              </div>
              <div class="media align-items-center mt-3" v-else-if="getSponsorDetails.is_empty === undefined">
                <img class="rounded-circle mr-3" src="@@/assets/images/rounded-image-placeholder.jpg" />
                <div class="media-body">
                  <h6 class="mb-1">{{ getSponsorDetails.name }}</h6>
                  <div style="font-size: 16px; font-size: 1rem;">{{ getSponsorDetails.country[0].custom_text }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import FieldErrors from '@/elements/common/components/FieldErrors'
import { APP_MEMBERSHIP_FORM } from '@@/store/localStorageKeys'
import _ from 'lodash'
import { SELECTED_COUNTRY } from '@/store/utils/localStorageKeys'

export default {
  name: 'MembershipPage',
  components: { FieldErrors },
  inject: ['$validator'],
  props: {
    navigateNext: {
      type: Function,
    },
  },
  computed: {
    ...mapGetters(['getCountries', 'getLanguageList', 'getAppLocationCountry', 'getSelectedLanguage', 'isLoading']),
    ...mapGetters('enrolment', {
      enrolmentTypes: 'getEnrolmentTypes',
      getSponsorDetails: 'getSponsorDetails',
    }),
    ...mapGetters('3rdPartyCheckoutMembership', ['getMembershipInfo', 'getSponsorIBOFromLink']),
    ...mapGetters('eshop', ['isShowRetailPrice']),
    getIntroducedTitleTranslation() {
      return this.$t('3rdParty.Checkout.Membership.MembershipDetails2.SubTitle', {
        trademark: '<sup class="trademark">' + this.$t('3rdParty.Common.Trademark.Text') + '</sup>',
      })
    },
  },
  watch: {
    membership: {
      handler(to) {
        this.setLocalForm({ namespace: '3rdPartyCheckoutMembership/', key: APP_MEMBERSHIP_FORM, formData: to })
      },
      deep: true,
    },
  },
  data: () => ({
    membership: {},
  }),
  async mounted() {
    this.membership = _.cloneDeep(this.getMembershipInfo)
    this.$validator.attach({
      name: 'isSponsorSelected',
      rules: 'required',
      getter: () => {
        return this.membership.sponsor.sponsor_user_id
      },
    })
    await this.countryHandler()
    if (this.getSponsorIBOFromLink) {
      await this.searchSponsor(this.getSponsorIBOFromLink)
    }
    if (this.membership.sponsor.sponsor_member_id.length < 1) {
      this.resetMemberSponsor()
    }
    if (this.isShowRetailPrice && this.getSponsorDetails.user_id === '') {
      this.isRetailPrice(false)
    } else if (this.isShowRetailPrice && this.getSponsorDetails.is_empty !== true) {
      this.membership.enrolment_type_id = null
      this.navigateNext()
    }
  },
  methods: {
    ...mapActions(['loadLanguages', 'updateSelectedCountry', 'getSelectedCountry']),
    ...mapActions('enrolment', ['getEnrolmentsTypes', 'getMember', 'resetMemberSponsor']),
    ...mapActions('3rdPartyCheckoutGlobal', ['setLocalForm']),
    ...mapActions('3rdPartyCheckoutMembership', ['removeEkbdSponsor']),
    ...mapActions('eshop', ['isRetailPrice']),
    async countryHandler() {
      this.membership.country_id = this.$helpers.getValue(this.getAppLocationCountry, 'countryId')
      await this.loadLanguages({ country_id: this.membership.country_id })
      await this.getEnrolmentsTypes({
        country_id: this.membership.country_id,
        sort: 'id',
        order: 'desc',
      })

      if (
        this.membership.language_id !== undefined &&
        this.getLanguageList.findIndex(x => x.value === this.membership.language_id) === -1
      ) {
        this.membership.language_id = this.$helpers.getValue(this.getLanguageList, '[0].value', null)
      }

      if (
        this.membership.enrolment_type_id !== undefined &&
        this.enrolmentTypes.findIndex(x => x.id === this.membership.enrolment_type_id) === -1
      ) {
        this.membership.enrolment_type_id = null
      }
      this.membership.country = this.getCountries.filter(x => x.value === this.membership.country_id)
    },
    async searchSponsor(customText = false) {
      if (customText) {
        this.membership.sponsor.sponsor_member_id = customText
      }
      if (this.membership.sponsor.sponsor_member_id.length > 0) {
        let query = {
          exact_text: this.membership.sponsor.sponsor_member_id,
          limit: 1,
          is_ba_only: true,
          minimal: true,
        }
        await this.getMember(query)
        this.membership.sponsor.sponsor_user_id = this.$helpers.getValue(this.getSponsorDetails, 'user_id', null)
        this.membership.sponsor.sponsor_name = this.$helpers.getValue(this.getSponsorDetails, 'name', null).toString()
        this.membership.sponsor.sponsor_member_id = this.$helpers
          .getValue(this.getSponsorDetails, 'member_id', null)
          .toString()
        this.removeEkbdSponsor()
      } else {
        this.resetMemberSponsor()
      }
    },
    async validateAndSubmit() {
      if (
        !!this.getSponsorDetails.member_id &&
        this.getSponsorDetails.member_id.toString() === this.membership.sponsor.sponsor_member_id
      ) {
        // Check if the saved sponsor ID is same as the current inserted ID
        return await this.$validator.validate().then(valid => {
          let localCountryDetails = JSON.parse(localStorage.getItem(SELECTED_COUNTRY))

          if (valid && localCountryDetails && this.getSelectedCountry.id !== localCountryDetails.id) {
            // re update country data if not match with localstorage value (mainly target to solve wordpress mounting site issue)
            this.updateSelectedCountry(localCountryDetails.id)
          }

          this.membership.status = valid
          return valid
        })
      } else if (this.membership.sponsor.sponsor_member_id) {
        // If a new sponsor ID inserted and not same with the saved ID
        this.$swal({
          title: this.$t('3rdParty.Common.HoldOn'),
          text: this.$t('3rdParty.Checkout.Membership.SponsorChecks.Loading'),
          timer: '4000',
          type: 'info',
        })
      } else {
        // If the sponsor field is empty
        await this.$validator.validate()
      }
      return false
    },
    getEnrolmentRankTitle(rank) {
      rank = (rank || '').toLowerCase()
      return (
        (rank === 'ba' && this.$t('Common.Terminology.Rank.Ba')) ||
        (rank === 'preferred customer' && this.$t('Common.Terminology.Rank.PreferredCustomer')) ||
        ''
      )
    },
    getEnrolmentInfo(rank) {
      rank = (rank || '').toLowerCase()

      return (
        (rank === 'ba' && this.$t('Enrolment.TypeInfo.BA')) ||
        (rank === 'preferred customer' && this.$t('Enrolment.TypeInfo.PreferredCustomer')) ||
        ''
      )
    },
  },
}
</script>
