<template>
  <tabs-template>
    <div class="eshop" v-if="getEwalletStatus === 1">
      <div v-if="screenState === 'confirm'">
        <div class="row pt-3 mx-3">
          <div class="col">
            <label>
              {{ $t('MyAccount.EwalletSettings.ToContinue', { user: getMyAccountMemberDetails.details.user.name }) }}
            </label>
          </div>
        </div>
        <b-row class="pt-3">
          <b-col class="col-11 col-md-2 col-lg-1 text-center text-md-left ml-4">
            <img
              v-if="getMyAccountMemberDetails.information.gender_id === 15"
              :src="profilePicture"
              class="rounded-circle"
            />
            <img v-else :src="profilePictureFe" class="rounded-circle" />
          </b-col>
          <b-col class="col-12 col-md-2 pt-4 text-center text-md-left">
            <label class="font-weight-bold">
              {{ getMyAccountMemberDetails.details.user.name }}
            </label>
          </b-col>
        </b-row>
        <b-row class="pt-3 mx-3">
          <b-col class="col-12 col-md-6 pr-0 d-md-flex">
            <div class="col-10 col-md-4 col-lg-3 pl-2 pt-md-2">
              <label> {{ $t('Common.MemberID') }} </label>
            </div>
            <b-col class="col-12 col-md-8 pl-2">
              <b-form-input disabled :value="getMyAccountMemberDetails.details.user.old_ibs_user_id" />
            </b-col>
          </b-col>
        </b-row>
        <b-row class="pt-2 mx-3">
          <b-col class="col-12 col-md-6 pr-0 d-md-flex">
            <div class="col-10 col-md-4 col-lg-3 pl-2 pt-md-2">
              <label class="required">
                {{ $t('MyAccount.EwalletSettings.Password') }}
              </label>
            </div>
            <b-col class="col-12 col-md-8 pl-2">
              <b-form-input
                v-model="ewalletSecurityPin"
                name="security pin"
                type="password"
                v-validate="'required|numeric'"
                :class="{ 'is-danger': securityPinInfo.status }"
                @focus.native="resetError"
              />
            </b-col>
          </b-col>
          <b-col class="col-12 col-md-4 pt-2">
            <span v-show="errors.has('security pin')" class="help is-danger">
              {{ checkSecurityPin(errors) }}
            </span>
            <span v-show="securityPinInfo.status" class="help is-danger">
              {{ securityPinInfo.message }}
            </span>
          </b-col>
        </b-row>
      </div>
      <div v-else-if="screenState === 'saveChanges'">
        <b-row class="pt-3 ml-0 ml-md-3">
          <b-col class="col-12 col-md-3 pl-2 pl-md-3">
            <label> {{ $t('MyAccount.EwalletSettings.SecurityPin') }} </label>
          </b-col>
          <b-col class="col-12 col-md-3 pl-2 pl-md-3">
            <button class="btn btn-primary" v-b-modal.confirm_reset_pin>
              {{ $t('MyAccount.EwalletSettings.ResetSecurityPin') }}
            </button>
          </b-col>
        </b-row>
        <!--TODO: temporarily hide-->
        <!--<b-row class="pt-3 ml-0 ml-md-3">-->
        <!--<b-col class="col-12 col-md-3 pl-2 pl-md-3">-->
        <!--<label> {{$t('MyAccount.EwalletSettings.AutoWithdrawal')}} </label>-->
        <!--</b-col>-->
        <!--<b-col class="col-12 col-md-3 pl-2 pl-md-3">-->
        <!--<b-form-radio-group v-model="ewawStatus"-->
        <!--:options="yesNoOpt"-->
        <!--@change="handleChangeEwallet"-->
        <!--name="radioInline">-->
        <!--</b-form-radio-group>-->
        <!--</b-col>-->
        <!--</b-row>-->
        <b-row v-if="autoWithdrawalStatusChanged && autoYesStatus" class="pt-3 ml-0 ml-md-3">
          <b-col class="col-12 col-md-3" />
          <b-col class="col-12 col-md-7 pl-2 pl-md-3">
            <b-form-group>
              <b-form-checkbox-group
                v-model="checkboxStatus"
                name="yesAutoWithdrawal"
                :options="optionsAutoWithdrawal"
                @change="handleCheckBox"
              />
            </b-form-group>
          </b-col>
        </b-row>
      </div>
      <div v-else />
      <b-row class="py-4 mr-3">
        <b-col class="col-12 text-left text-md-right pl-4">
          <button
            class="btn mr-3"
            @click="screenState = 'saveChanges'"
            v-if="screenState === 'resetPin' || screenState === 'confirmPin'"
          >
            Cancel
          </button>
          <button
            class="btn btn-primary"
            v-if="autoWithdrawalStatusChanged"
            :disabled="!selectedAutoWithdrawal && autoYesStatus"
            @click="changeScreenState"
          >
            {{ $t('MyAccount.EwalletSettings.Confirm') }}
          </button>
        </b-col>
      </b-row>
    </div>
    <div v-else class="h-75" />
    <b-modal ref="modalAutoWithdrawal" class="eshop-model" size="sm" hide-header centered ok-only>
      <h5>{{ $t('MyAccount.PersonalInfo.SaveChanges.Success') }}</h5>
    </b-modal>
    <b-modal ref="modalAutoWithdrawalYesNo" class="eshop-model" size="sm" hide-header centered @ok="confirmChangeNo">
      <h5>{{ $t('MyAccount.EwalletSettings.ConfirmChangeNo') }}</h5>
    </b-modal>
    <b-modal ref="modalConfirmReset" class="eshop-model" size="sm" hide-header centered @ok="confirmReset">
      <h5>{{ $t('MyAccount.EwalletSettings.ConfirmResetSecurityPin') }}</h5>
    </b-modal>
    <b-modal ref="modalResetPinResponse" class="eshop-model" ok-only size="sm" hide-header centered>
      <h5 v-if="responseStatusPin">
        {{ $t('MyAccount.EwalletSettings.ResetSecurityPinSuccess') }}
      </h5>
      <h5 v-else>
        {{ $t('MyAccount.PersonalInfo.SaveChanges.Failed') }}
      </h5>
    </b-modal>
    <b-modal
      ref="modalEwalletActivation"
      class="eshop-model"
      size="sm"
      hide-header
      centered
      @ok="activateEwallet"
      @cancel="cancelActivation"
    >
      <h5>{{ $t('MyAccount.PersonalInfo.EwalletSetting.Activation') }}</h5>
    </b-modal>
    <orderPaymentResetPin />
  </tabs-template>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import router from '@/router'
import { EWALLET_ACTIVATION } from '@/config/url-prefix'
import MyAccountTabsTemplate from './templates/MyAccountTabsTemplate'
import orderPaymentResetPin from '@/app/eshop/order/components/blocks/OrderPaymentResetPin'
export default {
  name: 'EwalletSettings',
  components: {
    TabsTemplate: MyAccountTabsTemplate,
    orderPaymentResetPin: orderPaymentResetPin,
  },
  $_veeValidate: {
    validator: 'new',
  },
  data() {
    return {
      profilePicture: '/static/misc/img-default-male.png',
      profilePictureFe: '/static/misc/img-default-female.png',
      screenState: 'saveChanges',
      selectedAutoWithdrawalStatus: 0,
      ewalletSecurityPin: '',
      securityPinInfo: {
        status: false,
        message: '',
      },
      yesNoOpt: [
        { text: this.$t('MyAccount.EwalletSettings.Yes'), value: 1 },
        { text: this.$t('MyAccount.EwalletSettings.No'), value: 0 },
      ],
      optionsAutoWithdrawal: [{ text: this.$t('MyAccount.EwalletSettings.AutoWithdrawalCheck'), value: 'selected' }],
      selectedAutoWithdrawal: false,
      checkboxStatus: '',
      verificationCode: null,
      securityPin: null,
      reSecurityPin: null,
      responseStatusPin: true,
      autoYesStatus: false,
      autoWithdrawalStatusChanged: false,
    }
  },
  mounted() {
    this.loadEwalletBalance().then(resp => {
      if (this.getEwalletStatus === 0) {
        this.$refs.modalEwalletActivation.show()
      }
    })
  },
  methods: {
    ...mapActions([
      'loadEwalletBalance',
      'changeAutoWithdrawalType',
      'validateSecurityPin',
      'validateMobile',
      'resetSecurityPin',
    ]),
    handleChangeEwallet(checked) {
      if (checked === 1) {
        this.autoYesStatus = true
      } else {
        this.autoYesStatus = false
        this.selectedAutoWithdrawal = false
        this.checkboxStatus = ''
      }
      this.autoWithdrawalStatusChanged = this.ewawStatus !== checked
    },
    confirmChangeNo() {
      this.changeAutoWithdrawalType(this.selectedAutoWithdrawalStatus).then(result => {
        if (result) {
          this.autoWithdrawalStatusChanged = false
          this.$refs.modalAutoWithdrawal.show()
        }
      })
    },
    handleCheckBox(checked) {
      if (typeof checked[0] !== 'undefined' && checked[0] === 'selected') {
        this.selectedAutoWithdrawal = true
        this.checkboxStatus = 'selected'
      } else if (checked === 'selected') {
        this.selectedAutoWithdrawal = true
        this.checkboxStatus = 'selected'
      } else {
        this.selectedAutoWithdrawal = false
        this.checkboxStatus = ''
      }
    },
    changeScreenState(scnState = '') {
      if (this.screenState === 'confirm') {
        // Verify ewallet pin
        this.$validator.validate('security pin', this.ewalletSecurityPin).then(valid => {
          if (valid) {
            this.validateSecurityPin(this.ewalletSecurityPin).then(result => {
              if (result) {
                this.screenState = 'saveChanges'
              } else {
                this.securityPinInfo.status = true
                this.securityPinInfo.message = this.$t('EWallet.GlobalWords.PINError')
              }
            })
          }
        })
      } else if (this.screenState === 'saveChanges') {
        // Change auto withdrawal type
        // button reset security pin
        if (this.selectedAutoWithdrawalStatus === 0 && this.ewawStatus === 1) {
          this.$refs.modalAutoWithdrawalYesNo.show()
        } else {
          this.changeAutoWithdrawalType(this.selectedAutoWithdrawalStatus).then(result => {
            if (result) {
              this.autoWithdrawalStatusChanged = false
              this.$refs.modalAutoWithdrawal.show()
            }
          })
        }
      } else if (this.screenState === 'resetPin') {
        this.verifyCode()
      } else {
        if (this.securityPin === this.reSecurityPin) {
          this.$validator.validate('Security Pin', this.securityPin).then(valid => {
            if (valid) {
              this.$refs.modalConfirmReset.show()
            }
          })
        }
      }
    },
    checkSecurityPin(errorObj) {
      if (errorObj.items.length > 0) {
        if (errorObj.items[0].rule === 'numeric') {
          this.securityPinInfo.status = true
          return errorObj.items[0].msg
        } else {
          this.securityPinInfo.status = true
          return errorObj.items[0].msg
        }
      }
    },
    verifyCode() {
      this.$validator.validate('Verification Code', this.verificationCode).then(valid => {
        if (valid) {
          let data = {
            mobile_1_country_code_id: this.getMyAccountMemberDetails.contact_info.mobile_1_country_code_id,
            mobile_1_num: this.getMyAccountMemberDetails.contact_info.mobile_1_num,
            code: this.verificationCode,
            request_type: 'validate',
          }
          this.validateMobile(data).then(result => {
            if (result) {
              this.screenState = 'confirmPin'
            }
          })
        }
      })
    },
    sendVerificationCode() {
      let data = {
        mobile_1_country_code_id: this.getMyAccountMemberDetails.contact_info.mobile_1_country_code_id,
        mobile_1_num: this.getMyAccountMemberDetails.contact_info.mobile_1_num,
      }
      this.validateMobile(data).then(result => {
        if (result) {
          this.screenState = 'resetPin'
        }
      })
    },
    hideModal() {
      this.$refs.modalConfirmReset.hide()
    },
    hideModalResSecPin() {
      this.$refs.modalResetPinResponse.hide()
    },
    confirmReset() {
      let data = {
        security_pin: this.securityPin,
        security_pin_confirmation: this.reSecurityPin,
      }
      this.resetSecurityPin(data).then(result => {
        if (result) {
          this.screenState = 'saveChanges'
        } else {
          this.responseStatusPin = false
        }
        this.$refs.modalResetPinResponse.show()
      })
    },
    resetError() {
      this.securityPinInfo.status = false
      this.securityPinInfo.message = ''
    },
    activateEwallet() {
      router.push(EWALLET_ACTIVATION)
    },
    cancelActivation() {
      router.go(-1)
    },
  },
  computed: {
    ...mapGetters([
      'getMobileVerificationStatus',
      'getMobileVerificationMessage',
      'getMobileConfirmationStatus',
      'getMobileConfirmationMessage',
      'getMyAccountMemberDetails',
      'getEwalletAutowithdrawalStatus',
      'getEwalletStatus',
    ]),
    ewawStatus: {
      get: function() {
        return this.getEwalletAutowithdrawalStatus
      },
      set: function(value) {
        this.selectedAutoWithdrawalStatus = value
      },
    },
  },
  watch: {
    getEwalletAutowithdrawalStatus: {
      handler(val) {
        if (val === 1) {
          this.autoYesStatus = true
          this.selectedAutoWithdrawal = true
          this.selectedAutoWithdrawalStatus = 1
          this.checkboxStatus = 'selected'
        }
      },
      immediate: true,
    },
  },
}
</script>
