<template>
  <div>
    <b-row>
      <b-col sm="12">
        <div class="card-title">
          {{ $t('Enrolment.RecurringInformation.Label') }}
        </div>
        <div class="card-text">
          <i>* {{ $t('Common.Payment.CreditCard.BankInfoWarning') }}</i>
        </div>
        <div class="card-body px-0">
          <b-form-group>
            <b-form-radio-group
              id="bank-info-type-1"
              name="bankradio1"
              v-model="recurringInfoBank"
              @input="updateChangeValue"
            >
              <div class="col-12 pr-0">
                <div class="row">
                  <b-col class="col-6 col-sm-3 col-md-4 border py-3 pl-3" v-if="!hideCard">
                    <b-form-radio value="bankInfoCard">
                      <span class="c-pointer">{{ $t('Enrolment.Card.Label') }}</span>
                    </b-form-radio>
                  </b-col>
                  <b-col
                    class="col-6 col-sm-3 col-md-4 py-3 pl-3 border-right border-bottom border-top"
                    v-if="!hideGiro"
                  >
                    <b-form-radio value="bankInfoGiro">
                      <span class="c-pointer">{{ $t('Enrolment.GIRO.Label') }}</span>
                    </b-form-radio>
                  </b-col>
                </div>
              </div>
              <div v-if="recurringInfoBank === 'bankInfoCard'">
                <div v-for="(field, index) in recurringInfoCardFields" :key="index">
                  <b-row class="pt-3 ml-0">
                    <b-col cols="12" md="3" lg="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
                      <label :class="{ required: field.required }">
                        {{ (tLabel = $t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)) }}
                      </label>
                    </b-col>
                    <b-col cols="12" md="7" lg="5" xl="4" class="pl-0 pl-md-3">
                      <template v-if="field.type === 'master-select' && field.identifier === 'card_company'">
                        <b-form-select
                          :options="getOptions(field.identifier)"
                          v-model="card.card_company_id"
                          @input="confirmInfo"
                          data-qa="card-network-select"
                          name="card_network"
                          v-validate="{ required: field.required }"
                          :class="{ 'border-danger': errors.has('card_network') }"
                          :data-vv-as="$t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)"
                        />
                        <b-form-invalid-feedback :state="!errors.has('card_network')">{{
                          errors.first('card_network')
                        }}</b-form-invalid-feedback>
                      </template>
                      <template v-if="field.type === 'master-select' && field.identifier === 'card_type'">
                        <b-form-select
                          :options="getOptions(field.identifier)"
                          v-model="card.card_type_id"
                          @input="confirmInfo"
                          data-qa="card-type-select"
                          name="card_type"
                          v-validate="{ required: field.required }"
                          :class="{ 'border-danger': errors.has('card_type') }"
                          :data-vv-as="$t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)"
                        />
                        <b-form-invalid-feedback :state="!errors.has('card_type')">{{
                          errors.first('card_type')
                        }}</b-form-invalid-feedback>
                      </template>
                      <template
                        v-if="(field.type === 'master-select' || field.type === 'select') && field.key === 'banks'"
                      >
                        <b-form-select
                          v-model="card.country_bank_id"
                          :options="getBankFormSelect"
                          name="issued_bank"
                          @input="confirmInfo"
                          data-qa="issue-bank-select"
                          v-validate="{ required: field.required }"
                          :class="{ 'border-danger': errors.has('issued_bank') }"
                          :data-vv-as="$t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)"
                        />
                        <b-form-invalid-feedback :state="!errors.has('issued_bank')">{{
                          errors.first('issued_bank')
                        }}</b-form-invalid-feedback>
                      </template>
                      <template v-if="field.type === 'input' && field.label === 'Card No'">
                        <b-form-input
                          :type="field.input_type"
                          :placeholder="field.placeholder"
                          v-model="card.card_number"
                          maxlength="16"
                          @change="confirmInfo"
                          class="rounded"
                          data-qa="card-number-input"
                          name="card_number"
                          v-validate="{ required: field.required }"
                          :class="{ 'border-danger': errors.has('card_number') }"
                          :data-vv-as="$t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)"
                        />
                        <b-form-invalid-feedback :state="!errors.has('card_number')">{{
                          errors.first('card_number')
                        }}</b-form-invalid-feedback>
                      </template>
                      <template v-if="field.type === 'input' && field.label === 'Name on Card'">
                        <b-form-input
                          :type="field.input_type"
                          :placeholder="field.placeholder"
                          v-model="card.card_holder_name"
                          @change="confirmInfo"
                          class="rounded"
                          name="name_on_card"
                          v-validate="{ required: field.required }"
                          :class="{ 'border-danger': errors.has('name_on_card') }"
                          :data-vv-as="$t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)"
                        />
                        <b-form-invalid-feedback :state="!errors.has('name_on_card')">{{
                          errors.first('name_on_card')
                        }}</b-form-invalid-feedback>
                      </template>
                      <template v-if="field.type === 'input' && field.label === 'Expiry Date'">
                        <b-form-input
                          :type="field.input_type"
                          :placeholder="field.placeholder"
                          v-model="card.card_expiry_date"
                          @change="confirmInfo"
                          class="rounded"
                          data-qa="expired-date-input"
                          name="expired_date"
                          v-validate="{ required: field.required }"
                          :class="{ 'border-danger': errors.has('expired_date') }"
                          :data-vv-as="$t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)"
                        />
                        <b-form-invalid-feedback :state="!errors.has('expired_date')">{{
                          errors.first('expired_date')
                        }}</b-form-invalid-feedback>
                      </template>
                      <template
                        v-if="
                          (field.type === 'master-select' || field.type === 'select') &&
                            field.identifier === 'rental_card_status'
                        "
                      >
                        <b-form-select
                          v-model="card.rental_card_stauts_id"
                          :options="getOptions(field.identifier)"
                          name="rental_card_status"
                          @input="confirmInfo"
                          data-qa="rental-card-status-select"
                          v-validate="{ required: field.required }"
                          :class="{ 'border-danger': errors.has('rental_card_status') }"
                          :data-vv-as="$t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)"
                        />
                        <b-form-invalid-feedback :state="!errors.has('rental_card_status')">{{
                          errors.first('rental_card_status')
                        }}</b-form-invalid-feedback>
                      </template>
                      <template v-if="field.type === 'file-input'">
                        <b-button
                          variant="outline-primary"
                          size="md"
                          @click="openBankCardUploader(field.reference)"
                          data-qa="upload-card-image-input"
                          :class="{ 'btn-outline-danger': uploadErrors.includes('credit-debit-card') }"
                        >
                          <icon name="spinner" pulse v-if="isLoading('uploading-bank-card')" />
                          {{ isLoading('uploading-bank-card') ? $t('Common.Uploading') : $t('Common.Browse') }}
                        </b-button>
                        <input
                          type="file"
                          v-show="false"
                          :id="field.reference"
                          :ref="field.reference"
                          :accept="getUploadsSettings.client_validate"
                          class="mt-3"
                          @change="startUploadBankCard(field.reference)"
                        />
                        <i
                          class="ml-2"
                          id="popoverBankCardUploadButton-sync"
                          v-if="field.reference === 'enrolRecurringBankCardUploader'"
                        >
                          <icon name="info-circle-icon" />
                        </i>
                        <b-popover
                          :show.sync="uploadCardShow"
                          target="popoverBankCardUploadButton-sync"
                          v-if="field.reference === 'enrolRecurringBankCardUploader'"
                        >
                          {{ $t('Enrolment.CreditCardTooltip.Label') }}
                        </b-popover>
                      </template>
                    </b-col>
                    <b-col
                      offset-md="3"
                      offset-lg="2"
                      lg="9"
                      cols="12"
                      class="pl-0 pl-md-3"
                      v-if="field.type === 'file-input' && field.reference === 'enrolRecurringBankCardUploader'"
                    >
                      <div
                        :id="`card-info-image-${listIndex}`"
                        class="image-lists mt-3 mb-3"
                        v-for="(list, listIndex) in card.credit_card_photocopy"
                        :key="listIndex"
                      >
                        <img :src="list.url" class="col-5 col-md-2 pl-0 object-fit-cover" />
                        <span class="remove c-pointer" @click="removeUploadedCardImageRow(listIndex)">
                          <icon name="cancel-icon" />
                        </span>
                      </div>
                    </b-col>
                    <b-col
                      offset-lg="2"
                      cols="12"
                      lg="9"
                      class="mt-0"
                      v-if="field.type === 'file-input' && field.reference === 'enrolRecurringDocsUploader'"
                    >
                      <div
                        :id="`other-docs-image-${idx}`"
                        class="image-lists mt-3 mb-3"
                        v-for="(list, idx) in card.income_proof"
                        :key="`field-${idx}`"
                      >
                        <span class="remove" @click="removeUploadedCardOthersDocsImageRow(idx)">
                          <icon name="cancel-icon" />
                        </span>
                        <span class="title"> {{ $t('Common.Image.Label') }}- {{ idx + 1 }} </span>
                        <b-tooltip :target="`other-docs-image-${idx}`" placement="left">
                          <b-img :src="list.url" fluid />
                        </b-tooltip>
                      </div>
                    </b-col>
                  </b-row>
                </div>
              </div>
              <div v-if="recurringInfoBank === 'bankInfoGiro'">
                <div>
                  <b-row class="pt-3 ml-0">
                    <b-col sm="12">
                      <template v-for="(field, index) in recurringInfoGiroFields">
                        <div v-if="field.platform === undefined || field.platform === 'eshop'" :key="`field-${index}`">
                          <div v-html="field.value" v-if="field.type === 'textarea'" class="gyro" />
                          <div v-if="field.type == 'link'" class="border d-inline-block m1-2 px-3 py-2 rounded-1">
                            <a :href="field.value" :download="field.label">
                              {{ field.label }}
                              <icon class="ml-2" name="download" />
                            </a>
                          </div>
                        </div>
                      </template>
                    </b-col>
                  </b-row>
                </div>
              </div>
            </b-form-radio-group>
          </b-form-group>
        </div>
      </b-col>
    </b-row>
    <b-row class="py-3 pr-4" v-if="0">
      <b-col class="text-left text-md-right mr-4 mr-md-0">
        <button class="btn btn-primary" @click="confirmInfo" data-qa="e-wallet-setting-confirm-button">
          {{ $t('MyAccount.EwalletSettings.Confirm') }}
        </button>
      </b-col>
    </b-row>
  </div>
</template>
<script>
import { mapActions, mapGetters, mapState } from 'vuex'
import { UploaderMixin, mapMasterDataId } from '@/app/_global/mixins'
import _ from 'lodash'
export default {
  name: 'CardRecurringInfo',
  mixins: [UploaderMixin],
  inject: ['$validator'],
  props: {
    countryId: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      recurringInfoBank: 'bankInfoCard',
      disabledStatus: false,
      uploadCardShow: false,
      hideGiro: false,
      hideCard: false,
      card: {
        card_type_id: '',
        card_company_id: '',
        card_holder_name: '',
        country_bank_id: '',
        card_number: '',
        card_expiry_date: '',
        credit_card_photocopy: [],
        income_proof: [],
        rental_card_stauts_id: '',
      },
      recurringInfoCardFields: [],
      recurringInfoGiroFields: [],
      uploadErrors: [],
    }
  },
  async mounted() {
    this.params.file_type = 'rental_documents'
    var postVar = {
      country_id: this.countryId,
      keys: ['card_type', 'card_company', 'bank_account_type', 'rental_card_status'],
    }
    await this.loadMasterDataKeys(postVar)
    var pv = {
      country_id: this.countryId,
      relations: ['banks'],
    }
    await this.loadCountryRelation(pv)
    await this.uploaderSettings()
    await this.getRecurringCardInfoFields()
    let data = await this.getRentalCardDetails
    let isEmptyObj = _.isEmpty(data)

    if (!isEmptyObj) {
      this.card = data
    }
    if (this.getSelectedRecurringInfoType === 'GIRO') {
      this.recurringInfoBank = 'bankInfoGiro'
    } else {
      this.recurringInfoBank = 'bankInfoCard'
    }
    this.updateChangeValue()
  },
  computed: {
    ...mapMasterDataId({
      FILE_TYPE: {
        fileTypeImageId: 'IMAGE',
        fileTypePdfId: 'PDF',
      },
    }),
    ...mapGetters('enrolment', {
      getCardRecurringInfoFields: 'getCardRecurringInfoFields',
      getBankFormSelect: 'getBankFormSelect',
      getRentalCardDetails: 'getRentalCardDetails',
      getCreditCardPhotoCopy: 'getCreditCardPhotoCopy',
      getSelectedRecurringInfoType: 'getSelectedRecurringInfoType',
      getRentalCardDataPayload: 'getRentalCardDataPayload',
    }),
    ...mapGetters({
      getOptions: 'getMasterDataOptionsByKey',
      isLoading: 'isLoading',
      getUploadsSettings: 'getUploadsSettings',
      getUploads: 'getUploads',
    }),
  },
  methods: {
    ...mapActions('enrolment', ['getDynamicRecurringInfo', 'setRentalCardDetails', 'setSelectedRecurringInfoType']),
    ...mapActions(['loadMasterDataKeys', 'loadCountryRelation']),
    updateChangeValue() {
      if (this.recurringInfoBank === 'bankInfoGiro') {
        this.setSelectedRecurringInfoType('GIRO')
      } else {
        this.setSelectedRecurringInfoType('CARD')
      }
    },
    confirmInfo() {
      let credit_card_photocopy = _.cloneDeep(this.card.credit_card_photocopy)
      let income_proof = _.cloneDeep(this.card.income_proof)
      let payload = {
        card_type_id: this.card.card_type_id,
        card_company_id: this.card.card_company_id,
        country_bank_id: this.card.country_bank_id,
        card_holder_name: this.card.card_holder_name,
        card_number: this.card.card_number,
        card_expiry_date: this.card.card_expiry_date,
        credit_card_photocopy: credit_card_photocopy,
        income_proof: income_proof,
        rental_card_stauts_id: this.card.rental_card_stauts_id,
      }
      this.setRentalCardDetails(payload)
    },
    async getRecurringCardInfoFields() {
      if (this.countryId !== undefined || this.countryId !== null) {
        const countryID = this.countryId
        let query = {
          country_id: countryID,
          types: ['recurring_information'],
        }
        await this.getDynamicRecurringInfo(query)
        if (
          this.getRentalCardDataPayload !== undefined &&
          this.getRentalCardDataPayload !== null &&
          this.getRentalCardDataPayload.recurring_info !== undefined &&
          this.getRentalCardDataPayload.recurring_info.length !== 0
        ) {
          let recurringInfoCard = this.getRentalCardDataPayload.recurring_info
          let card_fields = []
          let giro_fieds = []

          let card_fields_index = this.isFoundInfo(recurringInfoCard, 'CARD')
          let giro_fields_index = this.isFoundInfo(recurringInfoCard, 'GIRO')
          if (card_fields_index === -1) {
            this.hideCard = true
          } else {
            card_fields = recurringInfoCard[card_fields_index].fields
            // Set Selected Recurring Info Type
          }

          if (giro_fields_index === -1) {
            this.hideGiro = true
          } else {
            giro_fieds = recurringInfoCard[1].fields
            // Set Selected Recurring Info Type
          }
          for (var i = 0; i < card_fields.length; i++) {
            if (card_fields[i]['label'] === 'Other document') {
              card_fields[i].reference = 'enrolRecurringDocsUploader'
            } else {
              card_fields[i].reference = 'enrolRecurringBankCardUploader'
            }
          }
          this.recurringInfoCardFields = card_fields
          this.recurringInfoGiroFields = giro_fieds
        }
      }
    },
    isFoundInfo(list, key) {
      var found = -1
      for (let i = 0; i < list.length; i++) {
        key = key.toUpperCase()
        list[i].title = list[i].title.toUpperCase()
        if (list[i].title === key) {
          found = i
        }
      }
      return found
    },
    openBankCardUploader(ref) {
      let value = '#' + ref
      jQuery(value).trigger('click')
    },
    startUploadBankCard(ref) {
      let self = this
      if (ref === 'enrolRecurringBankCardUploader') {
        this.files = this.$refs.enrolRecurringBankCardUploader[0].files
        this.params.file_type = this.getUploadsSettings.file_type
        this.uploader('bank-card').then(() => {
          if (self.getUploads.length > 0) {
            self.getUploads.forEach(item => {
              self.card.credit_card_photocopy.push({
                file_type_id: self.fileTypeImageId,
                name: item.name,
                url: item.link,
              })
              if (self.uploadErrors.indexOf('credit-debit-card') !== -1) {
                self.uploadErrors.splice(self.uploadErrors.indexOf('credit-debit-card'), 1)
              }
            })
            self.confirmInfo()
          }
        })
      } else {
        this.files = this.$refs.enrolRecurringDocsUploader[0].files
        this.params.file_type = this.getUploadsSettings.file_type
        this.uploader('bank-card').then(() => {
          if (this.getUploads > 0) {
            this.getUploads.forEach(item => {
              this.card.income_proof.push({
                file_type_id: this.fileTypeImageId,
                name: item.name,
                url: item.link,
              })
            })
            this.confirmInfo()
          }
        })
      }
      this.$refs[ref][0].value = null
    },
    removeUploadedCardOthersDocsImageRow(index) {
      this.card.income_proof.splice(index, 1)
      this.confirmInfo()
    },
    removeUploadedCardImageRow(index) {
      this.card.credit_card_photocopy.splice(index, 1)
      this.confirmInfo()
    },
    checkUploadedDocumentStatus() {
      this.uploadErrors = []
      if (this.card.credit_card_photocopy.length < 1) {
        this.uploadErrors.push('credit-debit-card')
        this.$swal({
          title: 'Attention !!',
          text: this.$t('RecurringInfo.Required.Msg'),
          type: 'error',
          timer: '5000',
          confirmButtonClass: 'outline-primary',
        })
      }
    },
  },
}
</script>
<style lang="scss">
.gyro {
  ul {
    padding: 0px;

    li {
      padding-bottom: 5px;
    }
  }
}
</style>
