import { mapGetters, mapActions } from 'vuex'
import {
  ENROLMENT,
  ENROLMENT_SPONSOR,
  ENROLMENT_CHECKOUT,
  ENROLMENT_CHECKOUT_SELECT_SIZES,
  ENROLMENT_PERSONAL_DATA,
  ENROLMENT_PLACEMENT,
  ENROLMENT_REVIEW_ORDER,
  ENROLMENT_SELECT_PRODUCTS,
  ENROLMENT_START,
  ENROLMENT_COMPLETE,
  ENROLMENT_PWP_FOC,
  ENROLMENT_SELECT_SALES_KIT,
} from '@/config/url-prefix'
import validatedRouteMixin from '@/app/_global/mixins/validatedRouteMixin'
import { IS_LOGGED_IN_GUEST_GETTER_NAME } from '@/config/defaults'
import { RouteHasPath } from '@/helpers/routing'
import { mapMasterDataId } from '@/app/_global/mixins'
import _ from 'lodash'
import AppSettings from '@/config/app-settings'

export default {
  mixins: [validatedRouteMixin],
  data() {
    let self = this
    return {
      routingOrder: [
        {
          id: 1,
          path: ENROLMENT_START,
          type: 'start',
          previous: 'Common.Back',
          show: false,
          state: false,
          validate: () => self.$route.query.redirect === 'true' || self.getEnrolForm !== null,
        },
        {
          id: 2,
          name: 'Enrolment.Steps.StarterKit.Label',
          type: 'select-starter-kit',
          guide: true,
          show: true,
          state: false,
          selectable: { name: 'Enrolment Steps', params: { type: 'select-starter-kit', page: 1 } },
          path: ENROLMENT_SELECT_SALES_KIT + '/1',
          next: 'Enrolment.Enroll.Now',
          previous: 'Common.Back',
          addCallback: () => self.showSalesKitPageStep,
          validate: async (route, routingTo) =>
            self.$route.query.redirect === 'true' ||
            RouteHasPath(routingTo.path, ENROLMENT_SELECT_SALES_KIT) ||
            routingTo.path === ENROLMENT_START
              ? true
              : await self.getStepValidationStatus(route.type),
          error: () =>
            !self.getCartHasStarterKit && { starterKitError: self.$t('Enrolment.SelectProducts.ChooseProducts') },
        },
        {
          id: 3,
          name: 'Enrolment.Steps.PersonalData.Label',
          type: 'personal-data',
          order: 2,
          guide: () => !self.showSalesKitPageStep || self.getCartHasStarterKit,
          state: false,
          selectable: () => {
            if (self.showSalesKitPageStep && !self.getCartHasStarterKit) {
              return undefined
            }
            return { name: 'Enrolment Steps', params: { type: 'personal-data' } }
          },
          show: true,
          path: ENROLMENT_PERSONAL_DATA,
          params: 'personal-data',
          validate: async (route, routingTo) =>
            self.$route.query.redirect === 'true' ||
            ((RouteHasPath(routingTo.path, ENROLMENT_SELECT_PRODUCTS) || routingTo.path === ENROLMENT_START) &&
              self.getErrorsState('saveTempEnrolment')) ||
            routingTo.path === ENROLMENT_CHECKOUT_SELECT_SIZES
              ? true
              : await self.getStepValidationStatus(route.params),
          next: (AppSettings.evo.enable && 'Common.Continue') || 'Enrolment.Enroll.Now',
          previous: 'Common.Cancel',
          error: { personalData: self.$t('Enrolment.PersonalData.ValidationError') },
        },
        {
          id: 4,
          name: 'Common.CheckoutSteps.SelectProduct',
          type: 'select-products',
          order: 1,
          guide: () => !self.showSalesKitPageStep || self.getCartHasStarterKit,
          selectable: () => {
            if (self.showSalesKitPageStep && !self.getCartHasStarterKit) {
              return undefined
            }
            return { name: 'Enrolment Steps', params: { type: 'select-products' } }
          },
          show: true,
          state: false,
          path: ENROLMENT_SELECT_PRODUCTS,
          next: 'Enrolment.Confirm.Button',
          previous: 'Enrolment.Cancel.Button',
          params: 'select-products',
          validate: async (route, routingTo) =>
            self.$route.query.redirect === 'true' ||
            RouteHasPath(routingTo.path, ENROLMENT_SELECT_PRODUCTS) ||
            routingTo.path === ENROLMENT_PERSONAL_DATA ||
            routingTo.path === ENROLMENT_START
              ? true
              : await self.getStepValidationStatus(route.params),
          error: { productError: self.$t('Enrolment.SelectProducts.ChooseProducts') },
        },
        {
          id: 5,
          name: 'Enrolment.Steps.SelectSizes.Label',
          type: 'select-sizes',
          show: true,
          state: false,
          selectable: { name: 'Enrolment Steps', params: { type: 'select-sizes' } },
          path: ENROLMENT_CHECKOUT_SELECT_SIZES,
          previous: 'Enrolment.Cancel.Button',
          next: 'Common.Next',
          addCallback: self.cartNeedSelection,
          validate: async (route, routingTo) =>
            self.$route.query.redirect === 'true' ||
            RouteHasPath(routingTo.path, ENROLMENT_SELECT_PRODUCTS) ||
            routingTo.path === ENROLMENT_PERSONAL_DATA ||
            routingTo.path === ENROLMENT_START
              ? true
              : await self.checkCartDummyAllSizesSelected(),
          error: { cartError: self.$t('Eshop.SizeSelection.PleaseSelect') },
        },
        {
          id: 6,
          name: 'Enrolment.Steps.Promotions.Label',
          type: 'select-pwp-foc',
          show: true,
          state: false,
          selectable: { name: 'Enrolment Steps', params: { type: 'select-pwp-foc' } },
          path: ENROLMENT_PWP_FOC,
          previous: 'Enrolment.Cancel.Button',
          next: 'Common.Next',
          addCallback: () => {
            return Promise.resolve(self.getEligiblePromotion && self.getEligiblePromotion.length > 0)
          },
          validate: async (route, routingTo) =>
            self.$route.query.redirect === 'true' ||
            RouteHasPath(routingTo.path, ENROLMENT_SELECT_PRODUCTS) ||
            routingTo.path === ENROLMENT_PERSONAL_DATA ||
            routingTo.path === ENROLMENT_START
              ? true
              : self.getPwpFocSelectionComplete === true && (await self.getStepValidationStatus(route.params)),
        },
        {
          id: 7,
          name: 'Enrolment.Steps.Placement.Label',
          type: 'placement',
          order: 3,
          show: true,
          state: false,
          path: ENROLMENT_PLACEMENT,
          params: 'placement',
          addCallback: () => {
            if (self.$appSettings.placementPreference.showEnrolmentPlacementPage) {
              return Promise.resolve(
                self.$helpers.getValue(self.getEnrolForm, 'enrolment_type') ===
                  self.$helpers.getValue(
                    self.getEnrolmentTypes.find(x => x.title === 'BA'),
                    'id',
                    0
                  )
              )
            } else {
              return false
            }
          },
          validate: async (route, routingTo) =>
            self.$route.query.redirect === 'true' ||
            RouteHasPath(routingTo.path, ENROLMENT_SELECT_PRODUCTS) ||
            routingTo.path === ENROLMENT_PERSONAL_DATA ||
            routingTo.path === ENROLMENT_START ||
            routingTo.path === ENROLMENT_PLACEMENT
              ? true
              : await self.getStepValidationStatus(route.params),
          next: 'Common.Next',
          previous: 'Enrolment.Cancel.Button',
        },
        {
          id: 8,
          name: 'Enrolment.Steps.ReviewOrder.Label',
          type: 'review-order',
          order: 4,
          show: true,
          state: false,
          path: ENROLMENT_REVIEW_ORDER,
          next: 'Common.Next',
          previous: 'Enrolment.Cancel.Button',
          validate: async (route, routingTo) =>
            self.$route.query.redirect === 'true' ||
            RouteHasPath(routingTo.path, ENROLMENT_SELECT_PRODUCTS) ||
            routingTo.path === ENROLMENT_PERSONAL_DATA ||
            routingTo.path === ENROLMENT_START
              ? true
              : self.getOrderShipping !== null && self.getCheckout.status === true,
        },
        {
          id: 9,
          name: 'Common.Sales.PreCheckout',
          type: 'checkout',
          order: 5,
          show: true,
          state: false,
          path: ENROLMENT_CHECKOUT,
          next: 'Common.Next',
          title: 'Enrolment.Cancel.Button',
        },
        {
          id: 10,
          show: false,
          state: false,
          path: ENROLMENT_COMPLETE,
          next: 'Common.Next',
          previous: 'Enrolment.Cancel.Button',
        },
      ],
      initialized: false,
    }
  },
  watch: {
    getEnrolForm: {
      handler() {
        this.setCurrentValidStates()
      },
      deep: true,
    },
  },
  computed: {
    ...mapGetters('eshop', [
      'getOrderShipping',
      'getCartDisplayItems',
      'getEligiblePromotion',
      'getFocSelectionComplete',
      'getPwpFocSelectionComplete',
      'getCartTotal',
      'getCheckout',
      'getCartHasStarterKit',
    ]),
    ...mapGetters([
      'getEnrolmentRegion',
      'getErrorsState',
      'afterLoading',
      'getSelectedCountry',
      {
        isLoggedInGuest: [IS_LOGGED_IN_GUEST_GETTER_NAME],
      },
    ]),
    ...mapGetters('enrolment', ['getEnrolForm', 'getEnrolmentTypes']),
    ...mapMasterDataId({
      PROMOTION_FREE_ITEM_PROMO_TYPES: {
        focId: 'PROMO_TYPE_FOC',
        pwpfId: 'PROMO_TYPE_PWPF',
        pwpnId: 'PROMO_TYPE_PWPN',
      },
    }),
    showSalesKitPageStep() {
      return (
        AppSettings.evo.enable &&
        this.$helpers.getValue(this.getEnrolForm, 'membershipType') === this.$const.masterKey.STANDARD
      )
    },
  },
  methods: {
    ...mapActions(['logError']),
    ...mapActions('enrolment', ['getStepValidationStatus', 'getIsEnrolTypeIsMember']),
    ...mapActions('eshop', [
      'cartNeedSelection',
      'loadCart',
      'checkCartDummyAllSizesSelected',
      'pwpFocSelectionComplete',
    ]),
    async initEnrolment() {
      if (!this.isLoggedInGuest) {
        await this.afterLoading('guest_login')
      }
      this.validateRoutes = _.find(this.routingOrder, { path: this.$route.path }) !== undefined
      await this.initRouting()
      if (
        this.$route.path !== ENROLMENT &&
        this.$route.path !== ENROLMENT_START &&
        this.$route.path !== ENROLMENT_SPONSOR
      ) {
        if (this.getEnrolmentRegion !== undefined) {
          await this.loadCart({
            countryId: this.getEnrolmentRegion.id,
            locationId: this.getEnrolmentRegion.entity.locations[0].id,
            ekSmart: this.$helpers.getValue(this.getEnrolForm, 'membershipType', '').toLowerCase() === 'ek smart',
          })
        }
      }
      if (this.selectedOrder.findIndex(route => route.path === this.$route.path) === -1) {
        let routeMeta = { path: this.selectedOrder[0].path }

        if (this.$route.params.hasOwnProperty('sponsorID')) {
          routeMeta['query'] = { redirect: true }
        }
        // route to first page if the addRouteCallback return false on the current route
        this.$router.replace(routeMeta)
      }
      await this.setCurrentValidStates()
      this.initialized = true
      // })
    },
    setCurrentValidStates() {
      if (this.getEnrolForm !== null) {
        let steps = this.getEnrolForm.step_states
        if (steps !== undefined) {
          Object.entries(steps).forEach(async ([key, value]) => {
            let step = this.selectedOrder.find(x => x.type === key)
            if (step !== undefined) {
              let originalStep = this.routingOrder.find(y => y.id === step.id)
              if (originalStep !== undefined) {
                originalStep.state = value
              }
            }
          })
        }
      }
    },
  },
}
