<template>
  <div>
    <b-row>
      <b-col sm="12">
        <b-card>
          <card-recurring-info :country-id="getAppLocationCountry.countryId" ref="cardRecurringInfo" />
        </b-card>
      </b-col>
    </b-row>
    <b-row class="mt-2" v-if="getEmploymentDetailsFields !== null">
      <b-col sm="12">
        <b-card>
          <div class="card-title">
            {{ $t('Enrolment.EmploymentDetails.Title') }}
          </div>
          <div class="card-body">
            <component
              v-for="(element, index) in getEmploymentDetailsFields"
              :is="fieldMap.get(element.type)"
              @click="handleClick(element)"
              :key="index"
              variant="outline-primary"
              v-html="
                element.type === 'textarea'
                  ? element.value
                  : $t('Enrolment.Form.' + $helpers.capitalCase(element.label), element.label)
              "
              :data-qa="$helpers.capitalCase(element.label) === 'FillUpHere' ? 'employment-form-btn' : ''"
            >
            </component>
          </div>
        </b-card>
      </b-col>
    </b-row>
    <b-row class="mt-2">
      <b-col sm="12">
        <b-card>
          <div class="card-title required">
            {{ $t('Eshop.label.UploadIC') }}
          </div>
          <div class="card-body">
            <b-row class="pt-3 ml-0">
              <b-col cols="3" lg="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-2">
                <label class="required">
                  {{ $t('Enrolment.UploadSupportDoc.Label') }}
                </label>
              </b-col>
              <b-col cols="7" lg="5" xl="4" class="pl-0 pl-md-3">
                <b-button
                  variant="outline-primary"
                  size="md"
                  @click="openNRICUploader()"
                  data-qa="upload-id-document-btn"
                >
                  <icon name="spinner" pulse v-if="isLoading('uploading-nric')" />
                  {{ isLoading('uploading-nric') ? $t('Common.Uploading') : $t('Common.Browse') }}
                </b-button>
                <input
                  type="file"
                  v-show="false"
                  id="icDocUploder"
                  ref="icDocUploder"
                  :accept="getUploadsSettings.client_validate"
                  class="mt-3"
                  @change="startUploadNRIC()"
                  :placeholder="$t('MyAccount.PersonalInfo.PlaceHolder.ChangePicture')"
                />
              </b-col>
              <b-col offset="3" offset-lg="2" cols="12" lg="9" class="pl-0 pl-md-3">
                <div
                  :id="`nric-image-${index}`"
                  class="image-lists mt-3 mb-3"
                  v-for="(list, index) in this.nricDocs"
                  :key="index"
                >
                  <span class="remove c-pointer" @click="removeUploadedNRICRow(index)" data-qa="remove-id-document-btn">
                    <icon name="cancel-icon" />
                  </span>
                  <span class="title"> {{ $t('Common.Image.Label') }}- {{ index + 1 }} </span>
                  <b-tooltip :target="`nric-image-${index}`" placement="left">
                    <b-img :src="list.url" fluid />
                  </b-tooltip>
                </div>
              </b-col>
            </b-row>
          </div>
        </b-card>
      </b-col>
    </b-row>
    <b-row class="mt-2">
      <b-col sm="12">
        <b-card>
          <div class="card-title">
            {{ $t('Enrolment.SupportingDoc.Label') }}
          </div>
          <div class="card-body">
            <b-row class="pt-3 ml-0">
              <b-col cols="3" lg="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-2">
                <label>{{ $t('Enrolment.UploadSupportDoc.Label') }}</label>
              </b-col>
              <b-col cols="7" lg="5" xl="4" class="pl-0 pl-md-3">
                <b-button
                  variant="outline-primary"
                  size="md"
                  @click="openSupportDocUploader()"
                  data-qa="upload-supporting-document-btn"
                >
                  <icon name="spinner" pulse v-if="isLoading('uploading-sporting-document')" />
                  {{ isLoading('uploading-sporting-document') ? $t('Common.Uploading') : $t('Common.Browse') }}
                </b-button>
                <input
                  type="file"
                  v-show="false"
                  id="enrolSupportDocUploader"
                  ref="enrolSupportDocUploader"
                  multiple
                  :accept="getUploadsSettings.client_validate"
                  class="mt-3"
                  @change="startUploadSupportDoc"
                />
              </b-col>
              <b-col offset="3" offset-lg="2" cols="12" lg="9" class="pl-0 pl-md-3">
                <div
                  :id="`support-image-${index}`"
                  class="image-lists mt-3 mb-3"
                  v-for="(list, index) in this.supportingDocs"
                  :key="index"
                >
                  <span
                    class="remove c-pointer"
                    @click="removeUploadedImageRow(index)"
                    data-qa="remove-supporting-document-btn"
                  >
                    <icon name="cancel-icon" />
                  </span>
                  <span class="title"> {{ $t('Common.Image.Label') }}- {{ index + 1 }} </span>
                  <b-tooltip :target="`support-image-${index}`" placement="left">
                    <b-img :src="list.url" fluid />
                  </b-tooltip>
                </div>
              </b-col>
            </b-row>
          </div>
        </b-card>
      </b-col>
    </b-row>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import { UploaderMixin } from '@/app/_global/mixins'
import cardRecurringInfo from '@/app/_global/components/blocks/cardRecurringInfo'
import _ from 'lodash'

export default {
  name: 'EshopRecurringInfo',
  mixins: [UploaderMixin],
  $_veeValidate: {
    validator: 'new',
  },
  components: {
    cardRecurringInfo,
  },
  data() {
    return {
      disabledStatus: false,
      hideGiro: false,
      supportingDocs: [],
      nricDocs: [],
      passport_number: '',
      fieldMap: new Map([
        ['textarea', 'div'],
        ['link', 'b-button'],
      ]),
    }
  },
  async mounted() {
    await this.uploaderSettings()
    await this.loadBankList(this.getAppLocationCountry.countryId)
    this.nricDocs = await this.getNRICDocDetails
    this.supportingDocs = await this.getSupportingDocDetails
    let query = {
      country_id: this.getSelectedCountry.id,
      membership_type: 'EK Smart',
      types: ['employment_details'],
    }
    await this.getDynamicEmploymentDetails(query)
  },
  computed: {
    ...mapGetters([
      'getLayoutMode',
      'isLoading',
      'getAppLocationCountry',
      'getUploadsSettings',
      'getUploads',
      'getSelectedCountry',
    ]),
    ...mapGetters('enrolment', {
      getSupportingDocDetails: 'getSupportingDocDetails',
      getNRICDocDetails: 'getNRICDocDetails',
      getSelectedRecurringInfoType: 'getSelectedRecurringInfoType',
      getRentalCardDetails: 'getRentalCardDetails',
      getEmploymentDetailsFields: 'getEmploymentDetailsFields',
      getEmploymentFormStatus: 'getEmploymentFormStatus',
    }),
    ...mapGetters('eshop', {
      getCartIsRentalSaleOrder: 'getCartIsRentalSaleOrder',
      getCartHasRental: 'getCartHasRental',
    }),
    ...mapMasterDataId({
      FILE_TYPE: {
        fileTypeImageId: 'IMAGE',
        fileTypePdfId: 'PDF',
      },
    }),
  },
  methods: {
    handleClick(element) {
      if (this.$helpers.capitalCase(element.label) === 'FillUpHere') {
        this.openEmploymentForm(element.value)
      }
    },
    ...mapActions('enrolment', [
      'loadBankList',
      'setSupportingDocDetails',
      'setNRICDocDetails',
      'isValidCardInfoFields',
      'getDynamicEmploymentDetails',
      'updateEmploymentFormStatus',
    ]),
    async preCheckout(next) {
      if (this.getCartHasRental && (await this.isValidCardInfoFields()) === false) {
        await this.$validator.validate().then(result => {
          if (!result) {
            this.$scrollTo('[id="bank-info-type-1"]')
          }
        })
        this.$refs.cardRecurringInfo.checkUploadedDocumentStatus()
      } else if (!this.getEmploymentFormStatus) {
        this.$swal({
          title: this.$t('Enrolment.Form.EmploymentDetail.ErrorMessage.Title'),
          type: 'error',
          timer: '5000',
          confirmButtonClass: 'outline-primary',
        })
      } else if (this.getCartHasRental && this.nricDocs.length === 0) {
        this.$swal({
          title: 'Attention !!',
          text: this.$t('Enrolment.IDUploadRequired.Msg'),
          type: 'error',
          timer: '5000',
          confirmButtonClass: 'outline-primary',
        })
      } else {
        next()
      }
    },
    async openNRICUploader() {
      jQuery('#icDocUploder').trigger('click')
    },
    openSupportDocUploader() {
      jQuery('#enrolSupportDocUploader').trigger('click')
    },
    startUploadNRIC() {
      let self = this
      this.files = this.$refs.icDocUploder.files
      this.params.file_type = this.getUploadsSettings.file_type
      this.uploader('nric').then(() => {
        if (self.getUploads.length > 0) {
          self.getUploads.forEach(item => {
            self.nricDocs.push({
              file_type_id: self.fileTypeImageId,
              name: item.name,
              url: item.link,
            })
          })
          self.setNricDocs()
        }
        self.$refs.icDocUploder.value = null
      })
    },
    startUploadSupportDoc() {
      let self = this
      this.files = this.$refs.enrolSupportDocUploader.files
      this.params.file_type = this.getUploadsSettings.file_type
      this.uploader('sporting-document').then(() => {
        if (self.getUploads.length > 0) {
          self.getUploads.forEach(item => {
            self.supportingDocs.push({
              file_type_id: self.fileTypeImageId,
              name: item.name,
              url: item.link,
            })
          })
          self.setInfo()
        }
        self.$refs.enrolSupportDocUploader.value = null
      })
    },
    setInfo() {
      let docs = _.cloneDeep(this.supportingDocs)
      this.setSupportingDocDetails(docs)
    },
    setNricDocs() {
      let docs = _.cloneDeep(this.nricDocs)
      this.setNRICDocDetails(docs)
    },
    removeUploadedNRICRow(index) {
      this.nricDocs.splice(index, 1)
      this.setNricDocs()
    },
    removeUploadedImageRow(index) {
      this.supportingDocs.splice(index, 1)
      this.setInfo()
    },
    openEmploymentForm(url) {
      window.open(url, '_blank')
      setTimeout(() => {
        this.updateEmploymentFormStatus(true)
      }, 10000)
    },
  },
}
</script>
