<template>
  <div class="dashboard-panel-element px-0 pt-3 sv-transfer">
    <div v-can:create="'sv-transfer'">
      <b-col>
        <b-button
          variant="primary"
          class="lifted px-3"
          :to="{ name: 'SvTransferProcessStart' }"
          data-qa="svTransfer-svTransferListing-newSvTransfer-btn"
        >
          <span>{{ $t('SvTransfer.Listing.Button.NewSvTransfer') }}</span>
        </b-button>
        <hr />
      </b-col>
    </div>

    <div>
      <b-col>
        <div class="mb-4">
          <b-row>
            <b-col lg="6" class="border-lg-right">
              <b-form-group
                label-cols-md="3"
                class="mb-1 mb-md-3"
                label-class="text-capitalize required"
                :state="!errors.has('Pay Cycle') && null"
                :label="$t('Common.Terminology.PayCycle')"
                :invalid-feedback="errors.first('Pay Cycle')"
              >
                <b-skeleton v-if="isLoading('cwScheduleList')" type="input" />
                <b-select
                  v-else
                  name="Pay Cycle"
                  v-validate="'required'"
                  :options="getPayCycleOptions"
                  v-model="recordFilter.payCycle"
                  :state="!errors.has('Pay Cycle') && null"
                  :data-vv-as="$t('Common.Terminology.PayCycle')"
                  data-qa="svTransfer-svTransferListing-payCycle-select"
                />
              </b-form-group>

              <b-form-group
                label-cols-md="3"
                class="mb-1 mb-md-3"
                :label="$t('Common.IboId')"
                label-class="text-capitalize"
              >
                <b-row class="align-items-center">
                  <b-col class="pr-2">
                    <b-input
                      name="From Member Id"
                      :placeholder="$t('Common.From')"
                      v-model="recordFilter.fromMemberId"
                      data-qa="svTransfer-svTransferListing-fromMemberId-input"
                    />
                  </b-col>
                  <b-col cols="auto" class="px-0">~</b-col>
                  <b-col class="pl-2">
                    <b-input
                      name="To Member Id"
                      :placeholder="$t('Common.To')"
                      v-model="recordFilter.toMemberId"
                      data-qa="svTransfer-svTransferListing-toMemberId-input"
                    />
                  </b-col>
                </b-row>
              </b-form-group>

              <b-form-group
                label-cols-md="3"
                class="mb-1 mb-md-3"
                label-class="text-capitalize"
                :label="$t('Common.Sales.SalesDocumentNo')"
              >
                <b-row class="align-items-center">
                  <b-col class="pr-2">
                    <b-input
                      name="From Sales Document No"
                      :placeholder="$t('Common.From')"
                      v-model="recordFilter.fromSalesDocumentNumber"
                      data-qa="svTransfer-svTransferListing-fromDocumentNumber-input"
                    />
                  </b-col>
                  <b-col cols="auto" class="px-0">~</b-col>
                  <b-col class="pl-2">
                    <b-input
                      name="To Sales Document No"
                      :placeholder="$t('Common.To')"
                      v-model="recordFilter.toSalesDocumentNumber"
                      data-qa="svTransfer-svTransferListing-toDocumentNumber-input"
                    />
                  </b-col>
                </b-row>
              </b-form-group>

              <b-form-group
                label-cols-md="3"
                class="mb-1 mb-md-3"
                label-class="text-capitalize"
                :label="$t('Common.ProductCode')"
              >
                <b-input
                  name="Product Code"
                  v-model="recordFilter.productCode"
                  data-qa="svTransfer-svTransferListing-productCode-input"
                />
              </b-form-group>
            </b-col>

            <b-col lg="6">
              <b-form-group
                label-cols-md="3"
                class="mb-1 mb-md-3"
                :label="$t('Common.Date')"
                label-class="text-capitalize"
                :invalid-feedback="errors.first('From Date')"
                :state="!errors.has('From Date') && null"
              >
                <b-row class="align-items-center">
                  <b-col class="pr-2">
                    <custom-date-picker
                      name="From Date"
                      v-model="recordFilter.fromDate"
                      :placeholder="$t('Common.From')"
                      display-date-format="dd MMM yyyy"
                      :data-vv-as="$t('Common.FromDate')"
                      :has-error="errors.has('From Date')"
                      :disable-date-range="{ from: new Date(Date.now()) }"
                      v-validate="
                        recordFilter.toDate ? `date_format:yyyy-MM-dd|before:${recordFilter.toDate},true` : ''
                      "
                      data-qa="svTransfer-svTransferListing-fromDate-select"
                    />
                  </b-col>
                  <b-col cols="auto" class="px-0">~</b-col>
                  <b-col class="pl-2">
                    <custom-date-picker
                      name="To Date"
                      v-model="recordFilter.toDate"
                      :placeholder="$t('Common.To')"
                      display-date-format="dd MMM yyyy"
                      :wrapper-class="['to-date-picker']"
                      :calendar-class="['calender-container']"
                      :disable-date-range="{ from: new Date(Date.now()), to: new Date(recordFilter.fromDate) }"
                      data-qa="svTransfer-svTransferListing-toDate-select"
                    />
                  </b-col>
                </b-row>
              </b-form-group>

              <b-form-group
                label-cols-md="3"
                class="mb-1 mb-md-3"
                label-class="text-capitalize"
                :label="$t('Common.Sales.TransactionNo')"
              >
                <b-row class="align-items-center">
                  <b-col class="pr-2">
                    <b-input
                      name="From Transaction No"
                      :placeholder="$t('Common.From')"
                      v-model="recordFilter.fromTransactionNumber"
                      data-qa="svTransfer-svTransferListing-fromTransactionNumber-input"
                    />
                  </b-col>
                  <b-col cols="auto" class="px-0">~</b-col>
                  <b-col class="pl-2">
                    <b-input
                      name="To Transaction No"
                      :placeholder="$t('Common.To')"
                      v-model="recordFilter.toTransactionNumber"
                      data-qa="svTransfer-svTransferListing-toTransactionNumber-input"
                    />
                  </b-col>
                </b-row>
              </b-form-group>

              <b-form-group
                label-cols-md="3"
                class="mb-1 mb-md-3"
                label-class="text-capitalize required"
                :state="!errors.has('View As') && null"
                :invalid-feedback="errors.first('View As')"
                :label="$t('SvTransfer.Listing.Filters.ViewAs')"
              >
                <b-select
                  name="View As"
                  v-validate="'required'"
                  v-model="recordFilter.viewAs"
                  :options="getViewAsOptions"
                  :state="!errors.has('View As') && null"
                  :data-vv-as="$t('SvTransfer.Listing.Filters.ViewAs')"
                  data-qa="svTransfer-svTransferListing-viewAs-select"
                />
              </b-form-group>

              <div class="float-right col-md-4 px-0 mt-3 mt-md-0">
                <b-button
                  block
                  variant="primary"
                  @click="searchSvTransferRecord(1)"
                  data-qa="svTransfer-svTransferListing-search-btn"
                >
                  {{ $t('Common.Search') }}
                </b-button>
              </div>
            </b-col>
          </b-row>
        </div>

        <div v-show="recordFilter.payCycle" id="sv-transfer-records-list" class="animated fadeIn">
          <b-table
            hover
            bordered
            show-empty
            stacked="lg"
            responsive=""
            :fields="getTableFields"
            :items="getSvTransferRecords"
            :busy="isLoading('loadingSvTransferList')"
          >
            <template v-slot:empty>
              <div class="text-center my-2">
                <h5 class="text-primary">{{ $t('Common.RecordNotFound') }}</h5>
              </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>

            <template v-slot:cell(user_to)="row">
              <div>[{{ row.value.name }}]</div>
              <div>{{ row.value.old_member_id }}</div>
            </template>

            <template v-slot:cell(user_from)="row">
              <div>[{{ row.value.name }}]</div>
              <div>{{ row.value.old_member_id }}</div>
            </template>

            <template v-slot:cell(details)="row">
              <b-button
                class="p-0"
                variant="link"
                :to="{ name: 'SvTransferDetails', params: { recordId: row.item.id } }"
                data-qa="vTransfer-svTransferListing-transferDetails-btn"
              >
                <span class="d-lg-none pr-1">{{ $t('Common.MoreDetails') }}</span>
                <icon name="next-icon" class="text-primary icon-size-3" />
              </b-button>
            </template>
          </b-table>

          <div v-show="paginationMeta.total" class="eshop">
            <pagination
              name="sv-transfer-listing"
              :total="getPaginationMeta.total"
              class="eshop-pagination text-center"
              :per-page="getPaginationMeta.perPage"
              @getData="searchSvTransferRecord(page)"
              :disabled="isLoading('loadingSvTransferList')"
              data-qa-prefix="svTransfer-svTransferListing"
            />
          </div>
        </div>
      </b-col>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import Pagination from '@/app/_global/components/elements/Pagination'
import CustomDatePicker from '@/elements/common/components/CustomDatePicker'

export default {
  name: 'SvTransferListing',
  components: { CustomDatePicker, Pagination },
  $_veeValidate: {
    validator: 'new',
  },
  props: {
    page: { type: [String, Number], required: true },
  },
  data() {
    return {
      currentView: null,
      recordFilter: {
        payCycle: null,
        fromMemberId: null,
        toMemberId: null,
        productCode: null,
        fromTransactionNumber: null,
        toTransactionNumber: null,
        fromSalesDocumentNumber: null,
        toSalesDocumentNumber: null,
        fromDate: null,
        toDate: null,
        viewAs: null,
      },
      svTransferRecords: [],
      payCycleOptions: [],
      paginationMeta: {
        perPage: 20,
        total: 0,
      },
    }
  },
  watch: {
    getViewAsOptions: {
      handler(options) {
        this.recordFilter.viewAs = options.length
          ? (options.find(data => data.key === 'transferor') || options[0]).value
          : null
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(['isLoading']),
    ...mapMasterDataId({
      SALES_SV_TRANSFER_VIEW_AS: {
        getViewAsOptions: 'options',
        transferorId: 'transferor',
        transfereeId: 'transferee',
      },
    }),
    getTableFields() {
      return [
        {
          key: 'created_at',
          label: this.$t('Common.Sales.CreationDate'),
          formatter: date => moment(date).format('DD MMM YYYY'),
        },
        { key: 'document_no', label: this.$t('Common.Sales.SalesDocumentNo') },
        { key: 'transaction_number', label: this.$t('Common.Sales.TransactionNo') },
        {
          key: 'user_to',
          label: this.$t('SvTransfer.TransferTo'),
          show: this.currentView === this.transferorId,
        },
        {
          key: 'user_from',
          label: this.$t('SvTransfer.Listing.TableHeader.TransferFrom'),
          show: this.currentView === this.transfereeId,
        },
        { key: 'product_sku', label: this.$t('Common.ProductCode') },
        { key: 'total_quantity', label: this.$t('Common.Quantity'), class: ['text-lg-center'] },
        { key: 'total_sv_transferred', label: this.$t('Common.Terminology.Sv'), class: ['text-lg-right'] },
        { key: 'total_bv_transferred', label: this.$t('Common.Terminology.Bv'), class: ['text-lg-right'] },
        { key: 'total_cbp_point_transferred', label: this.$t('Common.Terminology.Cbp'), class: ['text-lg-right'] },
        { key: 'created_by', label: this.$t('SvTransfer.CreatedBy') },
        { key: 'details', label: this.$t('Common.MoreDetails'), class: ['text-lg-center'], thClass: ['text-lg-hide'] },
      ].filter(field => field.show !== false)
    },
    getPaginationMeta() {
      return this.paginationMeta
    },
    getSvTransferRecords() {
      return this.svTransferRecords || []
    },
    getPayCycleOptions() {
      return this.payCycleOptions.map(cycle => ({
        text: cycle.cw_name,
        value: cycle.id,
      }))
    },
  },
  async mounted() {
    await this.loadAvailablePayCycle()
  },
  methods: {
    ...mapActions(['loadCwScheduleList', 'loadSvTransferList']),
    searchSvTransferRecord(currentPage = 1) {
      let self = this

      this.$validator.validate().then(valid => {
        if (valid) {
          let payload = {
            payCycle: self.recordFilter.payCycle,
            fromIbo: self.recordFilter.fromMemberId,
            toIbo: self.recordFilter.toMemberId,
            fromDate: self.recordFilter.fromDate,
            toDate: self.recordFilter.toDate,
            productSku: self.recordFilter.productCode,
            fromDocumentNumber: self.recordFilter.fromSalesDocumentNumber,
            toDocumentNumber: self.recordFilter.toSalesDocumentNumber,
            fromTransactionNumber: self.recordFilter.fromTransactionNumber,
            toTransactionNumber: self.recordFilter.toTransactionNumber,
            viewAs: self.recordFilter.viewAs,
            offset: self.getPaginationMeta.perPage * (currentPage - 1 || 0),
            limit: self.getPaginationMeta.perPage,
          }

          if (currentPage === 1 && Number(self.page) !== 1) {
            self.$router.replace({ name: 'SvTransferListingPaginated', params: { page: 1 } })
          } else {
            self.loadSvTransferList(payload).then(result => {
              self.currentView = self.recordFilter.viewAs
              self.svTransferRecords = self.$helpers.getValue(result, 'data', [])
              self.paginationMeta.total = self.$helpers.getValue(result, 'total', 0)

              if (result) {
                self.$scrollTo('#sv-transfer-records-list', { offset: -70 })
              }
            })
          }
        }
      })
    },
    async loadAvailablePayCycle() {
      let payload = { filter_type: 'current_past', sort: 'id', order: 'desc', limit: 12 }
      await this.loadCwScheduleList(payload).then(cycle => {
        this.payCycleOptions = cycle || []
      })
    },
  },
}
</script>
