<template>
  <div class="enrol-content-wrapper" :class="type !== 'start' ? 'basic' : 'fullscreen'" v-if="ready">
    <div class="guide-overly" v-if="getGuideStatus() && getEnrolGuideStatus">
      <div class="guide-close">
        <icon @click.native="toggleGuideStatus(false)" class="animated bounceInDown" name="close-icon" />
      </div>
      <div class="guide-text">
        <h4>{{ $t('Enrolment.Guide.Info') }}</h4>
      </div>
    </div>
    <div class="enrol-progress" v-if="type !== 'start' && type !== 'complete' && getIsTabActive !== false">
      <stepped
        :steps="selectedOrder"
        border-solid
        :icon-indicator="!$appSettings.evo.enable"
        :active-step="activeStep()"
        text-placement="top"
        center-full
        :callback="() => toggleGuideStatus(false)"
        :guide-status="getEnrolGuideStatus"
        class="mt-2 mb-2"
        v-if="initialized === true"
      >
        <template slot="textArea" slot-scope="textAreaProps">
          <h5 class="mt-2 mb-2 text-capitalize">
            {{ $t(textAreaProps.text.name) }}
          </h5>
        </template>
      </stepped>
    </div>
    <div class="enrol-info-area">
      <div class="enrol-info" v-show="isLoading('saveTempEnrolment')">
        {{ $t('Enrolment.Saving.Info') }}
      </div>
      <div class="enrol-info" v-show="isLoading('productsAddingToCart') && type !== 'start'">
        {{ $t('Enrolment.cartUpdating.Info') }}
      </div>
    </div>
    <div
      v-if="isLoading('loadingCart') && type === undefined"
      class="vh-50 d-flex justify-content-center align-items-center"
    >
      <icon name="spinner" pulse class="icon-size-4" />
    </div>
    <enrolment-tab-active v-else-if="getIsTabActive === false" />
    <div v-else>
      <enrolment-plan-selection-page
        v-if="type === 'start'"
        :apply-temp-enrolment-data="applyTempEnrolmentData"
        :sponsor="enrolmentData.sponsor_member_id"
        :previous="$t(previousRoute().previous)"
        :next="$t(nextRoute().next)"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
      />
      <enrolment-sales-kit-page
        v-if="type === 'select-starter-kit'"
        :current-page="parseInt(page || 1)"
        :previous="$t(previousRoute().previous)"
        :next="$t(nextRoute().next)"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
        :is-ek-smart="isEkSmart"
      />
      <enrolment-personal-data-page
        v-if="type === 'personal-data'"
        :previous="$t(previousRoute().previous)"
        :next="$t(nextRoute().next)"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
      />
      <enrolment-product-selection-page
        v-if="type === 'select-products'"
        :previous="$t(previousRoute().previous)"
        :next="$t(nextRoute().next)"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
        :is-ek-smart="isEkSmart"
      />
      <enrolment-sizes-selection-page
        v-if="type === 'select-sizes'"
        :previous="$t(previousRoute().previous)"
        :next="$t(nextRoute().next)"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
      />
      <enrolment-pwp-foc-page
        v-if="type === 'select-pwp-foc'"
        :previous="$t(previousRoute().previous)"
        :next="$t(nextRoute().next)"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
      />
      <enrolment-placement-selection-page
        v-if="type === 'placement'"
        :previous="$t(previousRoute().previous)"
        :next="$t(nextRoute().next)"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
      />
      <enrolment-order-review-page
        v-if="type === 'review-order'"
        :previous="$t(previousRoute().previous)"
        :next="next"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
        :is-ek-smart="isEkSmart"
      />
      <enrolment-payment-page
        v-if="type === 'checkout'"
        :previous="$t(previousRoute().previous)"
        :next="next"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
      />
      <enrolment-complete-page
        v-if="type === 'complete'"
        :previous="$t(previousRoute().previous)"
        :next="next"
        :next-action="next"
        :prev-action="previous"
        :enrolment-data="enrolmentData"
        @payment-complete="paymentComplete"
      />
    </div>
  </div>
</template>
<script>
import _ from 'lodash'
import Stepped from '@/app/_global/components/elements/Stepped'
import * as enrolmentComponents from './stepper/index'
import { ENROLMENT_START } from '@/config/url-prefix'
import { IS_LOGGED_IN_GETTER_NAME, IS_LOGGED_IN_GUEST_GETTER_NAME } from '@/config/defaults'
import enrolmentRoutingMixin from '@/app/enrolment/_global/mixins/enrolmentRoutingMixin'
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
import { EnrolmentProvider } from '@/providers'
import { mapMasterDataId } from '@/app/_global/mixins'
import EnrolmentTabActive from '../../_global/components/blocks/EnrolmentTabActive'
import moment from 'moment'

export default EnrolmentProvider.extend({
  name: 'landing',
  props: ['sponsorID', 'type', 'guide', 'page'],
  components: {
    EnrolmentTabActive,
    Stepped,
    ...enrolmentComponents,
  },
  mixins: [enrolmentRoutingMixin],
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (vm.isLoggedInGuest === false) {
        let query = '?medium=enrolment&referrer=' + (vm.sponsorID ? vm.sponsorID : '')
        vm.guestLogin(query).then(() => {
          next()
        })
      }
    })
  },
  computed: {
    ...mapGetters({
      isLoggedIn: [IS_LOGGED_IN_GETTER_NAME],
      isLoggedInGuest: [IS_LOGGED_IN_GUEST_GETTER_NAME],
      sponsorName: 'getMemberName',
      isGuestReady: 'isGuestReady',
      isLoading: 'isLoading',
      getEnrolmentRegion: 'getEnrolmentRegion',
      getLoggedInUser: 'getLoggedInUser',
      getExternalApiClassicCrossSponsoringVerificationHasApiError:
        'getExternalApiClassicCrossSponsoringVerificationHasApiError',
    }),
    ...mapGetters('enrolment', [
      'getEnrolForm',
      'getEnrolGuideStatus',
      'getTempEnrolForm',
      'getUpgradeDetails',
      'getIsTabActive',
      'getEnrolmentTypes',
    ]),
    ...mapGetters('eshop', ['getCartItems', 'getEligiblePromotion', 'getCartPreservationStatus']),
    ...mapMasterDataId({
      SALE_TYPES: {
        repurchaseSalesTypeId: 'RE_PURCHASE',
        registrationSalesTypeId: 'REGISTRATION',
        formationSalesTypeId: 'FORMATION',
        rentalSalesTypeId: 'RENTAL',
      },
      FILE_TYPE: {
        fileTypeImageId: 'IMAGE',
        fileTypePdfId: 'PDF',
      },
    }),
    ...mapState({
      authenticated: state => state.logModule.errors.Unauthenticated,
    }),
    isEkSmart() {
      return this.$helpers.getValue(this.getEnrolForm, 'membershipType', '').toLowerCase() === 'ek smart'
    },
  },
  watch: {
    initialized(to) {
      if (to) {
        this.$emit('initialized', to)
      }
    },
    type: {
      async handler() {
        await this.headerFooterVisibility()
        await this.checkSetNewEnrolProcessFlow()
      },
    },
    enrolmentData: {
      handler() {
        if (!this.resetData) {
          // reset data happens only once
          this.setEnrolForm(_.cloneDeep(this.enrolmentData))
        } else {
          this.resetData = false
        }
      },
      deep: true,
    },
    isGuestReady: {
      handler() {
        this.ready = true
      },
      deep: true,
    },
    getEnrolGuideStatus: {
      handler() {
        this.enrolmentData.guide = this.getEnrolGuideStatus
      },
    },
    getCartItems: {
      handler() {
        this.initRouting()
      },
    },
    'getEnrolForm.enrolment_type': {
      async handler(to, from) {
        if (Number.isInteger(to) && to !== from) {
          this.loadCartDefaultItems()
        }
      },
    },
    'getEnrolmentRegion.id': {
      async handler(to, from) {
        if (Number.isInteger(to) && to !== from) {
          this.loadCartDefaultItems()
        }
      },
    },
    authenticated(to) {
      if (to === true) {
        // recreate guest token if use is unauthenticated by any means
        let query = '?medium=enrolment&referrer=' + (this.sponsorID ? this.sponsorID : '')
        this.guestLogin(query).then(() => {
          window.location.reload()
        })
      }
    },
    getExternalApiClassicCrossSponsoringVerificationHasApiError(to) {
      this.enrolmentData.member_data.details.is_cross_sponsor_error = to
    },
  },
  data() {
    return {
      ready: false,
      windowWidth: 0,
      resetData: false,
      defaultEnrolmentData: null,
      enrolmentData: {
        membershipType: 'Standard',
        temp_save: 1,
        step_states: {
          start: false,
          'select-starter-kit': false,
          'personal-data': false,
          'select-products': false,
          'select-sizes': true,
          'select-pwp-foc': false,
          placement: false,
          'review-order': false,
          checkout: false,
        },
        guide: true,
        global: 1,
        region: null,
        language: null,
        enrolment_type: '',
        sponsor_member_id: '',
        sponsor_name: '',
        sponsor_user_id: '',
        without_sponsor: 0,
        on_behalf_enrolment: 0,
        agreement: '',
        agreement_1: '',
        amp_preference: null,
        verification: {
          code: '',
          get: {},
          post: {},
        },
        sales_data: {},
        member_data: {
          details: {
            nationality_id: '',
            name: '',
            translated_name: '',
            ic_pass_type_id: '',
            ic_passport_number: '',
            date_of_birth: '',
            tin_no_taiwan: '',
            tin_no_philippines: '',
            is_cross_sponsor_error: 0,
            occupation: '',
            salary_range: '',
          },
          information: {
            gender_id: '',
            language_id: '',
            ethnic_group_id: '',
            martial_status_id: '',
            spouse: {
              spouse_elken_member: 0,
              spouse_ibo_id: '',
              ic_pass_type_id: null,
              ic_pass_type_number: '',
              spouse_name: '',
              dob: null,
            },
          },
          verification: [],
          contact_info: {
            preferred_contact_id: '',
            email: '',
            mobile_1_country_code_id: null,
            mobile_1_num: '',
            tel_office_1_country_code_id: null,
            tel_office_1_num: '',
            tel_home_1_country_code_id: null,
            tel_home_1_num: '',
          },
          address: {
            address_data: [],
          },
        },
        recurring_info: {
          card: {
            card_type_id: '',
            card_company_id: '',
            expiry_date: '',
            card_number: '',
            issued_bank: '',
            name_on_card: '',
            card_type: '',
            cardDocuments: [],
            otherDocuments: [],
          },
        },
        payee_info: {
          mpay: {
            card_country__name: '',
            card_holder_name: '',
            card_number: '',
            expiry_date: '',
            expiry_year: '',
          },
          bank: {
            bank_country_name: '',
            bank_id: '',
            bank_account_ic: '',
            payout_comapny: '',
            swift_code: '',
            account_number: '',
            account_type: '',
            account_holder_name: '',
          },
        },
        placement: {
          placement_position: 0,
          placement_member_user_id: '',
          placement_member_id: '',
          placement_member_name: '',
          placement_same_as_sponsor: 0,
        },
        supportingDocs: [],
        created_by: null,
      },
    }
  },
  created() {
    this.defaultEnrolmentData = { ...(this.defaultEnrolmentData || this.enrolmentData) }
    if (this.isLoggedInGuest) {
      this.ready = true
    }
    if (this.getEnrolForm !== null && Object.keys(this.getEnrolForm).length > 0) {
      this.enrolmentData = _.cloneDeep(this.getEnrolForm)
    } else {
      let routeMeta = { name: 'Enrolment Steps', params: { type: 'start' } }

      if (this.$route.params.hasOwnProperty('sponsorID')) {
        routeMeta['query'] = { redirect: true }
      }
      this.$router.replace(routeMeta)
      if (this.resetData) {
        window.location = ENROLMENT_START
      }
    }
    this.enrolmentTabStatus()
  },
  async mounted() {
    if (this.sponsorID) {
      this.enrolmentData.sponsor_member_id = await this.sponsorID
      this.enrolmentData.global = 0
    }
    if (this.type) {
      this.$emit('initialized', true)
    }
    this.$nextTick(() => {
      window.addEventListener('resize', this.getWindowWidth)
    })
    this.getWindowWidth()
    await this.initEnrolment()
    this.enrolmentData.created_by = this.$helpers.getValue(this.getLoggedInUser, 'id', null)
  },
  methods: {
    async loadCartDefaultItems() {
      /**
       * restructure flow for member type fresh enrolment
       */
      await this.resolveMasters // wait for master data to resolve
      if (this.getCartPreservationStatus) {
        this.validateRoutes = true
      } else {
        await this.clearCart()
      }
      // set default statues
      this.enrolmentData.step_states = {
        ...this.enrolmentData.step_states,
        'select-starter-kit': false,
        'personal-data': false,
        'select-products': false,
        'select-sizes': false,
        'select-inst-address': false,
        'select-pwp-foc': false,
        placement: false,
        'review-order': false,
        checkout: false,
      }
    },
    ...mapMutations({
      processingStart: 'PROCESSING_STARTED',
    }),
    ...mapActions(['guestLogin', 'getDynamicContent', 'clearLoadedData', 'logoutGuest']),
    ...mapActions('enrolment', [
      'setEnrolForm',
      'setEnrolGuideStatus',
      'getStepValidationStatus',
      'getIsEnrolTypeIsMember',
      'enrolmentTabStatus',
      'getMember',
      'updateEmploymentFormStatus',
    ]),
    ...mapActions('eshop', [
      'loadProducts',
      'loadMasterDataKeysEnrolment',
      'addProductToCart',
      'clearCart',
      'loadCart',
      'addToCartByProductFilters',
      'saveOrderShipping',
    ]),
    checkSetNewEnrolProcessFlow() {
      this.initRouting()
      /**
       * restructure flow for member upgrade
       */
      if (Object.keys(this.getUpgradeDetails).length > 0) {
        let id = 1
        if (this.getEnrolmentTypes.length > 0) {
          id = this.getEnrolmentTypes.find(x => x.title === 'BA').id
        }
        this.enrolmentData.enrolment_type = id
      }
    },
    async applyTempEnrolmentData() {
      if (this.getTempEnrolForm !== null && Object.keys(this.getTempEnrolForm).length > 0) {
        this.processingStart('applyTempEnrolmentData')
        this.enrolmentData = _.cloneDeep(this.getTempEnrolForm)
        if (this.$helpers.isSet(this.getTempEnrolForm, 'sponsor_member_id')) {
          let query = {
            exact_text: this.getTempEnrolForm.sponsor_member_id,
            limit: 1,
            minimal: true,
          }
          await this.getMember(query)
        }
      }
    },
    toggleGuideStatus(status) {
      if (status !== undefined) {
        this.setEnrolGuideStatus(status).then(() => {
          if (status) {
            jQuery('body').css({ overflow: 'hidden' })
            jQuery(window).scrollTop(0)
          } else {
            jQuery('body').css({ overflow: 'auto' })
          }
        })
      }
    },
    getDate: function(date) {
      return moment(date).format('DD/MM/YYYY')
    },
    paymentComplete() {
      this.routeInitialize.then(() => {
        // clear data
        this.resetData = true
        this.clearLoadedData('enrolment')
        this.updateEmploymentFormStatus(false)
        // set default form
        this.setEnrolForm(null)
        // logout guest
        this.logoutGuest()
        // Re create guest token
        let query = '?medium=enrolment&referrer=' + (this.sponsorID ? this.sponsorID : '')
        this.guestLogin(query)
      })
    },
    activeStep() {
      return this.selectedOrder.findIndex(x => x.type === this.type)
    },
    headerFooterVisibility() {
      let header = jQuery('#enrol-header')
      let footer = jQuery('#enrol-footer')
      if (this.type === 'start' && this.windowWidth >= 1024) {
        header.hide()
        footer.hide()
      } else {
        header.show()
        footer.show()
      }
    },
    getWindowWidth() {
      this.windowWidth = document.documentElement.clientWidth
      this.headerFooterVisibility()
    },
    getGuideStatus() {
      let step = this.selectedOrder.find(x => x.type === this.type)
      if (step !== undefined) {
        if (step.guide !== undefined && step.guide) {
          if (this.getEnrolGuideStatus) {
            jQuery(window).scrollTop(0)
          }
          return true
        }
      }
      return false
    },
  },
})
</script>
