<template>
  <b-container class="nh-75 p-0" v-bar="vueSidebarConfig">
    <div>
      <div class="row bg-light-extra border-y small px-3 py-2 w-100">
        <div class="col-12 col-md-4">
          <div class="row py-1">
            <div class="col-4 col-lg-5 col-md-7">
              {{ $t('OrderHistory.TableHeader.OrderNo') }}
            </div>
            <div class="col font-weight-bold-extra">
              {{ orderData.document_number }}
            </div>
          </div>
          <div class="row py-1">
            <div class="col-4 col-lg-5 col-md-7">
              {{ $t('OrderHistory.TableHeader.OrderDate') }}
            </div>
            <div class="col font-weight-bold-extra">
              {{ new Date(orderData.transaction_date).toLocaleDateString() }}
            </div>
          </div>
          <div class="row py-1">
            <div class="col-4 col-lg-5 col-md-7">
              {{ $t('Common.IboId') }}
            </div>
            <div class="col font-weight-bold-extra">
              {{ $helpers.getValue(orderData, 'downline_member.user.old_member_id', '') }}
            </div>
          </div>
          <div class="row py-1">
            <div class="col-4 col-lg-5 col-md-7">
              {{ $t('Common.IboName') }}
            </div>
            <div class="col font-weight-bold-extra">
              {{ $helpers.getValue(orderData, 'downline_member.name', '-') }}
            </div>
          </div>
        </div>
        <div class="col-12 col-md-4">
          <div v-if="showPayCycle" class="row py-1">
            <div class="col-4 col-lg-5 col-md-10">
              {{ $t('Common.Terminology.PayCycle') }}
            </div>
            <div :class="['col', 'font-weight-bold-extra']">
              {{ $helpers.getValue(orderData, 'cw.cw_name', '-') }}
            </div>
          </div>
          <div class="row py-1">
            <div class="col-4 col-lg-5 col-md-10">
              {{ $t('OrderHistory.TableHeader.OrderStatus') }}
            </div>
            <div :class="[getOrderStatusClassByName(orderData.order_status), 'col', 'font-weight-bold-extra']">
              {{ $helpers.getValue(orderData, 'translated_order_status.content', orderData.order_status) }}
            </div>
          </div>
          <div class="row py-1">
            <div class="col-4 col-lg-5 col-md-10">
              {{ $t('Common.Terminology.TotalBV') }}
            </div>
            <div class="col font-weight-bold-extra">
              {{ $helpers.getValue(orderData, 'cvs.total_bv', 0) }}
            </div>
          </div>
          <div class="row py-1">
            <div class="col-4 col-lg-5 col-md-10 ">
              {{ $t('Common.TotalAmount') }}
            </div>
            <div class="col font-weight-bold-extra">
              {{ getCountryCurrencyCode }}
              {{ getTotalAmount }}
            </div>
          </div>
          <div class="row py-1" v-if="isSelfPickup">
            <div class="col-4 col-lg-5 col-md-10 text-capitalize">
              {{ $t('OrderHistory.Detail.SelfCollection') }}
            </div>
            <div class="col font-weight-bold-extra">
              {{ $helpers.getValue(orderData, 'self_pick_up_number', '-') }}
            </div>
          </div>
          <div v-else>
            <div class="row py-1">
              <div class="col-4 col-lg-5 col-md-10">
                {{ $t('OrderHistory.Detail.ShippingCompany') }}
              </div>
              <div class="col font-weight-bold-extra text-uppercase">
                {{ getConsignmentShippingCompany || '-' }}
              </div>
            </div>
            <div class="row py-1">
              <div class="col-4 col-lg-5 col-md-10">
                {{ $t('OrderHistory.Detail.ShippingConsignmentNo') }}
              </div>
              <div class="col font-weight-bold-extra">
                {{ getConsignmentNumber || '-' }}
              </div>
            </div>
          </div>
        </div>
        <div class="col-12 col-md-4">
          <div class="row py-1">
            <div class="col-4 col-lg-5 col-md-10 text-capitalize">
              <span v-if="isSelfPickup">{{ $t('Common.SelfCollectionPoint') }}</span>
              <span v-else>{{ $t('Common.DeliveryDetails') }}</span>
            </div>
            <div class="col font-weight-bold" v-if="getShippingInfo">
              <div v-if="getShippingInfo.name" class="font-weight-bold-extra">[ {{ getShippingInfo.name }} ]</div>
              <div v-if="getShippingInfo.address">{{ getShippingInfo.address }}</div>
              <div v-if="getShippingInfo.contact">{{ getShippingInfo.contact }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="mr-3">
        <b-table :fields="getOrderFields" :items="populateProductItems.products" :responsive="true" class="small">
          <template v-slot:cell(index)="row">{{ row.index + 1 }}</template>
          <template v-slot:cell(delivery_status)="row">
            <span :class="getDeliveryStatusClass(row.item.id)">
              {{ getDeliveryStatus(row.item.id) }}
            </span>
          </template>

          <template v-slot:custom-foot>
            <b-tr v-if="getEsacVouchers.length > 0">
              <td colspan="2" />
              <td>
                <div>{{ $t('OrderHistory.Detail.EsacVoucher') }}</div>
                <div v-for="(voucher, idx) in getEsacVouchers" :key="idx">
                  <i>{{ `- ${voucher.voucher_number}` }}</i>
                </div>
              </td>
              <td :colspan="$appSettings.evo.enable ? 5 : 4" class="text-right">({{ getTotalEsacVoucher }})</td>
              <td colspan="2" />
            </b-tr>

            <b-tr v-if="getDeliveryFeeAmount !== '0.00' || true">
              <td colspan="2" />
              <td>{{ $t('Common.Sales.DeliveryFee') }}</td>
              <td :colspan="$appSettings.evo.enable ? 5 : 4" class="text-right">{{ getDeliveryFeeAmount }}</td>
              <td />
            </b-tr>

            <b-tr class="border-bottom-double border-light font-weight-bold-extra text-primary text-right">
              <b-td colspan="4">{{ $t('Common.Sales.GrandTotal') }}</b-td>
              <b-td> {{ (orderData.cvs && orderData.cvs.total_bv) || $appSettings.evo.enable ? '0.00' : '0' }}</b-td>
              <b-td v-if="!$appSettings.evo.enable">
                {{ (orderData.cvs && orderData.cvs.total_amp_cv) || '0' }}
              </b-td>
              <b-td v-if="$appSettings.evo.enable">
                {{ (orderData.cvs && orderData.cvs.total_sv) || 0 }}
              </b-td>
              <b-td v-if="$appSettings.evo.enable">
                {{ (orderData.cvs && orderData.cvs.total_cbp_point) || '0.0000' }}
              </b-td>
              <b-td> {{ getTotalAmount }}</b-td>
              <td />
            </b-tr>
          </template>
        </b-table>
      </div>

      <div class="row px-4 pt-3 pb-2 bg-light-extra border-y w-100 justify-content-between">
        <h4 class="font-weight-bold">
          {{ $t('OrderHistory.Detail.PaymentDetails.Title') }}
        </h4>
        <b-button v-if="orderData.resume_payment_url" variant="primary" @click="makeResumePayment">
          {{ $t('OrderHistory.Detail.Button.ResumePayment') }}
        </b-button>
      </div>
      <div class="overflow-x-auto mr-3">
        <table class="table border-bottom">
          <thead>
            <tr class="bg-transparent small font-weight-bold">
              <th scope="col" class="align-middle">
                {{ $t('Common.Sales.PaymentMethod') }}
              </th>
              <th scope="col" class="align-middle text-right">
                {{ $t('Common.TotalAmount.WithCurrency', { currency: getCountryCurrencyCode }) }}
              </th>
              <th scope="col" class="align-middle">
                {{ $t('OrderHistory.Detail.TableHeader.Bank') }}
              </th>
              <th scope="col" class="align-middle">
                {{ $t('OrderHistory.Detail.TableHeader.Tenure') }}
              </th>
              <th scope="col" class="align-middle">
                {{ $t('OrderHistory.Detail.TableHeader.ApprovalCode') }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, itemIndex) in getSalesPaymentData" class="small" :key="itemIndex">
              <td class="align-middle">
                {{ item.payment_mode_provider.name }}
              </td>
              <td class="align-middle text-right">
                {{ $helpers.getCurrencyValue(item.amount) }}
              </td>
              <td v-if="item.is_qr === 1" colspan="3" class="align-middle">
                <b-btn variant="primary" size="sm" @click="showQrCode(item.id)">
                  <b-spinner v-show="isLoading('paymentQRCodeLoading')" small class="mr-1" />
                  <span> {{ $t('OrderHistory.Detail.ShowQrCode') }}</span>
                </b-btn>
              </td>
              <td class="align-middle">
                {{ item.bank }}
              </td>
              <td class="align-middle">
                {{ item.tenure }}
              </td>
              <td class="align-middle">
                {{ item.approvecode_agreementno }}
              </td>
            </tr>
          </tbody>
          <tfoot>
            <tr class="small font-weight-bol border-light border-bottom-double">
              <td class="text-primary align-middle font-weight-bold-extra">
                {{ $t('Common.TotalAmount') }}
              </td>
              <td class="text-primary align-middle text-right font-weight-bold-extra">
                {{ getTotalPayment }}
              </td>
              <td colspan="5" />
            </tr>
          </tfoot>
        </table>
      </div>
      <div class="row px-4 pt-3 pb-2 bg-light-extra border-y justify-content-between w-100">
        <h4 class="font-weight-bold">
          {{ $t('OrderHistory.Detail.eVoucher.Title') }}
        </h4>
        <b-btn
          v-if="orderData.invoice !== null && getSaleEvouchers.length > 0"
          :disabled="isLoading('evoucherLoading')"
          variant="primary"
          class="text-right"
          :to="{ name: 'OrderHistoryEvoucher', params: { saleId: getCurrentSaleId } }"
        >
          {{ $t('OrderHistory.Detail.eVoucher.OpenIneVoucher') }}
        </b-btn>
        <b-btn v-else variant="light" disabled class="text-white text-right">
          {{ $t('OrderHistory.Detail.eVoucher.OpenIneVoucher') }}
        </b-btn>
      </div>
      <div class="overflow-x-auto mr-3">
        <table class="table border-bottom">
          <thead>
            <tr class="bg-transparent small font-weight-bold">
              <th scope="col" class="align-middle text-nowrap">
                {{ $t('OrderHistory.Detail.TableHeader.eVoucherNo') }}
              </th>
              <th scope="col" class="align-middle">
                {{ $t('OrderHistory.Detail.TableHeader.ProductDescription') }}
              </th>
              <th scope="col">
                {{ $t('OrderHistory.Detail.TableHeader.ActivationStatus') }}
              </th>
              <th scope="col">
                {{ $t('OrderHistory.Detail.TableHeader.ActivationDate') }}
              </th>
              <th scope="col">
                {{ $t('OrderHistory.Detail.TableHeader.RedemptionStatus') }}
              </th>
              <th scope="col">
                {{ $t('OrderHistory.Detail.TableHeader.RedemptionDate') }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in getSaleEvouchers" class="small" :key="index">
              <td class="align-middle">
                {{ item.evoucher_number }}
              </td>
              <td class="align-middle">
                {{ item.product_name }}
              </td>
              <td
                class="font-weight-bold align-middle"
                :class="item.activation.is_activated === 1 ? 'text-info' : 'text-primary'"
              >
                {{
                  item.activation.is_activated === 0
                    ? $t('OrderHistory.Detail.eVoucher.Status.Inactive')
                    : $t('OrderHistory.Detail.eVoucher.Status.Activated')
                }}
              </td>
              <td class="align-middle">
                {{ getDate(item.activation.activation_date) }}
              </td>
              <td
                class="font-weight-bold align-middle"
                :class="item.redemption.is_redeemed === 1 ? 'text-info' : 'text-primary'"
              >
                {{
                  item.redemption.is_redeemed === 0
                    ? $t('OrderHistory.Detail.eVoucher.Status.Unredeem')
                    : $t('OrderHistory.Detail.eVoucher.Status.Redeemed')
                }}
              </td>
              <td class="align-middle">
                {{ getDate(item.redemption.redemption_date) }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <b-modal
      size="lg"
      centered
      hide-footer
      no-close-on-esc
      no-enforce-focus
      ref="popUpQrCode"
      no-close-on-backdrop
      :body-class="['text-center']"
      :title="$t('OrderHistory.Detail.PaymentQrCode.Title')"
    >
      <b-img :src="qrCodeImage" fluid />
      <div>
        <b-btn variant="primary" @click="copyLink(qrCodeLink, defaultCopiedCallBack)">
          {{ $t('ShareQR.ShareVia.CopyLink') }}
        </b-btn>
      </div>
    </b-modal>
  </b-container>
</template>
<script>
import moment from 'moment'
import { mapGetters, mapActions } from 'vuex'
import { getCurrencyValue } from '@/helpers/currency-formatter'
import { CurrencyMixin, AddressMixin, PhoneMixin, mapMasterDataId, qrLinkCopyMixin } from '@/app/_global/mixins'

export default {
  name: 'Orderhistorydetail',
  mixins: [CurrencyMixin, AddressMixin, PhoneMixin, qrLinkCopyMixin],
  props: ['orderData', 'memberData', 'preferredEmailId', 'showPayCycle'],
  data() {
    return {
      totalProducts: 0,
      vueSidebarConfig: {
        preventParentScroll: true,
        resizeRefresh: true,
      },
      qrCodeImage: '',
      qrCodeLink: '',
    }
  },
  mounted() {
    if (typeof this.orderData.selected !== 'undefined') {
      this.selectedCountry = this.orderData.country_id
      this.totalProducts = this.$helpers.getCurrencyValue(this.populateProductItems.total)
    }
  },
  methods: {
    ...mapActions(['getPaymentQrCodeData']),
    ...mapActions('eshop', ['setCollPointState', 'setCollPointCity']),
    getDate(date) {
      return (date && moment(date).format('DD/MM/YYYY')) || ''
    },
    getDeliveryStatusClass(pid) {
      if (
        this.orderData.delivery_method !== null &&
        this.orderData.delivery_method === this.$const.masterData.SALE_DELIVERY_METHOD_SELF_PICKUP
      ) {
        return ''
      }
      if (typeof this.orderData.delivery_order !== 'undefined') {
        let status = this.orderData.delivery_order.find(product => product.sales_product_id === pid)
        if (status) {
          if (status.status_code.title !== 'Received') {
            return 'text-warning'
          }
        }
      }
      return 'text-info'
    },
    getDeliveryStatus(pid) {
      if (
        this.orderData.delivery_method !== null &&
        this.orderData.delivery_method === this.$const.masterData.SALE_DELIVERY_METHOD_SELF_PICKUP
      ) {
        return ''
      }
      if (typeof this.orderData.delivery_order !== 'undefined') {
        let status = this.orderData.delivery_order.find(product => product.sales_product_id === pid)
        return status ? status.status_code.title : ''
      }
    },
    getOrderStatusClassByName(status) {
      return (
        (status === this.$const.masterData.SALE_ORDER_STATUS_COMPLETED && 'text-info') ||
        (status === this.$const.masterData.SALE_ORDER_STATUS_PREORDER && 'text-danger') ||
        (status === this.$const.masterData.SALE_ORDER_STATUS_CANCELLED && 'text-light') ||
        ''
      )
    },
    showQrCode(paymentId) {
      this.getPaymentQrCodeData(paymentId).then(() => {
        this.qrCodeImage = this.getPaymentQrCode.image
        this.qrCodeLink = this.getPaymentQrCode.link
        this.$refs.popUpQrCode.show()
      })
    },
    makeResumePayment() {
      window.open(this.orderData.resume_payment_url, this.$helpers.isSafari() ? '_self' : '_blank')
    },
  },
  computed: {
    ...mapGetters([
      'getCountryById',
      'getSalesPaymentData',
      'populateProductItems',
      'getEsacVouchers',
      'getSaleEvouchers',
      'isLoading',
      'getPaymentQrCode',
      'getCurrentSaleId',
    ]),
    ...mapGetters('eshop', ['getCollectionPoint']),
    ...mapMasterDataId({
      SALE_DELIVERY_METHOD: {
        deliveryId: 'SALE_DELIVERY_METHOD_DELIVERY',
        selfPickupId: 'SALE_DELIVERY_METHOD_SELF_PICKUP',
      },
      PROMOTION_FREE_ITEM_PROMO_TYPES: {
        focId: 'PROMO_TYPE_FOC',
      },
    }),
    getTotalAmount() {
      return getCurrencyValue(this.$helpers.getValue(this.orderData, 'order_fees.total_gmp', 0))
    },
    getTotalPayment() {
      let total = this.getSalesPaymentData.reduce((acc, current) => acc + parseFloat(current.amount), 0)
      return this.$helpers.getCurrencyValue(total)
    },
    getShippingInfo() {
      let result = { name: '', contact: '', address: '' }
      if (this.deliveryId !== null && this.selfPickupId !== null) {
        if (typeof this.orderData.selected !== 'undefined' && this.orderData.selected !== null) {
          if (this.orderData.delivery_method_id === this.deliveryId) {
            if (this.orderData.selected.shipping !== null) {
              result['name'] = this.orderData.selected.shipping.recipient_name
              result['contact'] = this.phoneNumber(
                this.orderData.country_id,
                this.orderData.selected.shipping.recipient_mobile_phone_number
              )
              if (
                typeof this.orderData.selected.shipping.recipient_addresses !== 'undefined' &&
                this.orderData.selected.shipping.recipient_addresses !== ''
              ) {
                //TODO: REMOVE SIDE EFFECTSTs
                // eslint-disable-next-line vue/no-side-effects-in-computed-properties
                this.addresses = Array.isArray(this.orderData.selected.shipping.recipient_addresses)
                  ? this.orderData.selected.shipping.recipient_addresses
                  : [this.orderData.selected.shipping.recipient_addresses]
                this.initMixin(true, false)
                result['address'] = this.getAddressString(this.addresses[0])
              }
            }
          } else if (this.orderData.delivery_method_id === this.selfPickupId) {
            if (
              typeof this.orderData.self_collection_point !== 'undefined' &&
              this.orderData.self_collection_point !== null
            ) {
              result['name'] = this.orderData.self_collection_point.location_detail.name
              if (
                this.orderData.self_collection_point.telephone_code !== null &&
                this.orderData.self_collection_point.telephone_num !== null
              ) {
                result['contact'] = this.phoneNumber(
                  this.orderData.country_id,
                  this.orderData.self_collection_point.telephone_num
                )
              }
              //TODO: REMOVE SIDE EFFECTSTs
              // eslint-disable-next-line vue/no-side-effects-in-computed-properties
              this.addresses = this.orderData.self_collection_point.address_data
              this.initMixin(true, false)
              result['address'] = this.getAddressString(this.addresses[0])
            }
          }
        }
      }
      if (result.name === '' && result.contact === '' && result.address === '') {
        result['name'] = this.$t('OrderHistory.Detail.OTC')
      }
      return result
    },
    getTotalEsacVoucher() {
      let total = this.getEsacVouchers.reduce((acc, current) => acc + parseFloat(current.voucher_value), 0)
      return getCurrencyValue(total)
    },
    getDeliveryFeeAmount() {
      let total = 0
      let { delivery_fee: deliveryFee, delivery_fee_tax: tax } = this.orderData.order_fees || {}
      if (deliveryFee !== undefined) {
        total = parseFloat(deliveryFee) + parseFloat(tax)
      }
      return getCurrencyValue(total)
    },
    getCountryCurrencyCode() {
      return this.$helpers.getValue(this.getCountryById(this.orderData.country_id), 'currency.code', '')
    },
    isSelfPickup() {
      let deliveryMethodId = this.$helpers.getValue(this.orderData, 'selected.shipping.sale_delivery_method')
      return deliveryMethodId && this.selfPickupId === deliveryMethodId
    },
    getConsignmentShippingCompany() {
      return [...new Set((this.orderData.delivery_order || []).map(order => order.service.title))].join(' ')
    },
    getConsignmentNumber() {
      return [...new Set((this.orderData.delivery_order || []).map(order => order.consignment_order_number))].join(' ')
    },
    getOrderFields() {
      return [
        { key: 'index', label: this.$t('Common.Table.No') },
        { key: 'sku', label: this.$t('Common.ProductCode') },
        { key: 'name', label: this.$t('OrderHistory.Detail.TableHeader.ProductDescription') },
        { key: 'quantity', label: this.$t('Common.Quantity'), class: 'text-center' },
        { key: 'cv', label: this.$t('Common.Terminology.TotalBV'), class: 'text-right' },
        {
          key: 'amp',
          label: this.$t('OrderHistory.Detail.TableHeader.TotalAMPCV'),
          class: 'text-right',
          show: !this.$appSettings.evo.enable,
        },
        {
          key: 'sv',
          label: this.$t('Common.Terminology.TotalSv'),
          class: 'text-right',
          show: this.$appSettings.evo.enable,
        },
        {
          key: 'cbp',
          label: this.$t('Common.Terminology.TotalCbp'),
          class: 'text-right',
          show: this.$appSettings.evo.enable,
        },
        {
          key: 'price',
          label: this.$t('Common.TotalAmount.WithCurrency', { currency: this.getCountryCurrencyCode }),
          class: 'text-right',
          formatter: price => getCurrencyValue(price),
        },
        {
          key: 'delivery_status',
          label: this.$t('OrderHistory.Detail.TableHeader.DeliveryStage'),
          class: 'text-center',
        },
      ].filter(field => field.show !== false)
    },
  },
}
</script>
