<template>
  <div class="content">
    <div class="enrol-fifth-step-wrapper">
      <enrol-grid-1>
        <template slot="full-content">
          <div class="card w-100">
            <div class="card-body">
              <div class="enrol-fifth-step" id="enrol-fifth-step-form">
                <div class="enrol-main-title">
                  {{ $t('Enrolment.PlacementMethod.Title') }}
                </div>
                <!--Enrol Section-->
                <div class="enrol-section">
                  <div class="enrol-section-content text-capitalize">
                    <b-container fluid>
                      <b-row>
                        <b-col lg="8" sm="12">
                          <b-form-row class="enrol-controls-holder">
                            <b-col cols="12" class="enrol-section-label">
                              <label class="required">
                                {{ $t('Enrolment.Sponsor.Label') }}
                              </label>
                            </b-col>
                            <b-col class="enrol-section-controls col-10 col-md-8">
                              <search-sponsor-input-group
                                data-vv-name="sponsor"
                                reset-error-name="saveTempEnrolment"
                                @undisabled="resetPlacement(), clearDontKnowSponsor(enrolmentData.global)"
                                :class="{ animated: true, flash: highlightSponsor }"
                                @sponsorChanged=";(highlightSponsor = false), resetError('saveTempEnrolment')"
                                :sponsor-required="enrolmentData.on_behalf_enrolment === 1"
                                :enrolment-data="enrolmentData"
                                v-validate="'required'"
                              />
                            </b-col>
                            <b-col>
                              <icon
                                class="text-info-green"
                                name="tick-icon"
                                v-if="enrolmentData.sponsor_user_id !== ''"
                              />
                            </b-col>
                          </b-form-row>
                          <b-form-row class="enrol-controls-holder" v-if="!getErrorsState('saveTempEnrolment')">
                            <b-col cols="12" class="mt-2 enrol-section-controls-errors">
                              <h6
                                class="help invalid validated"
                                v-for="(error, index) in getErrorsBreakup('saveTempEnrolment')"
                                :key="index"
                              >
                                {{ Array.isArray(error) ? error.toString() : error }}
                              </h6>
                            </b-col>
                          </b-form-row>
                          <b-form-row v-if="enrolmentData.global === 1 && enrolmentData.on_behalf_enrolment === 0">
                            <b-col>
                              <b-form-checkbox
                                id="checkbox1"
                                v-model="enrolmentData.without_sponsor"
                                :value="1"
                                @input="resetError('saveTempEnrolment'), controlInputs('withoutSponsor')"
                                :unchecked-value="0"
                              >
                                {{ $t('Enrolment.DoNotKnowMySponsor.Text') }}
                              </b-form-checkbox>
                              <h6 class="text-info-green" v-if="enrolmentData.without_sponsor === 1">
                                {{ $t('Enrolment.Form.Sponsor.Info') }}
                              </h6>
                            </b-col>
                          </b-form-row>
                          <b-form-row>
                            <b-col>
                              <ic-passport-cross-sponsoring-validation
                                v-if="enrolmentData.without_sponsor !== 1"
                                count="1"
                                :sponsor-member-ibo="getSponsorDetails.member_id"
                                :member-id-passport-number="enrolmentData.member_data.details.ic_passport_number"
                                :sponsor-id="getSponsorDetails.user_id"
                              />
                            </b-col>
                          </b-form-row>
                          <b-form-row class="enrol-controls-holder">
                            <b-col cols="12" class="enrol-section-label">
                              <label class="required">
                                {{ $t('Enrolment.Placement.Label') }}
                              </label>
                            </b-col>
                            <b-col class="enrol-section-controls col-5 col-md-2 mb-2 mb-md-0">
                              <b-form-select
                                size="md"
                                @input="resetError('get_member_failed'), controlInputs('position')"
                                :disabled="
                                  enrolmentData.without_sponsor === 1 ||
                                    (enrolmentData.placement.placement_member_user_id !== '' &&
                                      !enrolmentData.placement.placement_same_as_sponsor)
                                "
                                v-model="enrolmentData.placement.placement_position"
                                :options="placementOptions"
                              />
                            </b-col>
                            <b-col cols="12" class="enrol-section-controls-errors">
                              <field-errors
                                :cerrors="errors"
                                :cfields="fields"
                                :name="$t('Enrolment.MemberId.Label')"
                              />
                            </b-col>
                            <b-col
                              cols="12"
                              class="enrol-section-controls-errors"
                              v-if="!getErrorsState('get_member_failed')"
                            >
                              <h6
                                class="help invalid validated"
                                v-for="(error, index) in getErrorsBreakup('get_member_failed')"
                                :key="index"
                              >
                                {{ Array.isArray(error) ? error.toString() : error }}
                              </h6>
                            </b-col>
                          </b-form-row>
                        </b-col>
                        <b-col cols="12" class="mt-5">
                          <b-row>
                            <b-col class="enrol-placement-info text-left">
                              <h6>{{ $t('Enrolment.PlacementInfo1.Label') }}</h6>
                              <h6>{{ $t('Enrolment.PlacementInfo2.Label') }}</h6>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>
                    </b-container>
                  </div>
                </div>
                <!--End Contact Details-->
              </div>
              <enrolment-stepped-footer-navigation
                :enrolment-data="enrolmentData"
                :next-action="nextAction"
                :prev-action="prevAction"
                :previous="previous"
                :validate-and-save="validateAndSave"
                :validate-status="enrolmentData.step_states['personal-data']"
                :next="next"
              />
            </div>
          </div>
        </template>
      </enrol-grid-1>
    </div>
  </div>
</template>
<script>
import enrolGrid1 from '@/app/enrolment/_global/components/templates/layouts/enrol-grid-1'
import searchSponsorInputGroup from '@/app/enrolment/_global/components/elements/searchSponsorInputGroup'
import EnrolmentSteppedFooterNavigation from '@/app/enrolment/_global/components/elements/enrolmentSteppedfooterNavigation'
import IcPassportCrossSponsoringValidation from '@/app/_global/components/elements/icPassportCrossSponsoringValidation'
import { mapActions, mapGetters, mapMutations } from 'vuex'

export default {
  name: 'EnrolmentPlacementSelectionPage',
  components: {
    enrolGrid1,
    EnrolmentSteppedFooterNavigation,
    searchSponsorInputGroup,
    IcPassportCrossSponsoringValidation,
  },
  $_veeValidate: {
    validator: 'new',
  },
  props: {
    enrolmentData: {
      type: Object,
      required: true,
    },
    previous: {
      type: String,
    },
    next: {
      type: String,
    },
    prevAction: {
      type: Function,
    },
    nextAction: {
      type: Function,
    },
  },
  data() {
    return {
      placementOptions: [
        { value: 0, text: 'Auto' },
        { value: 1, text: 'Left' },
        { value: 2, text: 'Right' },
      ],
      highlightSponsor: false,
    }
  },
  watch: {
    'enrolmentData.sponsor_member_id'(value) {
      if (value !== '') {
        this.initiateIcPassportValidation()
      } else {
        this.resetClassicCrossSponsoringVerification()
      }
    },
  },
  computed: {
    ...mapGetters(['getErrorsState', 'getErrorsBreakup', 'isLoading', 'getIcPassportValidationPassed']),
    ...mapGetters('enrolment', ['getLoggedInSponsor', 'getPlacementMemberDetails', 'getSponsorDetails']),
  },
  mounted() {
    this.initiateIcPassportValidation()
  },
  methods: {
    ...mapActions(['resetError', 'setAutoValidationTrigger']),
    ...mapActions('enrolment', ['getMember', 'postTempEnrolment']),
    ...mapMutations({
      resetClassicCrossSponsoringVerification: 'RESET_CLASSIC_CROSS_SPONSORING_VERIFICATION',
    }),
    async verifyPlacementMemberByMemberID() {
      if (this.enrolmentData.without_sponsor === 0 && this.enrolmentData.sponsor_member_id === '') {
        this.highlightSponsor = true
      } else {
        let query = {
          self: 0,
          placementMember: 1,
          mixed_filters: 5,
          sponsor_id: this.enrolmentData.sponsor_user_id,
          search_text: this.enrolmentData.placement.placement_member_id,
          limit: 1,
          minimal: true,
        }
        await this.getMember(query).then(() => {
          if (Object.keys(this.getPlacementMemberDetails).length > 0) {
            this.enrolmentData.placement.placement_member_name = this.getPlacementMemberDetails.name
            this.enrolmentData.placement.placement_member_user_id = this.getPlacementMemberDetails.user_id
            this.enrolmentData.placement.placement_member_id = this.getPlacementMemberDetails.member_id
          }
        })
      }
    },
    resetPlacement() {
      this.enrolmentData.placement.placement_member_id = ''
      this.enrolmentData.placement.placement_member_name = ''
      this.enrolmentData.placement.placement_position = 0
      this.enrolmentData.placement.placement_member_user_id = ''
      this.enrolmentData.placement.placement_same_as_sponsor = 0
    },
    controlInputs(name) {
      if (name === 'position') {
        if (this.enrolmentData.placement.placement_position === 0) {
          if (!this.enrolmentData.placement.placement_same_as_sponsor) {
            this.enrolmentData.placement.placement_member_id = ''
            this.enrolmentData.placement.placement_member_name = ''
          }
        }
      }
      if (name === 'withoutSponsor') {
        this.enrolmentData.sponsor_name = ''
        this.enrolmentData.sponsor_member_id = ''
        this.enrolmentData.sponsor_user_id = ''
        this.resetPlacement()
        this.resetError('member_placement_verify_failed')
      }
      if (name === 'same_as_sponsor') {
        if (this.enrolmentData.placement.placement_same_as_sponsor) {
          if (this.enrolmentData.sponsor_user_id !== '') {
            this.enrolmentData.placement.placement_member_id = this.enrolmentData.sponsor_member_id
            this.enrolmentData.placement.placement_member_name = this.enrolmentData.sponsor_name
            this.enrolmentData.placement.placement_member_user_id = this.enrolmentData.sponsor_user_id
          }
        } else {
          this.resetPlacement()
        }
      }
    },
    initiateIcPassportValidation() {
      if (this.enrolmentData.without_sponsor === 0) {
        if (this.enrolmentData.member_data.details.ic_passport_number !== '') {
          this.setAutoValidationTrigger()
        }
      }
    },
    clearDontKnowSponsor(value) {
      if (value) {
        this.enrolmentData.without_sponsor = 0
      }
    },
    async validateAndSave() {
      if (
        this.enrolmentData.placement.placement_member_user_id !== '' &&
        this.enrolmentData.placement.placement_position === 0
      ) {
        this.enrolmentData.step_states.placement = true
      } else {
        return await this.postTempEnrolment(this.enrolmentData)
          .then(() => {
            this.highlightSponsor = false
            this.enrolmentData.step_states.placement = true
          })
          .catch(async e => {
            this.highlightSponsor = true
            this.enrolmentData.step_states.placement = false
            throw e
          })
      }
    },
  },
}
</script>
