<template>
  <div>
    <b-row>
      <b-col cols="12" lg="8" class="border-lg-right">
        <b-row>
          <b-col cols="12">
            <b-form-group
              label-cols-lg="3"
              label-class="text-capitalize required"
              :label="$t('Common.Sales.TransactionDate')"
            >
              <b-input name="Transaction Date" :value="getCurrentDate" readonly />
            </b-form-group>
          </b-col>

          <b-col cols="12">
            <b-form-group
              label-cols-lg="3"
              label-class="text-capitalize required"
              :state="!errors.has('Pay Cycle') && null"
              :label="$t('Common.Terminology.PayCycle')"
              :invalid-feedback="errors.first('Pay Cycle')"
            >
              <b-select
                name="Pay Cycle"
                v-validate="'required'"
                :options="getActivePayCycleList"
                v-model="svTransferForm.payCycle"
                :state="!errors.has('Pay Cycle') && null"
                :data-vv-as="$t('Common.Terminology.PayCycle')"
                data-qa="svTransfer-productSelectionStep-payCycle-select"
              />
            </b-form-group>
          </b-col>

          <b-col cols="12">
            <b-form-group
              label-cols-lg="3"
              label-class="text-capitalize required"
              :label="$t('SvTransfer.TransfereeIboId')"
              :state="!(customError.ibo || errors.has('Transferee Ibo Id')) && null"
              :invalid-feedback="customError.ibo || errors.first('Transferee Ibo Id')"
            >
              <b-input-group @keyup.enter="searchMemberTrigger">
                <b-input-group-append
                  v-if="svTransferForm.transfereeIbo.memberId"
                  class="d-none d-md-flex align-items-center px-3 m-0 border border-right-0 bg-gray-200"
                >
                  {{ svTransferForm.transfereeIbo.memberId }}
                </b-input-group-append>
                <b-form-input
                  trim
                  autocomplete="off"
                  v-validate="'required'"
                  name="Transferee Ibo Id"
                  v-model="svTransferForm.transfereeIbo.name"
                  :data-vv-as="$t('SvTransfer.TransfereeIboId')"
                  :readonly="svTransferForm.transfereeIbo.id !== null"
                  :state="!(customError.ibo || errors.has('Transferee Ibo Id')) && null"
                  data-qa="svTransfer-productSelectionStep-transfereeIboId-input"
                />
                <b-input-group-prepend>
                  <b-button
                    class="border-left-0"
                    @click="searchMemberTrigger()"
                    :variant="svTransferForm.transfereeIbo.id === null ? 'primary' : 'outline-light'"
                    :disabled="isLoading('memberListLoading') || svTransferForm.transfereeIbo.name === ''"
                  >
                    <b-spinner v-if="isLoading('memberListLoading')" small />
                    <icon v-else-if="svTransferForm.transfereeIbo.id !== null" name="clear-icon" />
                    <icon v-else name="search" class="text-white" />
                  </b-button>
                </b-input-group-prepend>
              </b-input-group>
            </b-form-group>
          </b-col>
        </b-row>
      </b-col>

      <b-col cols="12" lg="4">
        <hr class="my-2 d-lg-none" />
        <b-row>
          <b-col cols="12" md="4" lg="12">
            <b-form-group label-cols-lg="4" :label="$t('Common.Terminology.TotalBV')">
              <b-input
                readonly
                name="Total Bv"
                class="text-right"
                :value="getSalesSvTransferMeta.total_bv_transferable || '0.00'"
              />
            </b-form-group>
          </b-col>

          <b-col cols="12" md="4" lg="12">
            <b-form-group label-cols-lg="4" :label="$t('Common.Terminology.TotalSv')">
              <b-input
                readonly
                name="Total Sv"
                class="text-right"
                :value="getSalesSvTransferMeta.total_sv_transferable || '0'"
              />
            </b-form-group>
          </b-col>

          <b-col cols="12" md="4" lg="12">
            <b-form-group label-cols-lg="4" :label="$t('Common.Terminology.TotalCbp')">
              <b-input
                readonly
                name="Total Cbp"
                class="text-right"
                :value="getSalesSvTransferMeta.total_cbp_point_transferable || '0.0000'"
              />
            </b-form-group>
          </b-col>
        </b-row>
      </b-col>
    </b-row>

    <b-row v-if="svTransferForm.payCycle" class="animated fadeIn">
      <b-col>
        <div class="border-top-double border-medium mb-3" />

        <div v-if="isLoading('loadingSvTransferProductList')">
          <b-skeleton-img no-aspect height="100px" />
        </div>

        <div v-else-if="getSvTransferProductList.length === 0" class="text-danger">
          {{ $t('SvTransfer.Creation.TransferableProductNotFound') }}
        </div>

        <div v-else>
          <div class="col-12 col-md-6 col-lg-4 px-0 ml-auto mb-3">
            <text-search-bar v-model="productFilterText" data-qa-prefix="svTransfer-productSelectionStep" />
          </div>

          <div v-for="(product, index) in getSvTransferProductList" :key="index" class="mb-2">
            <sv-transfer-product-card
              v-show="
                product.sku.toLowerCase().includes(productFilterText.toLowerCase()) ||
                  product.name.toLowerCase().includes(productFilterText.toLowerCase())
              "
              class="animated fadeInUp"
              :product-details="product"
              :quantity="getSvTransferProductCartQuantity(product.id)"
              data-qa-prefix="svTransfer-productSelectionStep"
              ref="svTransferProductCard"
            />
          </div>
        </div>
      </b-col>
    </b-row>
  </div>
</template>

<script>
import moment from 'moment'
import { mapActions, mapGetters } from 'vuex'
import TextSearchBar from '@/app/_global/components/elements/TextSearchBar'
import SvTransferProductCard from '@/app/sv-transfer/_global/components/blocks/SvTransferProductCard'

export default {
  name: 'SvTransferProductSelectionStep',
  components: { TextSearchBar, SvTransferProductCard },
  $_veeValidate: {
    validator: 'new',
  },
  data() {
    return {
      productFilterText: '',
      payCycleOptions: [],
      svTransferForm: {
        payCycle: null,
        transfereeIbo: {
          id: null,
          name: '',
          memberId: null,
        },
      },
      SalesSvTransferDetails: {},
      customError: {
        ibo: '',
      },
    }
  },
  watch: {
    'svTransferForm.payCycle': {
      handler(payCycleId) {
        this.loadAvailableProductTransferDetails(payCycleId)
      },
    },
    'svTransferForm.transfereeIbo.name': {
      handler() {
        this.customError.ibo = ''
      },
    },
  },
  computed: {
    ...mapGetters(['isLoading', 'getSvTransferProductCartQuantity', 'getSvTransferDetails']),
    getCurrentDate() {
      return moment().format('DD MMM YYYY')
    },
    getActivePayCycleList() {
      return this.payCycleOptions.map(cycle => ({
        text: cycle.cw_name,
        value: cycle.id,
      }))
    },
    getSalesSvTransferMeta() {
      return this.SalesSvTransferDetails || {}
    },
    getSvTransferProductList() {
      return this.getSalesSvTransferMeta.data || []
    },
  },
  async mounted() {
    if (this.getSvTransferDetails.validated) {
      this.svTransferForm = {
        payCycle: this.getSvTransferDetails.payCycle,
        transfereeIbo: { ...this.getSvTransferDetails.transfereeIbo },
      }
    }
    await this.loadAvailablePayCycle()
  },
  methods: {
    ...mapActions([
      'loadCwScheduleList',
      'loadSalesSvTransferProductMeta',
      'loadMemberList',
      'updateSvTransferFormData',
    ]),
    async loadAvailablePayCycle() {
      await this.loadCwScheduleList({ filter_type: 'current', sort: 'id', order: 'desc' }).then(cycle => {
        this.payCycleOptions = cycle || []
      })
    },
    loadAvailableProductTransferDetails(payCycleId) {
      this.loadSalesSvTransferProductMeta(payCycleId).then(result => {
        this.SalesSvTransferDetails = { ...(result || {}) }
      })
    },
    searchMemberTrigger() {
      if (this.svTransferForm.transfereeIbo.id !== null) {
        this.customError.ibo = ''
        this.svTransferForm.transfereeIbo = { id: null, name: '', memberId: '' }
      } else {
        this.searchMember()
      }
    },
    async searchMember() {
      this.customError.ibo = ''
      if (this.svTransferForm.transfereeIbo.name) {
        let self = this
        let payload = {
          limit: 1,
          minimal: true,
          includeSelf: false,
          exactText: this.svTransferForm.transfereeIbo.name,
        }

        await this.loadMemberList(payload).then(result => {
          result = (result && result[0]) || {}
          if (result.hasOwnProperty('old_member_id')) {
            self.svTransferForm.transfereeIbo = {
              id: result.user_id,
              name: result.name,
              memberId: result.old_member_id,
            }
            return true
          } else {
            self.customError.ibo = this.$t('Common.Genealogy.MemberSearch.Fail')
            return false
          }
        })
      }
    },
    scrollTo(target) {
      if (target) {
        this.$scrollTo(target, { offset: -140 })
      }
    },
    async validateAndSubmit() {
      let self = this

      return await this.$validator.validate().then(async valid => {
        if (valid) {
          if (this.svTransferForm.transfereeIbo.id === null) {
            await self.searchMember()
          }

          if (self.customError.ibo === '') {
            let transferableProductList = []

            Object.assign([], self.$refs['svTransferProductCard']).forEach(el => {
              let productData = el.getData()

              if (productData.quantity > 0) {
                transferableProductList.push(productData)
              }
            })

            if (transferableProductList.length) {
              let payload = {
                transfereeIbo: this.svTransferForm.transfereeIbo,
                payCycle: this.svTransferForm.payCycle,
                items: [...transferableProductList],
                validated: true,
              }

              self.updateSvTransferFormData(payload)
              return true
            } else {
              self.$swal({
                title: this.$t('SvTransfer.Creation.Error.NoTransferProductSelected', { limit: 1 }),
                type: 'error',
              })
            }
          } else {
            self.scrollTo(`[name='Transferee Ibo Id']`)
          }
        } else {
          self.scrollTo(`[name='${self.errors.items[0].field}']`)
        }
        return false
      })
    },
  },
}
</script>
