<template>
  <b-container>
    <b-modal
      v-model="showRedemptionModal"
      ref="evoucher_shipping_modal"
      centered
      no-close-on-backdrop
      hide-header
      size="lg"
      :ok-title="$t('Common.Confirm')"
      :cancel-title="$t('Common.Cancel')"
      :busy="isLoading(['evoucherRedempting', 'evoucherLoading'])"
      cancel-variant="link"
      @hidden="closeModal()"
      @ok="shipProcessing"
    >
      <b-container class="eshop p-0 nh-50" v-bar="vueSidebarConfig">
        <div>
          <shipping-method
            class="p-2"
            :shipping-info="shippingInfo"
            ref="shippingMethod"
            data-qa-prefix="orderHistory-eVoucherShipping"
          />
        </div>
      </b-container>
    </b-modal>
    <b-modal
      ref="notice_ok"
      no-close-on-esc
      no-close-on-backdrop
      hide-header
      centered
      ok-only
      class="eshop-model"
      size="sm"
    >
      {{ $t('OrderHistory.Detail.eVoucher.RedemptionOk.Notice') }}
    </b-modal>
    <b-modal
      ref="notice_not_ok"
      no-close-on-esc
      no-close-on-backdrop
      hide-header
      centered
      ok-only
      class="eshop-model"
      size="sm"
    >
      {{ $t('OrderHistory.Detail.eVoucher.RedemptionFail.Notice') }}
    </b-modal>
  </b-container>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import ShippingMethod from '@/app/_global/components/blocks/ShippingMethod'
import _ from 'lodash'

export default {
  name: 'OrderHistoryEvoucherShipping',
  $_veeValidate: {
    validator: 'new',
  },
  components: {
    ShippingMethod,
  },
  props: {
    memberData: null,
  },
  data() {
    return {
      shippingInfo: {},
      evoucher: { evoucher_number: '' },
      vueSidebarConfig: {
        preventParentScroll: true,
        resizeRefresh: true,
      },
    }
  },
  methods: {
    ...mapActions('eshop', ['saveOrderShipping']),
    ...mapActions('orderhistory', ['setSalesVoucherToRedeem', 'setShowRedemptionModal', 'selectEvoucherProductsSizes']),
    ...mapActions([
      'loadCountries',
      'loadMyAccountInfo',
      'initializeShippingData',
      'loadStockistLocationAddressList',
      'redeemEvoucher',
      'loadEvoucherBySale',
    ]),
    shipProcessing(e) {
      e.preventDefault()
      let self = this
      this.$refs.shippingMethod.validate().then(shippingMethodValidation => {
        if (shippingMethodValidation) {
          let data = this.$refs.shippingMethod.getData()
          this.setSalesVoucherToRedeem(this.evoucher.id)
          this.saveOrderShipping(data)
          this.redeemEvoucher({
            shipping: this.getOrderShipping,
            sizes: this.getSelectedMasterIds(this.evoucher.id),
          }).then(() => {
            if (!this.getErrors('evoucherRedeem')) {
              this.selectEvoucherProductsSizes({ sizes: [], evoucher: [] })
              this.loadEvoucherBySale().then(() => {
                this.$emit('change')
                this.closeModal()
                this.$refs.notice_ok.show()
              })
            } else {
              this.$refs.notice_not_ok.show()
            }
          })
        } else {
          self.$scrollTo('[name="' + self.$refs.shippingMethod.$validator.errors.items[0].field + '"]')
        }
      })
    },
    getSelectedMasterIds(voucherId) {
      let result = []
      let selectedDummiesSize = this.getAllSelectedDummies.sizes.filter(dummy => dummy.voucher_id === voucherId)
      selectedDummiesSize.forEach(size => {
        this.getSalesDetails.products.forEach(product => {
          if (product.evoucher !== null && product.evoucher.id === size.voucher_id) {
            if (size.product_id === product.product_id) {
              if (
                result.find(
                  x => x.product_id === product.master_product_id && x.kitting_id === product.master_kitting_id
                ) === undefined
              ) {
                result.push({
                  product_id: product.master_product_id,
                  kitting_id: product.master_kitting_id,
                  dummy_id: size.dummy_id,
                  quantity: null,
                  data: _.map(size.data, function(item) {
                    if (item.foc_qty > 0) {
                      return {
                        ...item,
                        quantity: 0,
                      }
                    } else {
                      return item
                    }
                  }),
                })
              } else {
                result
                  .find(x => x.product_id === product.master_product_id && x.kitting_id === product.master_kitting_id)
                  .data.push(
                    ..._.map(size.data, function(item) {
                      if (item.foc_qty > 0) {
                        return {
                          ...item,
                          quantity: 0,
                        }
                      } else {
                        return item
                      }
                    })
                  )
              }
            }
          }
        })
        this.getSalesDetails.kittings.forEach(kitting => {
          if (kitting.evoucher !== null && kitting.evoucher.id === size.voucher_id) {
            kitting.kitting_products.forEach(product => {
              if (size.product_id === product.product_id) {
                if (
                  result.find(
                    x => x.product_id === product.master_product_id && x.kitting_id === product.master_kitting_id
                  ) === undefined
                ) {
                  result.push({
                    product_id: product.master_product_id,
                    kitting_id: product.master_kitting_id,
                    dummy_id: size.dummy_id,
                    quantity: null,
                    data: _.map(size.data, function(item) {
                      if (item.foc_qty > 0) {
                        return {
                          ...item,
                          quantity: 0,
                        }
                      } else {
                        return item
                      }
                    }),
                  })
                } else {
                  result
                    .find(x => x.product_id === product.master_product_id && x.kitting_id === product.master_kitting_id)
                    .data.push(
                      ..._.map(size.data, function(item) {
                        if (item.foc_qty > 0) {
                          return {
                            ...item,
                            quantity: 0,
                          }
                        } else {
                          return item
                        }
                      })
                    )
                }
              }
            })
          }
        })
      })
      return result
    },
    generateStockistAddressLists(payload) {
      return this.loadStockistLocationAddressList({
        country_id: this.getSelectedCountry.id,
        location_id: payload.location_id,
        sale_id: this.getSalesDetails.sale_id,
      })
    },
    closeModal() {
      this.setShowRedemptionModal(false)
    },
  },
  provide() {
    let self = this
    return {
      get _shipping_countries() {
        return self.getCountries
      },
      _self_pickup_load_stockist_address_list: self.generateStockistAddressLists,
    }
  },
  mounted() {
    let self = this
    self
      .loadMyAccountInfo()
      .then(() => {
        return self.initializeShippingData({
          member: self.memberData,
          countryId: self.getSelectedCountry.id,
          isPreferredEmail: self.getMyAccountMemberDetails.contact_info.preferred_contact_id === self.preferredEmailId,
        })
      })
      .then(() => {
        self.shippingInfo = _.cloneDeep(self.getShippingData)
      })
    this.loadCountries()
  },
  computed: {
    ...mapGetters('eshop', ['getOrderShipping']),
    ...mapGetters('orderhistory', ['getSelectedVoucher', 'getAllSelectedDummies', 'getShowRedemptionModal']),
    ...mapGetters([
      'getErrors',
      'isLoading',
      'getMyAccountMemberDetails',
      'getShippingData',
      'getCountries',
      'getSelectedCountry',
      'getStockistStatesByCountry',
      'getSalesDetails',
    ]),
    showRedemptionModal: {
      get: function() {
        return this.getShowRedemptionModal
      },
      set: function(value) {},
    },
  },
  watch: {
    getShowRedemptionModal(to) {
      if (to === true) {
        this.evoucher = this.getSelectedVoucher
      }
    },
  },
}
</script>
