<template>
  <div>
    <b-row class="mb-4">
      <b-col>
        <div>
          <span>
            {{ $t('SvTransfer.TransferTo') }}: [{{
              $helpers.getValue(getSvTransferDetails, 'transfereeIbo.memberId', '')
            }}]
          </span>
        </div>
        <div class="m-0 font-size-5 font-weight-bold text-capitalize">
          {{ $helpers.getValue(getSvTransferDetails, 'transfereeIbo.name', '') }}
        </div>
      </b-col>
    </b-row>

    <b-row>
      <b-col>
        <b-table
          hover
          outlined
          show-empty
          caption-top
          stacked="md"
          responsive=""
          :fields="getTableField"
          :items="getSelectedSvTransferProductList"
        >
          <template v-slot:table-caption>
            {{ $t('SvTransfer.Creation.SelectedTransferProducts.TableDescription') }}
          </template>

          <template v-slot:empty>
            <div class="text-center text-primary my-2">
              <strong class="h4">{{ $t('Common.RecordNotFound') }}</strong>
            </div>
          </template>

          <template v-slot:cell(index)="row">
            {{ row.index + 1 }}
          </template>

          <template v-slot:custom-foot v-if="getSelectedSvTransferProductList.length">
            <b-tr class="border-top-double border-light-extra">
              <b-td colspan="4" class="font-weight-bold text-primary text-right align-middle">
                {{ $t('Common.Sales.Total') }}
              </b-td>
              <b-td class="font-weight-bold text-primary text-right no-wrap">
                <span>{{ getGrandTotal.bv }}</span>
              </b-td>
              <b-td class="font-weight-bold text-primary text-right no-wrap">
                <span>{{ getGrandTotal.sv }}</span>
              </b-td>
              <b-td class="font-weight-bold text-primary text-right no-wrap">
                <span>{{ getGrandTotal.cbp }}</span>
              </b-td>
            </b-tr>
          </template>
        </b-table>
      </b-col>
    </b-row>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'SvTransferConfirmationStep',
  computed: {
    ...mapGetters(['getSvTransferDetails']),
    getTableField() {
      return [
        { key: 'index', label: this.$t('Common.Table.No') },
        { key: 'sku', label: this.$t('Common.ProductCode') },
        { key: 'name', label: this.$t('Common.Product.ProductName') },
        { key: 'quantity', label: this.$t('Common.Quantity'), class: 'text-md-right' },
        { key: 'bv', label: this.$t('Common.Terminology.Bv'), class: 'text-md-right' },
        { key: 'sv', label: this.$t('Common.Terminology.Sv'), class: 'text-md-right' },
        {
          key: 'cbp_point',
          label: this.$t('Common.Terminology.Cbp'),
          class: 'text-md-right',
        },
      ]
    },
    getSelectedSvTransferProductList() {
      return this.getSvTransferDetails.items || []
    },
    getGrandTotal() {
      let result = this.getSelectedSvTransferProductList.reduce(
        (accumulator, current) => ({
          bv: accumulator.bv + Number(current.bv) * current.quantity,
          sv: accumulator.sv + Number(current.sv) * current.quantity,
          cbp: accumulator.cbp + Number(current.cbp_point) * current.quantity,
        }),
        { bv: 0, sv: 0, cbp: 0 }
      )

      return {
        ...result,
        bv: result.bv.toFixed(2),
        cbp: result.cbp.toFixed(4),
      }
    },
  },
  methods: {
    ...mapActions(['createSvTransferTransaction']),
    async validateAndSubmit() {
      let self = this
      let payload = {
        userToId: this.$helpers.getValue(this.getSvTransferDetails, 'transfereeIbo.id'),
        payCycleId: this.getSvTransferDetails.payCycle,
        items: this.getSelectedSvTransferProductList.map(product => ({
          id: product.id,
          type: product.type,
          quantity: product.quantity,
        })),
      }

      await this.$swal({
        type: 'warning',
        title: this.$t('SvTransfer.Creation.Confirmation.Title'),
        allowOutsideClick: false,
        showLoaderOnConfirm: true,
        showConfirmButton: true,
        showCancelButton: true,
        reverseButtons: true,
        confirmButtonText: self.$t('Common.Continue'),
        cancelButtonText: self.$t('Common.Cancel'),
        html: `
          <table class="m-auto text-left">
            <tr>
              <td>${self.$t('Common.Terminology.Bv')}</td>
              <td class="px-1">:</td>
              <td>${self.getGrandTotal.bv}</td>
            </tr>
            <tr>
              <td>${self.$t('Common.Terminology.Sv')}</td>
              <td class="px-1">:</td>
              <td>${self.getGrandTotal.sv}</td>
            </tr>
            <tr>
              <td>${self.$t('Common.Terminology.Cbp')}</td>
              <td class=px-1>:</td>
              <td>${self.getGrandTotal.cbp}</td>
            </tr>
          </table>
        `,
        preConfirm: async () => {
          let result = await self.createSvTransferTransaction(payload)
          return { response: result }
        },
      }).then(async result => {
        if (!result.dismiss) {
          let config =
            result.value && result.value.response
              ? { title: self.$t('SvTransfer.Creation.CreateSvTransferRecord.Success'), type: 'success', timer: 5000 }
              : {
                  title: self.$t('SvTransfer.Creation.CreateSvTransferRecord.Fail'),
                  text: self.$t('Common.Error.ActionFailure.HelpText'),
                  type: 'error',
                }

          await self.$swal(config)

          if (result.value.response) {
            self.$router.push({ name: 'SvTransferDetails', params: { recordId: result.value.response.id } })
          }
        }
      })
    },
  },
}
</script>
