<template>
  <div :class="wrapperClasses">
    <b-container fluid :class="containerClass">
      <div>
        <span
          v-show="errors.has('Shipping Method') || errors.has('Delivery Method')"
          class="help text-danger float-right animated flash"
        >
          {{ $t('Eshop.Order.Shipping.Method.Delivery.NotSelected') }}
        </span>
        <h5 class="text-primary mb-4 mt-0" v-if="!hideTitle">
          {{ $t('Common.ShippingMethod') }}
        </h5>

        <b-form-group>
          <b-form-radio-group
            buttons
            class="w-100"
            button-variant="outline-primary"
            v-model="shippingInfo.sale_delivery_method"
            :disabled="isLoading(['loadingCart', 'locationsLoadStockistLocations', 'loadStockistLocationAddressList'])"
          >
            <b-form-radio
              v-if="shippingMethodDeliveryId !== null"
              :value="shippingMethodDeliveryId"
              class="py-3 w-50 text-left d-flex align-items-center"
              :data-qa="`${dataQaPrefix}-shippingMethod-delivery-radio`"
            >
              <icon name="eshop-delivery" class="icon-size-3 px-2" />
              <span>{{ $t('Eshop.Order.Shipping.Method.Delivery.Title') }}</span>
            </b-form-radio>
            <b-form-radio
              v-if="!(hideSelfCollection || shippingMethodSelfCollectionId === null)"
              :value="shippingMethodSelfCollectionId"
              class="py-3 w-50 text-left d-flex align-items-center"
              :data-qa="`${dataQaPrefix}-shippingMethod-selfCollection-radio`"
            >
              <icon name="eshop-selfCollection" class="icon-size-3 px-2" />
              <span>{{ $t('Eshop.Order.Shipping.Method.SelfCollection.Title') }}</span>
            </b-form-radio>
          </b-form-radio-group>
        </b-form-group>
        <div>
          <shipping-method-delivery
            v-if="shippingInfo.sale_delivery_method === shippingMethodDeliveryId"
            :address-style="addressStyle"
            :shipping-info="shippingInfo"
            :enable-cross-country="enableCrossCountry"
            ref="shippingMethodDelivery"
            v-model="deliveryModel"
            :class="shippingMethodDeliveryClasses"
            :allow-save-shipping-address="allowSaveShippingAddress"
            :shipping-method-form-field-row-size-classes="shippingMethodFormFieldRowSizeClasses"
            :show-shipping-empty-address-info="showShippingEmptyAddressInfo"
          />
          <shipping-method-self-collection
            v-if="shippingInfo.sale_delivery_method === shippingMethodSelfCollectionId"
            :shipping-info="shippingInfo"
            ref="shippingMethodSelfCollection"
            v-model="shippingModel"
            :class="shippingMethodSelfCollectionClasses"
          />
        </div>
      </div>
    </b-container>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import shippingMethodDelivery from './ShippingMethodDelivery'
import shippingMethodSelfCollection from './ShippingMethodSelfCollection'
import { GeneralMixin, mapMasterDataId } from '../../mixins'
import _ from 'lodash'

export default {
  name: 'ReviewAndShipping',
  mixins: [GeneralMixin],
  props: {
    shippingInfo: {
      type: Object,
      required: true,
    },
    enableCrossCountry: {
      type: Boolean,
      default: false,
    },
    allowSaveShippingAddress: {
      type: Boolean,
      default: true,
    },
    wrapperClasses: {
      type: Array,
      default: () => ['border'],
    },
    containerClass: {
      type: Array,
      default: () => [],
    },
    shippingMethodDeliveryClasses: {
      type: Array,
      default: () => [],
    },
    shippingMethodFormFieldRowSizeClasses: {
      type: [Array, String],
    },
    shippingMethodSelfCollectionClasses: {
      type: Array,
      default: () => [],
    },
    hideTitle: {
      type: Boolean,
      default: false,
    },
    showShippingEmptyAddressInfo: {
      type: Boolean,
      default: false,
    },
    addressStyle: {
      type: String,
      default: 'list',
    },
    hideSelfCollectionOption: {
      type: Boolean,
      default: false,
    },
    dataQaPrefix: {
      type: String,
      required: true,
    },
  },
  $_veeValidate: {
    validator: 'new',
  },
  data() {
    return {
      deliveryModel: {},
      shippingModel: {},
      currentData: {},
    }
  },
  created() {
    this.$validator.attach({
      name: 'Shipping Method',
      rules: 'required',
      getter: () => {
        let self = this
        return self.shippingInfo.sale_delivery_method
      },
    })
  },
  components: {
    shippingMethodDelivery,
    shippingMethodSelfCollection,
  },
  methods: {
    ...mapActions(['loadStates', 'loadEsacStateCity', 'loadEsacActiveCountry']),
    getData() {
      let data = {}
      if (this.shippingInfo.sale_delivery_method === this.shippingMethodDeliveryId) {
        data = this.deliveryModel
      } else if (this.shippingInfo.sale_delivery_method === this.shippingMethodSelfCollectionId) {
        data = this.shippingModel
      }
      data.sale_delivery_method = this.shippingInfo.sale_delivery_method
      return data
    },
    updateModel() {
      let newData = this.getData()
      if (!_.isEqual(this.currentData, newData)) {
        this.currentData = _.cloneDeep(newData)
        this.$emit('input', newData)
      }
    },
    validate() {
      let validators = [this.$validator.validate()]
      if (this.$refs.shippingMethodDelivery !== undefined) {
        validators.push(this.$refs.shippingMethodDelivery.$validator.validateAll())
      } else if (this.$refs.shippingMethodSelfCollection !== undefined) {
        validators.push(this.$refs.shippingMethodSelfCollection.$validator.validateAll())
      }

      return Promise.all([...validators]).then(async function(validation) {
        return validation.indexOf(false) === -1 && validation.indexOf(undefined) === -1
      })
    },
  },
  watch: {
    'shippingInfo.sale_delivery_method'() {
      this.errors.remove('deliveryMethodError')
    },
    deliveryModel: {
      handler() {
        this.updateModel()
      },
      deep: true,
    },
    shippingModel: {
      handler() {
        this.updateModel()
      },
      deep: true,
    },
  },
  computed: {
    ...mapGetters(['isLoading', 'getMasterDataByKey', 'getAppStatus']),
    ...mapGetters('eshop', ['getCartIsRentalSaleOrder', 'getCartHasRental']),
    ...mapMasterDataId({
      SALE_DELIVERY_METHOD: {
        shippingMethodDeliveryId: 'DELIVERY',
        shippingMethodSelfCollectionId: 'SELF_PICKUP',
      },
    }),
    hideSelfCollection() {
      if (this.hideSelfCollectionOption) {
        return true
      }
      if (this.getAppStatus('enrolment') === true || this.getAppStatus('eshop') === true) {
        return this.getCartHasRental
      } else {
        return false
      }
    },
  },
}
</script>
