<template>
  <order-history>
    <b-row>
      <b-col sm="12">
        <div class="justify-content-between py-3 d-print-none row">
          <b-container fluid class="m-0 p-0">
            <div class="d-block d-md-flex flex-wrap justify-content-between">
              <div class="col-max-width-lg-3 pb-1 flex-fill">
                <b-input-group @keyup.13="searchOrder">
                  <b-form-input
                    class="border-right-0 mv-100"
                    v-model="searchDoc"
                    @keyup.13="searchOrder"
                    :placeholder="$t('OrderHistory.Placeholder.Search')"
                    :title="$t('OrderHistory.EnterToSearch')"
                    :disabled="isLoading('salesListLoading')"
                  />
                  <b-input-group-append>
                    <b-btn
                      v-if="searchDoc !== ''"
                      variant="link"
                      @click="clearSearch"
                      class="border-light border-left-0"
                    >
                      <icon name="clear-icon" class="" />
                    </b-btn>
                    <b-btn
                      class="bg-transparent text-success border-light rounded-0"
                      @click="searchOrder"
                      :disabled="isLoading('salesListLoading') || searchDoc === ''"
                    >
                      <icon name="search" />
                    </b-btn>
                  </b-input-group-append>
                </b-input-group>
              </div>
              <div class="col-max-width-lg-4 pb-1 flex-fill mx-0 mx-md-3 mb-2">
                <b-input-group>
                  <eshop-autocomplete
                    :items="getMemberList"
                    v-model="searchMember"
                    :get-label="item => (item ? item.name : '')"
                    :wait="200"
                    variant="primary"
                    template-name="member"
                    :min-len="3"
                    class="flex-grow-1"
                    :placeholder="$t('Genealogy.SponsorNetworkTree.Search.SearchDownline')"
                    id="myInput"
                    @updateItems="searchMemberListExcludeSelf"
                    @item-selected="searchDownline"
                  />
                  <b-input-group-append>
                    <b-btn
                      v-if="$helpers.isEmpty(searchMember) === false"
                      variant="link"
                      @click="clearMemberSearch"
                      class="border-light border-left-0"
                    >
                      <icon name="clear-icon" class="" />
                    </b-btn>
                    <b-btn
                      class="bg-transparent text-success border-light rounded-0"
                      @click="searchOrder"
                      :disabled="isLoading(['salesListLoading', 'memberTreeLoading']) || searchMember === ''"
                    >
                      <icon name="search" />
                    </b-btn>
                  </b-input-group-append>
                </b-input-group>
              </div>
              <div class="no-wrap flex-fill text-right">
                <b-btn
                  class="bg-primary border-primary rounded-4 px-3"
                  :disabled="isLoading(['salesListLoading', 'evoucherLoading']) || getSalesList.length === 0"
                  @click="printDocument"
                >
                  <icon name="printer-icon" />
                  <span class="mx-1">
                    {{ $t('Common.Print') }}
                  </span>
                </b-btn>
              </div>
            </div>
          </b-container>
        </div>
        <b-row class="overflow-x-auto">
          <b-table
            hover
            bordered
            show-empty
            stacked="lg"
            :fields="getTableFields"
            :items="getSalesList"
            :busy="isLoading('salesListLoading')"
          >
            <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(invoices)="row">
              <b-link v-if="row.value" @click="showInvoice(row.value)">
                {{ row.value.invoice_number }}
              </b-link>
              <span v-else>-</span>
            </template>
            <template v-slot:cell(ibo_id)="row">
              {{ $helpers.getValue(row, 'item.member.user.old_member_id', '-') }}
            </template>
            <template v-slot:cell(ibo_name)="row">
              {{ $helpers.getValue(row, 'item.member.user.name', '-') }}
            </template>
            <template v-slot:cell(pay_cycle)="row">
              {{ $helpers.getValue(row, 'item.cw.cw_name', '-') }}
            </template>
            <template v-slot:cell(type)="row">
              {{ getOrderType(row.item) }}
            </template>
            <template v-slot:cell(total_gmp)="row">
              <span> {{ getCountryById(row.item.country_id).currency.code }}</span>
              <span> {{ $helpers.getCurrencyValue(row.value) }}</span>
            </template>
            <template v-slot:cell(order_status_id)="row">
              <span :class="getOrderStatusClass(row.value)">{{ getOrderStatusName(row.value) }}</span>
            </template>
            <template v-slot:cell(self_collection)="row">
              <span
                :title="
                  getSelfCollectionCode(row.item)
                    .replace('-', '')
                    .replace(' ', '')
                "
                >{{ getSelfCollectionCode(row.item) }}</span
              >
            </template>
            <template v-slot:cell(order_by_for)="row">
              {{ getOrderByFor(row.item) }}
            </template>
            <template v-slot:cell(e_voucher)="row">
              <b-button
                v-if="row.item.evouchers.length > 0 && row.item.order_status_id === completedId"
                variant="primary"
                size="sm"
                @click="goToEvoucher(row.item.id.toString())"
                :disabled="isLoading(['evoucherLoading', 'salesDetailsLoading'])"
              >
                <b-spinner v-if="isProcessing(row.item.id)" small></b-spinner>
                <span v-else>{{ $t('OrderHistory.TableHeader.eVoucher') }}</span>
              </b-button>
              <span v-else>N/A</span>
            </template>
            <template v-slot:cell(show_details)="row">
              <b-button
                v-if="row.item.is_product_exchange === 0"
                @click="showOrderDetail(row.item)"
                variant="link"
                :title="$t('OrderHistory.Detail.ShowOrderDetail')"
                :disabled="isLoading(['evoucherLoading', 'salesDetailsLoading'])"
                class="p-0"
              >
                <span class="d-lg-none pr-1">{{ $t('Common.MoreDetails') }}</span>
                <icon name="next-icon" class="icon-size-3" />
              </b-button>
              <div v-else>N/A</div>
            </template>
          </b-table>
        </b-row>
        <div class="eshop">
          <pagination
            class="eshop-pagination"
            name="orderhistory"
            :total="getSalesListTotalRows"
            :per-page="getOrderHistoryPaginationSize"
            data-qa-prefix="orderHistory-eshopSalesList"
          />
        </div>
      </b-col>
    </b-row>
    <b-modal
      no-close-on-backdrop
      no-close-on-esc
      hide-header
      hide-footer
      id="orderhistorydetail"
      v-model="eshop_orderhistorydetail_modal"
      size="lg"
      ref="orderhistorydetail"
    >
      <div class="row justify-content-between px-4 py-2">
        <div>
          <h4 class="font-weight-bold">
            {{ $t('OrderHistory.Detail.Title') }}
          </h4>
        </div>
        <div>
          <b-btn variant="link" class="border-primary rounded-4 px-3" @click="hideModal">
            &#10005; {{ $t('OrderHistory.Detail.Close') }}
          </b-btn>
        </div>
      </div>
      <div
        v-if="isLoading(['salesDetailsLoading', 'evoucherLoading'])"
        class="vh-25 d-flex justify-content-center align-items-center"
      >
        <icon name="spinner" pulse class="px-3 text-center text-light icon-size-5 py-3" />
      </div>
      <div v-else-if="getErrors('salesDetails')" class="text-center">
        <span class="text-danger font-size-3">
          {{ getErrors('salesDetails').message }}
        </span>
      </div>
      <order-history-details
        v-else
        :show-pay-cycle="!$appSettings.evo.enable"
        :order-data="getSalesDetails"
        :member-data="getMyAccountMemberDetails"
        :preferred-email-id="preferredEmailId"
      />
    </b-modal>
    <b-modal size="sm" ok-only hide-header class="eshop-model" :ok-title="$t('Common.Ok')" ref="no_evoucher" centered>
      <div>{{ $t('OrderHistory.NoEvoucherNotice') }}</div>
    </b-modal>
    <pdf-viewer-modal ref="pdf" :title="invoiceNo" :pdf-link="pdfLink"></pdf-viewer-modal>
  </order-history>
</template>
<script>
import OrderHistory from './OrderHistory'
import { mapGetters, mapActions } from 'vuex'
import orderHistoryDetails from './blocks/OrderHistoryDetails'
import Pagination from '@/app/_global/components/elements/Pagination'
import EshopAutocomplete from '@/app/_global/components/elements/EshopAutocomplete'
import pdfViewerModal from '@/app/_global/components/elements/pdfViewerModal'
import orderHistoryMixin from '../Mixins/orderHistoryMixin'
import moment from 'moment'

export default {
  name: 'EshopSales',
  mixins: [orderHistoryMixin],
  components: {
    pdfViewerModal,
    orderHistoryDetails,
    Pagination,
    EshopAutocomplete,
    OrderHistory,
  },
  data() {
    return {
      invoiceNo: '',
      pdfLink: '',
      eshop_orderhistorydetail_modal: false,
    }
  },
  mounted() {
    this.searchDoc = this.getSearchText.doc
    this.searchMember = this.getSearchText.member ? this.getSearchText.member.user_id : ''
    this.searchMemberListExcludeSelf('')
  },
  methods: {
    ...mapActions(['searchMemberListExcludeSelf']),
    ...mapActions('orderhistory', ['setSearchText']),

    hideModal() {
      this.eshop_orderhistorydetail_modal = false
    },
    searchOrder() {
      this.setSearchText({
        doc: this.searchDoc.trim(),
        member: this.searchMember !== '' ? this.searchMember : { user_id: '' },
      })
    },
    searchDownline(val) {
      this.setSearchText({ doc: this.searchDoc.trim(), member: val })
    },
    clearMemberSearch() {
      this.searchMember = ''
      this.searchOrder()
    },
    showOrderDetail(sales) {
      this.eshop_orderhistorydetail_modal = true
      if (this.getCurrentSaleId !== sales.id) {
        this.selectEvoucherProductsSizes({ sizes: [], evoucher: [] })
      }
      this.setCurrentSaleId(sales.id)
      this.loadSalesDetailsData({ saleId: parseInt(sales.id) })
      if (sales.evouchers !== undefined && sales.evouchers.length > 0) {
        this.loadEvoucherBySale()
      } else {
        this.clearSaleEvouchers()
      }
    },
    async goToEvoucher(saleId) {
      if (this.getCurrentSaleId !== saleId) {
        this.selectEvoucherProductsSizes({ sizes: [], evoucher: [] })
      }
      await this.setCurrentSaleId(saleId)
      await this.loadSalesDetailsData({ saleId: parseInt(saleId) })
      await this.loadEvoucherBySale().then(() => {
        if (!this.getErrors('evoucherBySale')) {
          this.$router.push({
            name: 'OrderHistoryEvoucher',
            params: {
              saleId: saleId,
            },
          })
        } else {
          this.$refs.no_evoucher.show()
        }
      })
    },
    showInvoice(invoice) {
      if (invoice !== null) {
        this.invoiceNo = this.$t('OrderHistory.Detail.eVoucher.TaxInvoiceNo') + ' ' + invoice.invoice_number
        this.pdfLink = ''
        this.downloadEsacInvoice({ invoice_id: invoice.id }).then(response => {
          this.pdfLink = this.getEsacDownloadInvoiceData.download_link
          this.$refs.pdf.show()
        })
      }
    },
    getOrderType(order) {
      let orderType = ''
      if (order.is_esac_redemption === 1) {
        orderType = this.$t('OrderHistory.OrderType.Esac')
      }
      if (order.is_enrollment_sale === 1) {
        orderType = this.$t('OrderHistory.OrderType.Enrolment')
      }
      if (order.is_rental_sale_order === 1) {
        orderType = this.$t('OrderHistory.OrderType.Rental')
      }
      if (order.is_product_exchange === 1) {
        orderType = this.$t('OrderHistory.OrderType.Exchange')
      }
      if (order.is_evoucher === 1) {
        orderType = this.$t('OrderHistory.OrderType.Evoucher')
      }
      if (orderType === '') {
        if (order.sale_type !== undefined && order.sale_type !== null) {
          orderType = order.sale_type
        } else {
          orderType = this.$t('OrderHistory.OrderType.Sales')
        }
      } else {
        if (order.sale_type !== undefined && order.sale_type !== null) {
          orderType = orderType + '/ ' + order.sale_type
        }
      }
      return orderType
    },
  },
  computed: {
    ...mapGetters('orderhistory', ['getSearchText']),
    ...mapGetters(['getSalesList', 'getSalesListTotalRows', 'getCountryById', 'getMemberList']),
    getTableFields() {
      return [
        {
          key: 'transaction_date',
          label: this.$t('OrderHistory.TableHeader.OrderDate'),
          formatter: date => moment(date).format('L'),
        },
        { key: 'document_number', label: this.$t('OrderHistory.TableHeader.OrderNo') },
        { key: 'invoices', label: this.$t('OrderHistory.TableHeader.TaxInvoice') },
        { key: 'ibo_id', label: this.$t('Common.IboId'), show: !this.$appSettings.evo.enable },
        { key: 'ibo_name', label: this.$t('Common.IboName'), show: !this.$appSettings.evo.enable },
        { key: 'pay_cycle', label: this.$t('Common.Terminology.PayCycle'), show: !this.$appSettings.evo.enable },
        { key: 'total_cv', label: this.$t('Common.Terminology.Bv') },
        { key: 'total_sv', label: this.$t('Common.Terminology.Sv'), show: this.$appSettings.evo.enable },
        { key: 'total_cbp_point', label: this.$t('Common.Terminology.Cbp'), show: this.$appSettings.evo.enable },
        { key: 'type', label: this.$t('OrderHistory.TableHeader.Type') },
        { key: 'total_gmp', label: this.$t('Common.Sales.Total'), class: ['text-lg-right'] },
        {
          key: 'order_status',
          label: this.$t('OrderHistory.TableHeader.OrderStatus'),
          formatter: method =>
            this.$helpers.getValue(method, 'translated_title.content', (method && method.title) || '-'),
        },
        {
          key: 'delivery_method',
          label: this.$t('OrderHistory.TableHeader.Shipping'),
          formatter: method =>
            this.$helpers.getValue(method, 'translated_title.content', (method && method.title) || '-'),
        },
        { key: 'self_collection', label: this.$t('OrderHistory.TableHeader.SelfCollectionCode') },
        {
          key: 'delivery_status',
          label: this.$t('OrderHistory.TableHeader.DeliveryStatus'),
          formatter: status => (status || {}).title || '-',
        },
        { key: 'order_by_for', label: this.$t('OrderHistory.TableHeader.OrderByFor') },
        {
          key: 'e_voucher',
          label: this.$t('OrderHistory.TableHeader.eVoucher'),
          class: ['text-lg-center'],
          show: this.$security.policy.can('e-voucher', 'view'),
        },
        {
          key: 'show_details',
          label: this.$t('OrderHistory.Detail.ShowOrderDetail'),
          thClass: ['text-lg-hide'],
          class: ['d-print-none', 'text-lg-center'],
        },
      ].filter(field => field.show !== false)
    },
  },
}
</script>
