<template>
  <order-history>
    <b-row>
      <b-col>
        <b-row class="justify-content-between py-3 d-print-none">
          <b-col cols="12" md="9" lg="7" class="p-0 mb-2">
            <b-row>
              <b-col md="7" xl="6" class="pb-1">
                <b-input-group @keyup.13="searchOrder">
                  <b-form-input
                    class="border-right-0 mw-100"
                    v-model="searchDoc"
                    @keyup.13="searchOrder"
                    :placeholder="$t('OrderHistory.Placeholder.Search')"
                    :title="$t('OrderHistory.EnterToSearch')"
                    :disabled="isLoading('ekSmartSalesListLoading')"
                  />
                  <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('ekSmartSalesListLoading') || searchDoc === ''"
                    >
                      <icon name="search" />
                    </b-btn>
                  </b-input-group-append>
                </b-input-group>
              </b-col>
            </b-row>
          </b-col>
          <b-col class="p-0 text-right">
            <b-btn
              class="bg-primary border-primary rounded-4 px-3"
              :disabled="isLoading(['ekSmartSalesListLoading', 'evoucherLoading']) || getEkSmartSalesList.length === 0"
              @click="printDocument"
            >
              <icon name="printer-icon" />
              <span class="mx-1">
                {{ $t('Common.Print') }}
              </span>
            </b-btn>
          </b-col>
        </b-row>
        <b-row class="overflow-x-auto">
          <b-table
            hover
            bordered
            show-empty
            stacked="lg"
            :fields="getTableFields"
            :items="getEkSmartSalesList"
            :busy="isLoading('ekSmartSalesListLoading')"
          >
            <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(invoice_number)="row">
              <b-link v-if="row.item.invoices !== null" @click="showInvoice(row.item.invoices)">
                {{ row.item.invoices.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(total_gmp)="row">
              <span>
                {{ getCountryById(row.item.country_id).currency.code }}
                {{ $helpers.getCurrencyValue(row.value) }}
              </span>
            </template>
            <template v-slot:cell(type)="row">
              {{ getOrderType(row.item) }}
            </template>
            <template v-slot:cell(order_status_id)="row">
              <span :class="getOrderStatusClass(row.value)">
                {{ getOrderStatusName(row.value) }}
              </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)"
                :disabled="
                  (row.item.evouchers.length === 0 && row.item.order_status_id !== completedId) ||
                    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(application_form)="row">
              <div v-if="row.item.is_rental_recurring === 0">
                <b-btn variant="primary" size="sm" @click="downloadApplicationForm(row.item)">
                  {{ $t('OrderHistory.ApplicationForm.Download') }}
                </b-btn>
              </div>
              <div>N/A</div>
            </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="eksmartorderhistory"
            :total="getEkSmartSalesListTotalRows"
            :per-page="getOrderHistoryPaginationSize"
            data-qa-prefix="orderHistory-ekSmartSalesList"
          />
        </div>
      </b-col>
    </b-row>
    <pdf-viewer-modal :title="modalTitle" :pdf-link="modalLink" ref="pdf" />
    <b-modal
      no-close-on-backdrop
      no-close-on-esc
      hide-header
      hide-footer
      v-model="ek_smart_orderhistorydetail_modal"
      size="lg"
    >
      <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>
  </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 pdfViewerModal from '@/app/_global/components/elements/pdfViewerModal'
import orderHistoryMixin from '../Mixins/orderHistoryMixin'
import moment from 'moment'

export default {
  name: 'EksmartSales',
  mixins: [orderHistoryMixin],
  components: {
    pdfViewerModal,
    orderHistoryDetails,
    Pagination,
    OrderHistory,
  },
  data() {
    return {
      ek_smart_orderhistorydetail_modal: false,
      currentPage: 1,
      modalTitle: '',
      modalLink: '',
    }
  },
  mounted() {
    this.searchDoc = this.getEkSmartSearchText.doc
    this.searchMember = this.getEkSmartSearchText.member.user_id !== '' ? this.getEkSmartSearchText.member : ''
  },
  methods: {
    ...mapActions('orderhistory', ['retrieveApplicationForm', 'setEkSmartSearchText']),
    async downloadApplicationForm(item) {
      let query = {
        sale_id: item.id,
        form_name: 'ek_smart',
        country_code: item.country.code_iso_2,
        lang: 'EN',
        formats: ['pdf'],
        source: 'rental',
      }
      if (await this.retrieveApplicationForm(query)) {
        this.modalLink = this.getApplicationDownloadUrl
        this.modalTitle = 'EK Smart Application Form'
        this.$refs.pdf.show()
      }
    },
    hideModal() {
      this.ek_smart_orderhistorydetail_modal = false
    },
    searchOrder() {
      this.setEkSmartSearchText({
        doc: this.searchDoc.trim(),
        member: this.searchMember !== '' ? this.searchMember : { user_id: '' },
      })
    },
    showOrderDetail(sales) {
      this.ek_smart_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.toString(),
            },
          })
        } else {
          this.$refs.no_evoucher.show()
        }
      })
    },
    showInvoice(invoice) {
      if (invoice !== null) {
        this.modalTitle = this.$t('OrderHistory.Detail.eVoucher.TaxInvoiceNo') + ' ' + invoice.invoice_number
        this.modalLink = ''
        this.downloadEsacInvoice({ invoice_id: invoice.id }).then(response => {
          this.modalLink = 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 && order.is_rental_recurring === 0) {
        orderType = this.$t('OrderHistory.OrderType.Rental')
      }
      if (order.is_rental_sale_order === 1 && order.is_rental_recurring === 1) {
        orderType = this.$t('OrderHistory.OrderType.Recurring')
      }
      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', ['getEkSmartSearchText', 'getApplicationDownloadUrl']),
    ...mapGetters(['getEkSmartSalesList', 'getEkSmartSalesListTotalRows', 'getCountryById']),
    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: 'invoice_number', 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: 'rental_ek_smart_no',
          label: this.$t('OrderHistory.TableHeader.EKSmartOrderNum'),
          formatter: num => num || '-',
        },
        {
          key: 'rental_pre_screen_status',
          label: this.$t('OrderHistory.TableHeader.PreScreeningStatus'),
          formatter: status =>
            this.$helpers.getValue(status, 'translated_title.content', (status && status.title) || '-'),
        },
        {
          key: 'rental_credibility_status',
          label: this.$t('OrderHistory.TableHeader.CredibilityStatus'),
          formatter: status =>
            this.$helpers.getValue(status, 'translated_title.content', (status && status.title) || '-'),
        },
        {
          key: 'order_status',
          label: this.$t('OrderHistory.TableHeader.OrderStatus'),
          formatter: status =>
            this.$helpers.getValue(status, 'translated_title.content', (status && status.title) || '-'),
        },
        {
          key: 'delivery_status',
          label: this.$t('OrderHistory.TableHeader.DeliveryStatus'),
          formatter: status =>
            this.$helpers.getValue(status, 'translated_title.content', (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: 'application_form',
          label: this.$t('OrderHistory.TableHeader.ApplicationForm'),
          class: ['text-lg-center'],
          show: this.$appSettings.order_history.ek_smart.application_form,
        },
        {
          key: 'show_details',
          label: this.$t('OrderHistory.Detail.ShowOrderDetail'),
          class: ['d-print-none', 'text-lg-center'],
          thClass: ['text-lg-hide'],
        },
      ].filter(field => field.show !== false)
    },
  },
}
</script>
