<template>
  <b-card no-body class="dashboard-panel-element rounded-0 pt-0" v-can:view="'auto-ship'">
    <b-row class="border-bottom mb-3 py-2 mx-0">
      <b-col cols="6" md="8" class="pl-0">
        <b-button
          variant="link"
          class="d-flex align-items-center text-decoration-none"
          :to="{ name: 'AutoshipHomePaginated', params: { page: 1 } }"
          data-qa="autoship-autoship-detail-back-btn"
        >
          <icon name="back-arrow" class="mr-2" />
          <span class="font-size-5 d-none d-md-inline-block">{{ $t('Autoship.BackToMenu.Label') }}</span>
          <span class="d-inline-block font-size-5 d-md-none">{{ $t('Common.Back') }}</span>
        </b-button>
      </b-col>
      <b-col v-if="!isLoading('loadingSubscriptionDetail')" cols="6" md="4" class="pr-0">
        <div v-if="isActive" class="d-flex flex-row-reverse">
          <b-button
            variant="primary"
            class="ml-3 px-4"
            @click="editAutoship"
            data-qa="autoship-autoship-detail-edit-btn"
          >
            {{ $t('Autoship.Edit.Label') }}
          </b-button>
          <b-button variant="outline-light" @click="terminateAutoship" data-qa="autoship-autoship-detail-terminate-btn">
            {{ $t('Autoship.Terminate.Label') }}
          </b-button>
        </div>
        <div v-else class="d-flex flex-row-reverse pt-2">
          <span class="text-danger font-weight-bold pr-2">{{ $t('Autoship.TerminatedStatus.Label') }}</span>
        </div>
      </b-col>
    </b-row>
    <div v-if="isLoading('loadingSubscriptionDetail')">
      <div class="text-center text-primary my-5">
        <b-spinner class="mx-2" />
        <strong class="h4">{{ $t('Common.Loading') }}</strong>
      </div>
    </div>
    <div v-else>
      <div class="bg-note px-3">
        <b-row>
          <b-col cols="12" md="4">
            <b-row class="py-2">
              <b-col cols="4" md="12" class="text-wrap col-xxl-4">
                {{ $t('Autoship.AutoshipNo') }}
              </b-col>
              <b-col class="font-weight-bolder">{{ getAutoshipId }}</b-col>
            </b-row>
            <b-row class="py-2">
              <b-col cols="4" md="12" class="text-wrap col-xxl-4">
                {{ $t('Autoship.NextBillDate') }}
              </b-col>
              <b-col class="font-weight-bolder">{{ getNextBillDate }}</b-col>
            </b-row>
            <b-row class="py-2">
              <b-col cols="4" md="12" class="text-wrap col-xxl-4">
                {{ $t('Autoship.BillingCycle') }}
              </b-col>
              <b-col class="font-weight-bolder">{{ getShippingCycle }}</b-col>
            </b-row>
            <b-row class="py-2">
              <b-col cols="4" md="12" class="text-wrap col-xxl-4">
                {{ $t('Common.Payment.CreditCard') }}
              </b-col>
              <b-col class="font-weight-bolder">{{ getCreditCard }}</b-col>
            </b-row>
          </b-col>
          <b-col cols="12" md="4">
            <b-row class="py-2">
              <b-col cols="4" md="12" xl="4">
                <span v-if="isSelfPickup">{{ $t('Common.SelfCollectionPoint') }}</span>
                <span v-else>{{ $t('Common.DeliveryDetails') }}</span>
              </b-col>
              <b-col class="">
                <span class="font-weight-bolder">{{ getRecipientName('Shipping') }}</span>
                <br />
                <span>{{ getShippingAddress }}</span>
                <br />
                <span>{{ getRecipientNumber('Shipping') }}</span>
              </b-col>
            </b-row>
          </b-col>
          <b-col cols="12" md="4">
            <b-row class="py-2">
              <b-col cols="4" md="12" xl="4">
                {{ $t('Autoship.BillingDetail.Label') }}
              </b-col>
              <b-col>
                <span class="font-weight-bolder">{{ getRecipientName('Billing') }}</span>
                <br />
                <span>{{ getBillingAddress }}</span>
                <br />
                <span>{{ getRecipientNumber('Billing') }}</span>
              </b-col>
            </b-row>
          </b-col>
        </b-row>
      </div>
      <div class="pt-4 table-responsive">
        <table class="table border-bottom mb-2">
          <thead>
            <tr class="bg-transparent">
              <th scope="col" class="align-middle">
                {{ $t('Common.Table.No') }}
              </th>
              <th scope="col" class="align-middle">
                {{ $t('Common.ProductCode') }}
              </th>
              <th scope="col" class="align-middle">
                {{ $t('Common.Product.ProductName') }}
              </th>
              <th scope="col" class="align-middle text-center">
                {{ $t('Common.Quantity') }}
              </th>
              <th scope="col" class="align-middle text-right">
                {{ $t('Common.Terminology.TotalBV') }}
              </th>
              <th scope="col" class="align-middle text-right">
                {{ $t('Common.TotalAmount.WithCurrency', { currency: getCurrency }) }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in getSubscriptionItemList" :key="`subscription-list${index}`">
              <td class="align-middle">
                {{ index + 1 }}
              </td>
              <td class="align-middle">
                {{ item.sku }}
              </td>
              <td class="align-middle">
                {{ item.name }}
              </td>
              <td class="text-center align-middle">
                {{ item.quantity }}
              </td>
              <td class="text-right align-middle">
                {{ item.cv * item.quantity }}
              </td>
              <td class="text-right align-middle">
                {{ $helpers.getCurrencyValue(item.price * item.quantity) }}
              </td>
            </tr>
          </tbody>
          <tfoot>
            <tr class="font-weight-bold border-bottom-double">
              <td colspan="4" class="text-primary align-middle text-right font-weight-bold-extra text-uppercase">
                {{ $t('Common.Sales.GrandTotal') }}
              </td>
              <td class="text-primary align-middle text-right font-weight-bold-extra"></td>
              <td class="text-primary align-middle text-right font-weight-bold-extra">
                {{ $helpers.getCurrencyValue(getGrandTotal) }} *
              </td>
            </tr>
          </tfoot>
        </table>
        <span class="text-black-50">{{ $t('Common.Sales.PreSalesDeclaimer') }}</span>
      </div>
    </div>
  </b-card>
</template>

<script>
import { AddressMixin, PhoneMixin } from '@/app/_global/mixins'
import { mapGetters, mapActions } from 'vuex'
import { getValue } from '@/helpers/variable-handling'
import _ from 'lodash'

export default {
  name: 'AutoshipDetails',
  mixins: [AddressMixin, PhoneMixin],
  props: ['orderId'],
  data() {
    return {
      isActive: true,
      stockistDetails: {},
      isSelfPickup: false,
    }
  },
  async created() {
    await this.loadAutoshipSubscriptionDetail(this.orderId)
    this.addresses = [getValue(this.getAutoshipSubscriptionDetail, 'billing_address.recipient_addresses[0]', [])]
    // Push Stockist address if user choose delivery to Stockist place
    if (getValue(this.getAutoshipSubscriptionDetail, 'shipping_address.pickup_address')) {
      this.isSelfPickup = true
      // Set stockist details
      this.stockistDetails = _.cloneDeep(
        getValue(this.getAutoshipSubscriptionDetail, 'shipping_address.pickup_address', {})
      )
      this.addresses.push(getValue(this.stockistDetails, 'recipient_addresses[0]', []))
    } else {
      this.addresses.push(getValue(this.getAutoshipSubscriptionDetail, 'shipping_address.recipient_addresses[0]', []))
    }
    this.isActive = this.getAutoshipSubscriptionDetail.deleted_at === null
    await this.initMixin(true)
  },
  computed: {
    ...mapGetters(['getAutoshipSubscriptionDetail', 'isLoading']),
    getAutoshipId() {
      return this.getAutoshipSubscriptionDetail.code || ''
    },
    getNextBillDate() {
      return this.getAutoshipSubscriptionDetail.next_bill_date || ''
    },
    getShippingCycle() {
      let frequency = this.getAutoshipSubscriptionDetail.recurring_frequency
      return (frequency === 1 && 'Monthly') || ''
    },
    getShippingAddress: function() {
      let address = this.isSelfPickup
        ? getValue(this.stockistDetails, 'recipient_addresses[0]')
        : getValue(this.getAutoshipSubscriptionDetail, 'shipping_address.recipient_addresses[0]')
      return address ? this.getAddressString(address) : '-'
    },
    getBillingAddress() {
      let address = getValue(this.getAutoshipSubscriptionDetail, 'billing_address.recipient_addresses[0]')
      return address ? this.getAddressString(address) : '-'
    },
    getCreditCard() {
      let card = this.getAutoshipSubscriptionDetail.card
      return `[${card.card_type}]  ${card.card_number}  Exp: ${card.card_expiry}` || ''
    },
    getSubscriptionItemList() {
      let itemList = []
      let subscriptionItems = this.getAutoshipSubscriptionDetail.subscription_items
      for (let i in subscriptionItems) {
        let item = { sku: '-', name: '-', cv: 0, price: 0 }
        if (subscriptionItems[i].product !== undefined) {
          item['sku'] = subscriptionItems[i].product.sku || '-'
          item['name'] = subscriptionItems[i].product.name || '-'
          item['cv'] = subscriptionItems[i].product.product_price.base_cv || 0
          item['price'] = subscriptionItems[i].product.product_price.gmp_price_tax || 0
        } else if (subscriptionItems[i].kitting !== undefined) {
          item['sku'] = subscriptionItems[i].kitting.code || '-'
          item['name'] = subscriptionItems[i].kitting.name || '-'
          item['cv'] = subscriptionItems[i].kitting.kitting_price.base_cv || 0
          item['price'] = subscriptionItems[i].kitting.kitting_price.gmp_price_tax || 0
        }
        item['quantity'] = subscriptionItems[i].quantity || ''
        // push item to the list
        itemList.push(item)
      }
      return itemList
    },
    getCurrency() {
      return this.getAutoshipSubscriptionDetail.currency_code
    },
    getGrandTotal() {
      return this.getAutoshipSubscriptionDetail.amount
    },
  },
  methods: {
    ...mapActions(['loadAutoshipSubscriptionDetail', 'unsubscribeAutoship', 'loadStockistLocationAddressList']),
    editAutoship() {
      this.$router.push({ name: 'AutoshipEdit', params: { autoshipId: this.orderId } })
    },
    terminateAutoship() {
      this.$swal({
        title: this.$t('Autoship.Popup.TerminateAutoship.Label'),
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: this.$t('Autoship.Popup.TerminateAutoship.Confirm'),
        cancelButtonText: this.$t('Autoship.Popup.TerminateAutoship.Cancel'),
        reverseButtons: true,
      }).then(result => {
        if (result.value) {
          this.unsubscribeAutoship(this.orderId).then(result => {
            if (result) {
              this.$swal({
                title: this.$t('Autoship.Popup.Termination.Success.Title'),
                text: this.$t('Autoship.Popup.Termination.Success.Msg', { id: this.getAutoshipId }),
                type: 'success',
                timer: '2200',
              })
              this.isActive = false
            } else {
              this.$swal({
                title: this.$t('Autoship.Popup.Termination.Fail.Title'),
                text: this.$t('Autoship.Popup.Termination.Fail.Msg', { id: this.getAutoshipId }),
                type: 'error',
              })
            }
          })
        }
      })
    },
    getRecipientName(type) {
      let name =
        this.isSelfPickup && type.toLowerCase() === 'shipping'
          ? this.stockistDetails.recipient_name
          : getValue(this.getAutoshipSubscriptionDetail, type.toLowerCase() + '_address.recipient_name')

      return name || '-'
    },
    getRecipientNumber(type) {
      let mobile = {}

      if (this.isSelfPickup && type.toLowerCase() === 'shipping') {
        mobile['country_code'] = this.stockistDetails.recipient_mobile_country_code_id
        mobile['number'] = this.stockistDetails.recipient_mobile_phone_number
      } else {
        mobile['country_code'] = getValue(
          this.getAutoshipSubscriptionDetail,
          type.toLowerCase() + '_address.recipient_mobile_country_code_id'
        )
        mobile['number'] = getValue(
          this.getAutoshipSubscriptionDetail,
          type.toLowerCase() + '_address.recipient_mobile_phone_number'
        )
      }

      if (mobile.country_code && mobile.number) {
        return this.phoneNumber(mobile.country_code, mobile.number, type.toLowerCase() === 'billing', false)
      } else {
        return '-'
      }
    },
  },
}
</script>
