<template>
  <div class="dashboard-panel-element p-0 bg-white">
    <b-container fluid class=" bg-white p-3">
      <b-row>
        <b-col class="pl-2 col-md-5 col-lg-4 col-xl-3">
          <b-input-group class="w-100">
            <b-form-input
              v-model="searchMember"
              :placeholder="$t('Esac.EsacVoucherList.SearchDownline')"
              :disabled="loadingData || isLoading('eSacVoucherListLoading')"
              @keyup.13="searchSponsorDownlineMember"
            />
            <b-input-group-append>
              <div class="d-flex justify-content-between">
                <b-btn
                  class="bg-transparent text-success border-light rounded-0"
                  variant="primary"
                  @click="searchSponsorDownlineMember"
                  :disabled="searchMember === '' || loadingData || isLoading('eSacVoucherListLoading')"
                  v-if="getEsacVoucherListSearchText == ''"
                >
                  <icon name="search" />
                </b-btn>
                <b-btn
                  variant="primary"
                  class="bg-transparent text-success border-light rounded-0"
                  @click="clearSponsorDownlineMember"
                  :disabled="loadingData || isLoading('eSacVoucherListLoading')"
                  v-if="getEsacVoucherListSearchText !== ''"
                >
                  <icon name="undo" />
                </b-btn>
              </div>
            </b-input-group-append>
          </b-input-group>
        </b-col>
        <b-col class="pr-2 col-4 col-md">
          <b-btn
            variant="primary"
            class="px-3 float-right"
            :disabled="getEsacSelectedVoucherCount === 0"
            @click="clickEsacVoucherSelectionRedeem"
          >
            {{ $t('Common.Redeem') }}
          </b-btn>
        </b-col>
      </b-row>
    </b-container>
    <b-col class="px-2 pb-3 overflow-auto">
      <b-table
        hover
        outline
        show-empty
        stacked="lg"
        :fields="tabFields"
        :items="getEsacVoucherData"
        class="border"
        :busy="
          loadingData ||
            isLoading([
              'eSacVoucherListLoading',
              'esacCwScheduleLoading',
              'esacMemberDataLoading',
              'esacCountryRelationLoading',
              'esacStockLoadtionByTransactionLocationLoading',
              'esacProductCategoryListLoading',
            ])
        "
      >
        <template v-slot:empty>
          <div class="text-center text-primary my-2">
            <strong class="h4">{{ $t('Common.RecordNotFound') }}</strong>
          </div>
        </template>
        <template v-slot:table-busy>
          <div class="text-center text-primary my-2">
            <b-spinner class="mx-2" />
            <strong class="h4">{{ $t('Common.Loading') }}</strong>
          </div>
        </template>
        <!--table columns-->
        <template v-slot:cell(index)="row">
          {{ row.index + 1 }}
        </template>
        <template v-slot:cell(voucher_amount)="row">
          <span
            >{{
              getCountryById(row.item.country_id).currency.translated_code ||
                getCountryById(row.item.country_id).currency.code
            }}
            {{ row.item.voucher_value }}</span
          >
        </template>
        <template v-slot:cell(sponsor_child_level)="row">
          {{ row.value > 0 ? $t('Esac.EsacVoucherList.TableItem.SponsorChildLevelFormat', { level: row.value }) : '' }}
        </template>
        <template v-slot:cell(selection)="row">
          <b-form-checkbox
            class="ml-auto mr-auto text-lg-center"
            :checked="isVoucherSelect(row.item.id)"
            @change="toggleEsacVoucherSelection({ id: row.item.id, sender: 'VoucherSelection' })"
            v-if="isVoucherEnable(row.item.id)"
          />
        </template>
      </b-table>
      <div class="eshop">
        <pagination
          v-if="
            !getErrors('esac_voucher_list_loading') && getEsacVoucherListTotalRows > getEsacVoucherListPaginationSize
          "
          class="eshop-pagination pb-2"
          name="esacvoucherlist"
          :total="getEsacVoucherListTotalRows"
          :per-page="getEsacVoucherListPaginationSize"
          data-qa-prefix="esac-voucherListing"
        />
      </div>
    </b-col>
    <b-modal
      ok-only
      hide-header
      centered
      size="sm"
      class="eshop-model"
      ref="member_search_notice"
      @ok="closeMemberSearchNotice"
    >
      <div v-if="searchDataSource.length === 0">
        {{ $t('Report.Notice.MemberSearchEmptyNotice') }}
      </div>
      <div v-else>
        {{ $t('Report.Notice.MemberSearchNotice') }}
      </div>
    </b-modal>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import Pagination from '@/app/_global/components/elements/Pagination'

export default {
  name: 'EsacVoucherList',
  components: {
    Pagination,
  },
  data() {
    return {
      cwScheduleLoaded: false,
      countryRelationLoaded: false,
      productCategoryLoaded: false,
      searchDataSource: [],
      searchMember: '',
      loadingData: true,
      tabFields: [
        { key: 'index', label: this.$t('Common.Table.No') },
        { key: 'voucher_number', label: this.$t('Common.Voucher.VoucherNo') },
        { key: 'esac_voucher_type_name', label: this.$t('Esac.EsacVoucherList.TableHeader.Type') },
        {
          key: 'voucher_amount',
          label: this.$t('Esac.EsacVoucherList.TableHeader.VoucherAmount'),
          class: ['text-lg-right'],
        },
        { key: 'sponsor_child_level', label: this.$t('Esac.EsacVoucherList.TableHeader.SponsorChildLevel') },
        { key: 'ibo_id', label: this.$t('Common.IboId') },
        { key: 'ibo_name', label: this.$t('Common.IboName') },
        { key: 'issued_date', label: this.$t('Common.Voucher.IssuedDate') },
        { key: 'expiry_date', label: this.$t('Common.ExpiryDate') },
        { key: 'selection', label: this.$t('Common.Voucher.Selection') },
      ],
    }
  },
  mounted() {
    this.searchMember = this.getEsacVoucherListSearchText
    this.fetchCountryList()
    this.loadEsacCwScheduleList({ filter_type: 'current' }).then(response => {
      this.cwScheduleLoaded = true
      this.checkLoadingData()
    })
    this.loadEsacMemberData({ user_id: this.getEsacUserId }).then(response => {
      this.loadEsacCountryRelation({ country_id: this.getEsacCountryId }).then(response => {
        let transactionLocationId = this.getEsacTransactionLocationId
        if (transactionLocationId !== null) {
          this.loadEsacStockLocationByTransactionLocation({ location_id: transactionLocationId }).then(response => {
            this.countryRelationLoaded = true
            this.checkLoadingData()
          })
        } else {
          this.countryRelationLoaded = true
          this.checkLoadingData()
        }
      })
    })
    this.loadEsacProductCategoryList().then(response => {
      this.productCategoryLoaded = true
      this.checkLoadingData()
    })
  },
  methods: {
    ...mapActions([
      'fetchCountryList',
      'loadEsacCwScheduleList',
      'loadEsacCountryRelation',
      'loadEsacStockLocationByTransactionLocation',
      'initializeEsacShippingData',
      'loadEsacMemberData',
      'loadEsacProductCategoryList',
      'loadEsacVoucherList',
      'toggleEsacVoucherSelection',
      'clickEsacVoucherSelectionSearchDownline',
      'clickEsacVoucherSelectionClearSearch',
      'clickEsacVoucherSelectionRedeem',
      'setEsacVoucherListSearchText',
    ]),
    checkLoadingData: function() {
      if (this.cwScheduleLoaded && this.countryRelationLoaded && this.productCategoryLoaded) {
        // this.initializeEsacShippingData()
        this.loadEsacVoucherList()
        this.loadingData = false
      }
    },
    searchSponsorDownlineMember: function() {
      let searchText = this.searchMember.toLowerCase()
      this.setEsacVoucherListSearchText(searchText)
    },
    clearSponsorDownlineMember: function() {
      this.searchMember = ''
      this.setEsacVoucherListSearchText('')
    },
    closeMemberSearchNotice() {
      this.$refs.member_search_notice.hide()
    },
    isVoucherSelect(voucherId) {
      let voucher = this.getEsacVoucherData.find(item => item.id === voucherId && item.selected === true)
      return typeof voucher !== 'undefined' && voucher !== null
    },
    isVoucherEnable(voucherId) {
      let voucherData = this.getEsacVoucherData
      let enable = false
      let voucher1 = voucherData.find(item => item.id === voucherId)
      if (typeof voucher1 !== 'undefined' && voucher1 !== null) {
        if (voucher1.enabled) {
          let voucher2 = voucherData.find(item => item.id !== voucherId && item.selected === true)
          if (typeof voucher2 !== 'undefined' && voucher2 !== null) {
            if (voucher1.voucher_type_id === voucher2.voucher_type_id) {
              enable = true
            }
          } else {
            enable = true
          }
        }
      }
      return enable
    },
  },
  computed: {
    ...mapGetters(['isLoading', 'getErrors', 'getCountryById']),
    ...mapGetters([
      'getEsacCountryId',
      'getEsacUserId',
      'getEsacCurrencyCode',
      'getEsacVoucherData',
      'getEsacSelectedVoucherCount',
      'getEsacTransactionLocationId',
      'getEsacVoucherListPaginationSize',
      'getEsacVoucherListTotalRows',
      'getEsacVoucherListSearchText',
    ]),
  },
}
</script>
