<template>
  <b-row>
    <b-col lg="8" class="mb-1">
      <bundle-info-form
        v-if="!isUpdate || (isUpdate && bundleInformation)"
        v-model="bundleInformation"
        data-qa-prefix="myBundle-bundleInformationStep"
        :bundle-items="getBundleCartDetails.bundleItems"
        :bundle-prices="getBundleCartDetails.bundleTotal"
        :currency="currency || ''"
        :bundle-price-options="bundleConfig.priceTypes"
        :bundle-checkout-enrolment-types="bundleConfig.enrolmentTypes"
        ref="bundleInfoForm"
      />
    </b-col>
    <b-col lg="4" class="border-top border-lg-left border-lg-top-0 pb-5">
      <bundle-image-display
        class="mt-3 mt-lg-0"
        :image-src="bundleImageSrc"
        :loading="isLoading('uploading-my-bundle-image')"
      />
      <b-form-file
        v-show="!uploadStatus"
        placeholder=""
        v-model="bundleImageInput"
        class="no-overflow no-wrap"
        accept="image/png, image/jpeg"
        :browse-text="$t('Common.UploadImage')"
      />
      <div class="text-right mt-3" v-show="uploadStatus">
        <b-button variant="link" class="mr-2" @click="saveBundleImage(false)">{{ $t('Common.Cancel') }}</b-button>
        <b-button variant="primary" @click="saveBundleImage">{{ $t('Common.Confirm') }}</b-button>
      </div>
    </b-col>
  </b-row>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { CurrencyMixin, UploaderMixin } from '@/app/_global/mixins'
import MyBundleCommonMixin from '@/app/my-bundle/mixins/myBundleCommonMixin'
import BundleInfoForm from '@/app/my-bundle/_global/components/blocks/BundleInfoForm'
import BundleImageDisplay from '@/app/my-bundle/_global/components/blocks/BundleImageDisplay'

export default {
  name: 'BundleInformationStep',
  mixins: [MyBundleCommonMixin, CurrencyMixin, UploaderMixin],
  components: { BundleImageDisplay, BundleInfoForm },
  data() {
    return {
      uploadStatus: false,
      bundleImageSrc: null,
      bundleImageInput: null,
      bundleInformation: null,
      oriBundleImageSrc: null,
      errorBag: new Map([
        ['CART_ERR', { text: this.$t('Common.Cart.EmptyCart'), type: 'warning' }],
        ['REQUEST_FAIL_ERR', { text: this.$t('Common.Error.ActionFailure.HelpText'), type: 'error' }],
        ['NO_PRICE_ERR', { text: this.$t('MyBundle.Error.NoPriceSelection'), type: 'warning', timer: '4000' }],
        ['REQUIRED_FIELD_ERR', { text: this.$t('Common.Error.RequiredField'), type: 'warning', timer: '4000' }],
      ]),
    }
  },
  computed: {
    ...mapGetters(['getUploads', 'isLoading']),
    ...mapGetters('myBundle', ['getBundleDetails', 'getBundleCartDetails']),
    isUpdate() {
      return Boolean(this.$route.query.id)
    },
  },
  mounted() {
    this.loadBundleConfig()
  },
  methods: {
    ...mapActions('myBundle', ['createBundle', 'updateBundle']),
    saveBundleImage(save) {
      if (!save) {
        this.bundleImageSrc = this.oriBundleImageSrc
      }
      this.bundleImageInput = null
      this.uploadStatus = false
    },
    validateAndSubmit() {
      let self = this
      let errorStatus = false
      let actionTitle = this.isUpdate ? 'MyBundle.GenerateBundle.UpdateBundle' : 'MyBundle.GenerateBundle.CreateBundle'
      let itemsValidation = this.getBundleCartDetails.bundleItems.length > 0
      let priceValidation = true

      if (this.$appSettings.bundle.dynamicPrice.enable) {
        let { isPriceTypeSelected, isBundleCheckoutEnrolmentTypeSelected } = this.$refs.bundleInfoForm

        priceValidation = isPriceTypeSelected && isBundleCheckoutEnrolmentTypeSelected
      }

      let preValidation = itemsValidation && priceValidation

      return this.$refs.bundleInfoForm.$validator.validate().then(async valid => {
        if (valid && preValidation) {
          let action = self.isUpdate ? self.updateBundle : self.createBundle
          let {
            bundleName,
            bundleDescription,
            bundleEnrolmentType,
            useMemberPrice,
            useRetailPrice,
          } = self.bundleInformation
          let configs = []

          if (useMemberPrice) {
            configs = [
              this.bundleConfig.priceTypes.find(config => config.key === 'bundle_member_price'),
              this.bundleConfig.enrolmentTypes.find(type => type.key === bundleEnrolmentType),
            ]
          }

          if (useRetailPrice) {
            configs.push(this.bundleConfig.priceTypes.find(config => config.key === 'bundle_retail_price'))
          }

          let payload = {
            bundleName,
            bundleDescription,
            bundleImage: self.bundleImageSrc,
            bundleId: self.$route.query.id,
            configs: configs.filter(config => config),
          }

          await action(payload).then(result => {
            if (result) {
              this.$swal({ title: this.$t(actionTitle + '.Success'), timer: '2400', type: 'success' })
              this.$router.replace({ name: 'MyBundleDetails', params: { bundleId: result.bundle_id } })
              return true
            } else {
              errorStatus = 'REQUEST_FAIL_ERR'
            }
          })
        } else {
          /* we not specific throwing enrolment type missing error here, when enrolment types not returning by backend,
            but we will set 'REQUEST_FAIL_ERR' instead */
          errorStatus =
            (!valid && 'REQUIRED_FIELD_ERR') ||
            (self.getBundleCartDetails.bundleItems.length < 1 && 'CART_ERR') ||
            (priceValidation === false && 'NO_PRICE_ERR') ||
            'REQUEST_FAIL_ERR'
        }

        if (errorStatus) {
          self.$swal({
            title: this.$t(actionTitle + '.Fail'),
            ...self.errorBag.get(errorStatus),
          })
        }
        return false
      })
    },
  },
  watch: {
    getBundleDetails: {
      handler(value) {
        if (this.isUpdate && value.bundle_id) {
          this.bundleInformation = {
            bundleName: value.bundle_name,
            bundleDescription: value.bundle_description,
            useMemberPrice: this.hasConfig('bundle_member_price', value.bundle_configs),
            useRetailPrice: this.hasConfig('bundle_retail_price', value.bundle_configs),
            bundleEnrolmentType: this.getBundleCheckoutEnrolmentKey(value.bundle_configs) || null,
          }
          this.oriBundleImageSrc = value.bundle_image
          this.bundleImageSrc = value.bundle_image
        }
      },
      immediate: true,
    },
    bundleImageInput(value) {
      if (value) {
        let self = this
        this.files = [value]
        this.params = { file_type: 'product_bundle_image' }
        this.uploader('my-bundle-image').then(() => {
          if (self.getUploads.length > 0) {
            self.getUploads.forEach(item => {
              self.bundleImageSrc = item.link
              self.uploadStatus = true
            })
          } else {
            self.uploadStatus = false
            self.bundleImageInput = null
          }
        })
      }
    },
  },
}
</script>
