<template>
  <b-col lg="12" class="p-0">
    <b-row>
      <b-col lg="10">
        <b-row class="my-2">
          <b-col cols="12">
            <h6>{{ $t('3rdParty.Checkout.AutoshipShippingSelection.Title') }}</h6>
          </b-col>
        </b-row>
        <shipping-method
          class="p-1 bg-white"
          :hide-title="true"
          :wrapper-classes="['shipping-wrapper']"
          :shipping-method-delivery-classes="['shipping-delivery-method']"
          :shipping-method-self-collection-classes="['shipping-self-collection-method']"
          :shipping-info="autoshipShippingInfo"
          v-model="autoshipShippingModel"
          :allow-save-shipping-address="false"
          shipping-method-form-field-row-size-classes="col-lg-12"
          :show-shipping-empty-address-info="true"
          :enable-cross-country="true"
          data-qa-prefix="autoship-shippingAndPayment"
          ref="billingAddressInfo"
        />
      </b-col>
      <b-col lg="8" class="mt-3">
        <!--Todo crossCountryBanking props need to update-->
        <b-row class="my-2">
          <b-col cols="12">
            <h6>{{ $t('3rdParty.Checkout.AutoshipCreditCardInfo.Title') }}</h6>
          </b-col>
        </b-row>
        <b-row>
          <b-col cols="12">
            <div>
              <b-form-group
                :label="$t('Autoship.BillOn.Label')"
                :label-for="$t('Autoship.BillOn.Label')"
                class="required"
              >
                <custom-date-picker
                  name="BillOnDate"
                  :data-vv-as="$t('Autoship.BillOn.Label')"
                  v-model="autoshipSubscription.autoshipBillOn"
                  v-validate="'required'"
                  :disable-date-range="autoshipDisableDateRange"
                  :has-error="errors.has('BillOnDate')"
                ></custom-date-picker>
              </b-form-group>
              <span v-show="errors.has('BillOnDate')" class="text-danger text-nowrap">
                {{ errors.first('BillOnDate') }}
              </span>
            </div>
          </b-col>
        </b-row>
        <add-new-card
          ref="autoshipCard"
          :cross-country-banking="true"
          :card-info="autoshipCardInfo"
          v-model="autoshipCardModel"
          wrraper-class="auto-ship-add-new-card"
          :hide-title="true"
        ></add-new-card>
      </b-col>
    </b-row>
  </b-col>
</template>
<script>
import CustomDatePicker from '@/elements/common/components/CustomDatePicker'
import ShippingMethod from '@/app/_global/components/blocks/ShippingMethod'
import AddNewCard from '@/app/_global/components/elements/AddNewCard'
import { APP_SHIPPING_AND_PAYMENT_FORM, APP_AUTOSHIP_FORM } from '@@/store/localStorageKeys'
import appSettings from '@/config/app-settings'
import { DefaultProvider } from '@/providers'
import _ from 'lodash'
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import moment from 'moment'

export default DefaultProvider.extend({
  name: 'AutoshipShippingAndPayment',
  components: { ShippingMethod, AddNewCard, CustomDatePicker },
  $_veeValidate: {
    validator: 'new',
  },
  provide() {
    let self = this
    return {
      get _shipping_countries() {
        return self.getCountries
      },
      _self_pickup_load_stockist_address_list: self.generateStockistAddressLists,
    }
  },
  data() {
    return {
      autoshipShippingInfo: {},
      loadingData: true,
      autoshipShippingModel: {},
      autoshipCardInfo: false,
      autoshipCardModel: {},
      enableCrossCountry: {
        autoshipShipping: false,
      },
      autoshipSubscription: {},
      autoshipDisableDateRange: { to: new Date(Date.now()) },
    }
  },
  watch: {
    autoshipShippingInfo: {
      handler() {
        this.setLocalForm({
          namespace: '3rdPartyCheckoutShippingAndPayment/',
          key: APP_SHIPPING_AND_PAYMENT_FORM,
          formData: { autoshipShippingInfo: this.autoshipShippingInfo },
        })
      },
      deep: true,
    },
    autoshipShippingModel: {
      handler() {
        this.setLocalForm({
          namespace: '3rdPartyCheckoutShippingAndPayment/',
          key: APP_SHIPPING_AND_PAYMENT_FORM,
          formData: { autoshipShippingModel: this.autoshipShippingModel },
        })
      },
      deep: true,
    },
    autoshipCardModel: {
      handler() {
        this.setLocalForm({
          namespace: '3rdPartyCheckoutShippingAndPayment/',
          key: APP_SHIPPING_AND_PAYMENT_FORM,
          formData: { autoshipCardInfo: this.autoshipCardModel },
        })
      },
      deep: true,
    },
    autoshipSubscription: {
      handler() {
        this.setLocalForm({
          namespace: '3rdPartyCheckoutAutoship/',
          key: APP_AUTOSHIP_FORM,
          formData: this.autoshipSubscription,
        })
      },
      deep: true,
    },
  },
  computed: {
    ...mapGetters([
      'getMyAccountMemberDetails',
      'getShippingData',
      'getCountries',
      'getSelectedCountry',
      'getStockistStatesByCountry',
      'getEnrolmentRegion',
      'getAppLocationCountry',
      'getBackendSetting',
    ]),
    ...mapGetters('3rdPartyCheckoutEnrolment', ['getEnrolmentInfo']),
    ...mapGetters('3rdPartyCheckoutShippingAndPayment', ['getShippingAndPaymentInfo']),
    ...mapGetters('3rdPartyCheckoutAutoship', ['getAutoshipInfo']),
    ...mapMasterDataId({
      SALE_DELIVERY_METHOD: {
        shippingMethodWithoutShippingId: 'WITHOUT_SHIPPING',
        shippingMethodDeliveryId: 'DELIVERY',
        shippingMethodSelfCollectionId: 'SELF_PICKUP',
      },
    }),
  },
  async mounted() {
    let self = this
    await this.setDateRangeConfig()
    await this.resolveMasters
    await self
      .initializeShippingData({
        member: self.getEnrolmentInfo.member_data,
        countryId: self.getAppLocationCountry.countryId,
      })
      .then(async () => {
        self.autoshipShippingInfo = _.cloneDeep(self.getShippingData)
        let localStorageAutoshipShippingInfo = _.chain(self.getShippingAndPaymentInfo.autoshipShippingInfo)
          .cloneDeep()
          .merge({
            member_country_id: self.getAppLocationCountry.countryId,
            self_collection_country_id: self.getAppLocationCountry.countryId,
            sale_delivery_method: !self.$helpers.isSet(
              self.getShippingAndPaymentInfo,
              'autoshipShippingModel.sale_delivery_method'
            )
              ? self.shippingMethodDeliveryId
              : self.getShippingAndPaymentInfo.autoshipShippingModel.sale_delivery_method,
            self_collection_point_id: self.getShippingAndPaymentInfo.autoshipShippingModel
              ? self.getShippingAndPaymentInfo.autoshipShippingModel.self_collection_point_id
              : null,
            self_collection_city_id: self.getShippingAndPaymentInfo.autoshipShippingModel
              ? self.getShippingAndPaymentInfo.autoshipShippingModel.self_collection_city_id
              : null,
          })
          .value()
        self.autoshipShippingInfo = _.cloneDeep({
          ...self.autoshipShippingInfo,
          ...localStorageAutoshipShippingInfo,
        })

        // Todo temp hack to match member primary address
        if (this.$helpers.isSet(self.autoshipShippingInfo, 'member_addresses[0]')) {
          self.autoshipShippingInfo.member_addresses[0].fields =
            self.getEnrolmentInfo.member_data.address.address_data[0].fields
        }
        if (this.$helpers.isSet(self.autoshipShippingInfo, 'member_addresses[1]')) {
          self.autoshipShippingInfo.member_addresses[1].fields =
            self.getEnrolmentInfo.member_data.address.address_data[0].fields
        }

        // Todo temp hack remove wrong country from address list
        let autoShippingCountryField = this.$helpers
          .getValue(self.autoshipShippingInfo.member_addresses, '[2]fields', [])
          .find(field => field.key === 'countries')

        if (
          autoShippingCountryField &&
          autoShippingCountryField.value !== self.autoshipShippingInfo.member_country_id
        ) {
          self.autoshipShippingInfo.member_addresses[2].fields = []
        }
      })

    self.autoshipCardInfo = _.cloneDeep(self.getShippingAndPaymentInfo.autoshipCardInfo)
    self.autoshipSubscription = _.cloneDeep(self.getAutoshipInfo)

    if (appSettings.eshop.order_item.cv_transfer_checkbox === true) {
      self.orderData = {
        cvTransferList: self.getCvTransferList,
      }
    }
    this.errors.clear()
  },
  methods: {
    ...mapActions('3rdPartyCheckoutGlobal', ['setLocalForm']),
    ...mapActions('eshop', ['loadCart', 'saveOrderShipping', 'updateCvTransferList']),
    ...mapActions('enrolment', ['getIsEnrolTypeIsMember']),
    ...mapActions([
      'loadCountries',
      'loadMyAccountInfo',
      'initializeShippingData',
      'loadStockistLocationAddressList',
      'clearLoadedData',
      'loadBackendSetting',
    ]),
    generateStockistAddressLists(payload) {
      return this.loadStockistLocationAddressList({
        country_id: this.getEnrolmentRegion.id,
        state_id: payload.state_id,
        location_id: payload.location_id,
      })
    },
    async setDateRangeConfig() {
      let disableMeta = { to: new Date(Date.now()) }
      await this.loadBackendSetting(['autoship_next_billing_date_range', 'autoship_unavailable_billing_date'])

      let autoshipDateRangeConfig = this.getBackendSetting('autoship_next_billing_date_range') || {}
      let autoshipDisabledDate = this.getBackendSetting('autoship_unavailable_billing_date') || {}

      if (typeof autoshipDateRangeConfig.data == 'number')
        disableMeta['from'] = moment()
          .add(autoshipDateRangeConfig.data, 'days')
          .toDate()

      if (Array.isArray(autoshipDisabledDate.data)) {
        disableMeta['daysOfMonth'] = autoshipDisabledDate.data
      }

      this.autoshipDisableDateRange = disableMeta
    },
    validate() {
      let validators = [
        this.$validator.validateAll(),
        this.$refs.billingAddressInfo.validate(),
        this.$refs.autoshipCard.$validator.validate('addCardForm.*'),
      ]
      return Promise.all([...validators]).then(async function(validation) {
        return validation.indexOf(false) === -1 && validation.indexOf(undefined) === -1
      })
    },
  },
})
</script>
